mirror: 上游快照导入

This commit is contained in:
gitea committed 2026-11-30 09:52:36 +08:00
commit 7475ccb467
86 files changed
+3213

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net472</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<AssemblyVersion>0.0.6.0</AssemblyVersion>
</PropertyGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="move /Y $(TargetPath) $(OutDir)CSharpManager.bin" />
</Target>
<ItemGroup>
<ProjectReference Include="..\CSharpModBase\CSharpModBase.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.5" />
</ItemGroup>
</Project>
+175
View File
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using CSharpModBase;
using CSharpModBase.Input;
using Mono.Cecil;
namespace CSharpManager
{
public class CSharpModManager
{
static string? LoadingModName { get; set; }
public List<ICSharpMod> LoadedMods { get; } = new();
public InputManager InputManager { get; } = new();
public bool Develop { get; set; }
private Thread? loopThread;
static CSharpModManager()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += AssemblyResolve;
currentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
}
private static Assembly? TryLoadDll(string path)
{
if (File.Exists(path))
{
return Assembly.LoadFrom(path);
}
return null;
}
private static Assembly? AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
if (LoadingModName == null)
{
return null;
}
string dllName = $"{new AssemblyName(args.Name).Name}.dll";
return TryLoadDll(Path.Combine(Common.ModDir, LoadingModName, dllName)) ??
TryLoadDll(Path.Combine(Common.ModDir, "Common", dllName)) ??
TryLoadDll(Path.Combine(Common.LoaderDir, dllName));
}
catch (Exception e)
{
Log.Error($"Load assembly {args.Name} failed:");
Log.Error(e);
}
return Assembly.Load(args.Name);
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.Error($"UnhandledException:");
Log.Error((Exception)e.ExceptionObject);
}
private static void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Log.Error($"UnobservedTaskException:");
Log.Error(e.Exception);
}
public CSharpModManager()
{
Utils.InitInputManager(InputManager);
// load config from ini
Ini iniFile = new(Path.Combine(Common.LoaderDir, "b1cs.ini"));
Develop = iniFile.GetValue("Develop", "Settings", "1").Trim() == "1";
Log.Debug($"Develop: {Develop}");
}
public void LoadMods()
{
LoadedMods.Clear();
if (!Directory.Exists(Common.ModDir))
{
Log.Error($"Mod dir {Common.ModDir} not exists");
return;
}
string[] dirs = Directory.GetDirectories(Common.ModDir);
Type ICSharpModType = typeof(ICSharpMod);
foreach (var dir in dirs)
{
LoadingModName = Path.GetFileName(dir);
string dllPath = Path.Combine(dir, $"{LoadingModName}.dll");
if (!File.Exists(dllPath)) continue;
try
{
Log.Debug($"======== Loading {dllPath} ========");
Assembly assembly;
if (Develop)
{
using var assemblyDef = AssemblyDefinition.ReadAssembly(dllPath);
assemblyDef.Name.Name += DateTime.Now.ToString("_yyyyMMdd_HHmmssffff");
using MemoryStream stream = new();
assemblyDef.Write(stream);
assembly = Assembly.Load(stream.GetBuffer());
}
else
{
assembly = Assembly.LoadFrom(dllPath);
}
foreach (Type type in assembly.GetTypes())
{
if (ICSharpModType.IsAssignableFrom(type))
{
Log.Debug($"Found ICSharpMod: {type}");
if (Activator.CreateInstance(type) is ICSharpMod mod)
{
mod.Init();
LoadedMods.Add(mod);
Log.Debug($"Loaded mod {mod.Name} {mod.Version}");
}
}
}
LoadingModName = null;
}
catch (Exception e)
{
Log.Error($"Load {dllPath} failed:");
Log.Error(e);
}
}
}
public void ReloadMods()
{
Log.Debug("ReloadMods");
InputManager.Clear();
foreach (var mod in LoadedMods)
{
try
{
mod.DeInit();
}
catch (Exception e)
{
Log.Error($"DeInit {mod.Name} failed:");
Log.Error(e);
}
}
LoadMods();
}
public void StartLoop()
{
InputManager.RegisterBuiltinKeyBind(ModifierKeys.Control, Key.F5, ReloadMods);
loopThread = new Thread(Loop)
{
// IsBackground = true,
};
loopThread.Start();
}
private void Loop()
{
while (true)
{
InputManager.Update();
Thread.Sleep(10); // 10ms
}
}
}
}
+208
View File
@@ -0,0 +1,208 @@
// https://gist.github.com/Larry57/5725301
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
public class Ini
{
Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
string file;
/// <summary>
/// Initialize an INI file
/// Load it if it exists
/// </summary>
/// <param name="file">Full path where the INI file has to be read from or written to</param>
public Ini(string file)
{
this.file = file;
if (!File.Exists(file))
return;
Load();
}
/// <summary>
/// Load the INI file content
/// </summary>
public void Load()
{
var txt = File.ReadAllText(file);
Dictionary<string, string> currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[""] = currentSection;
foreach (var l in txt.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select((t, i) => new
{
idx = i,
text = t.Trim()
}))
// .Where(t => !string.IsNullOrWhiteSpace(t) && !t.StartsWith(";")))
{
var line = l.text;
if (line.StartsWith(";") || string.IsNullOrWhiteSpace(line))
{
currentSection.Add(";" + l.idx.ToString(), line);
continue;
}
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[line.Substring(1, line.Length - 2)] = currentSection;
continue;
}
var idx = line.IndexOf("=");
if (idx == -1)
currentSection[line] = "";
else
currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);
}
}
/// <summary>
/// Get a parameter value at the root level
/// </summary>
/// <param name="key">parameter key</param>
/// <returns></returns>
public string GetValue(string key)
{
return GetValue(key, "", "");
}
/// <summary>
/// Get a parameter value in the section
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <returns></returns>
public string GetValue(string key, string section)
{
return GetValue(key, section, "");
}
/// <summary>
/// Returns a parameter value in the section, with a default value if not found
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <param name="default">default value</param>
/// <returns></returns>
public string GetValue(string key, string section, string @default)
{
if (!ini.ContainsKey(section))
return @default;
if (!ini[section].ContainsKey(key))
return @default;
return ini[section][key];
}
/// <summary>
/// Save the INI file
/// </summary>
public void Save()
{
var sb = new StringBuilder();
foreach (var section in ini)
{
if (section.Key != "")
{
sb.AppendFormat("[{0}]", section.Key);
sb.AppendLine();
}
foreach (var keyValue in section.Value)
{
if (keyValue.Key.StartsWith(";"))
{
sb.Append(keyValue.Value);
sb.AppendLine();
}
else
{
sb.AppendFormat("{0}={1}", keyValue.Key, keyValue.Value);
sb.AppendLine();
}
}
if (!endWithCRLF(sb))
sb.AppendLine();
}
File.WriteAllText(file, sb.ToString());
}
bool endWithCRLF(StringBuilder sb)
{
if (sb.Length < 4)
return sb[sb.Length - 2] == '\r' &&
sb[sb.Length - 1] == '\n';
else
return sb[sb.Length - 4] == '\r' &&
sb[sb.Length - 3] == '\n' &&
sb[sb.Length - 2] == '\r' &&
sb[sb.Length - 1] == '\n';
}
/// <summary>
/// Write a parameter value at the root level
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="value">parameter value</param>
public void WriteValue(string key, string value)
{
WriteValue(key, "", value);
}
/// <summary>
/// Write a parameter value in a section
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <param name="value">parameter value</param>
public void WriteValue(string key, string section, string value)
{
Dictionary<string, string> currentSection;
if (!ini.ContainsKey(section))
{
currentSection = new Dictionary<string, string>();
ini.Add(section, currentSection);
}
else
currentSection = ini[section];
currentSection[key] = value;
}
/// <summary>
/// Get all the keys names in a section
/// </summary>
/// <param name="section">section</param>
/// <returns></returns>
public string[] GetKeys(string section)
{
if (!ini.ContainsKey(section))
return new string[0];
return ini[section].Keys.ToArray();
}
/// <summary>
/// Get all the section names of the INI file
/// </summary>
/// <returns></returns>
public string[] GetSections()
{
return ini.Keys.Where(t => t != "").ToArray();
}
}
+177
View File
@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using CSharpModBase;
using CSharpModBase.Input;
namespace CSharpManager
{
public class InputManager : IInputManager
{
public List<HotKeyItem> BuiltinHotKeyItems { get; } = new();
public List<HotKeyItem> HotKeyItems { get; } = new();
public bool EnableGamePad { get; set; } = true;
public static GamePadButton CurrentGamePadButton { get; set; }
// public static GamePadButtonEventHandler? GamePadButtonDown { get; set; }
private IntPtr HWnd;
public InputManager()
{
}
private void FindMainWindow()
{
uint currentProcessId = GetCurrentProcessId();
StringBuilder stringBuilder = new(64);
EnumWindows(new EnumWindowsProc((hWnd, lParam) =>
{
GetWindowThreadProcessId(hWnd, out uint processId);
if (processId == GetCurrentProcessId() &&
GetClassName(hWnd, stringBuilder, stringBuilder.Capacity) > 0 &&
stringBuilder.ToString() == "UnrealWindow")
{
HWnd = hWnd;
return false;
}
return true; // 继续枚举
}), IntPtr.Zero);
}
private void HandleKeys(List<HotKeyItem> items)
{
var now = DateTime.Now.Ticks / 10000;
var modifiers = KeyUtils.Modifiers;
foreach (var item in items)
{
if (item.Modifiers == modifiers && KeyUtils.IsKeyDown(item.Key) ||
CurrentGamePadButton != GamePadButton.None && item.GamePadButton != GamePadButton.None && CurrentGamePadButton.HasFlag(item.GamePadButton))
{
if (item.IsPressed && (item.RepeatMs == 0 || item.LastTriggerMs > 0 && now - item.LastTriggerMs < item.RepeatMs))
{
continue;
}
item.IsPressed = true;
if (item.RunOnGameThread)
{
Utils.TryRunOnGameThread(item.Action);
}
else
{
Utils.TryRun(item.Action);
}
}
else if (item.IsPressed)
{
item.IsPressed = false;
}
}
}
public void Update()
{
if (!IsProgramFocused()) return;
if (EnableGamePad)
{
GamePadUtils.GetGamePadButtons(out var buttons);
// if (buttons != GamePadButton.None)
// {
// GamePadButtonDown?.Invoke(new GamePadButtonEvent { Button = buttons });
// }
CurrentGamePadButton = buttons;
}
HandleKeys(BuiltinHotKeyItems);
lock (HotKeyItems)
{
HandleKeys(HotKeyItems);
}
}
public void Clear()
{
lock (HotKeyItems)
{
HotKeyItems.Clear();
}
}
public bool IsProgramFocused()
{
if (HWnd == IntPtr.Zero)
{
Thread.Sleep(1000);
FindMainWindow();
}
var hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero) return false;
return hwnd == HWnd;
}
[DllImport("user32.dll")]
private extern static IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern uint GetCurrentProcessId();
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// 导入Win32 API函数
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public HotKeyItem RegisterBuiltinKeyBind(Key key, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, key, action);
BuiltinHotKeyItems.Add(item);
return item;
}
public HotKeyItem RegisterBuiltinKeyBind(ModifierKeys modifiers, Key key, Action action)
{
var item = new HotKeyItem(modifiers, key, action);
BuiltinHotKeyItems.Add(item);
return item;
}
public void RegisterKeyBind(HotKeyItem item)
{
lock (HotKeyItems)
{
HotKeyItems.Add(item);
}
}
public HotKeyItem RegisterKeyBind(Key key, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, key, action);
RegisterKeyBind(item);
return item;
}
public HotKeyItem RegisterKeyBind(ModifierKeys modifiers, Key key, Action action)
{
var item = new HotKeyItem(modifiers, key, action);
RegisterKeyBind(item);
return item;
}
public HotKeyItem RegisterGamePadBind(GamePadButton button, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, Key.None, action)
{
GamePadButton = button
};
RegisterKeyBind(item);
return item;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
namespace CSharpManager
{
internal class Program
{
public static void Main(string[] args)
{
CSharpModManager manager = new();
manager.LoadMods();
manager.StartLoop();
}
}
}
+6
View File
@@ -0,0 +1,6 @@
# CSharpManager
C# mod的管理器,CSharpLoader会加载CSharpManager,通过CSharpManager加载其他C# mod
## 编译
dotnet build
+4
View File
@@ -0,0 +1,4 @@
[Settings]
Develop=1
Console=1
EnableJit=1