-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUML.cs
491 lines (455 loc) · 14.4 KB
/
UML.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
using UML;
using UnityEngine;
public class _UML
{
private static void PreloadMod(string path, List<Mod> mods)
{
Log("UML", $"Loading file {Path.GetFileName(path)}");
Assembly assembly = Assembly.LoadFrom(path);
Mod mod3 = null;
int num = 0;
try
{
foreach (Type type2 in assembly.GetTypes())
{
ModInfo customAttribute = type2.GetCustomAttribute<ModInfo>();
if (customAttribute == null && num != 2)
num = 1;
else
{
mod3 = new Mod(assembly, type2, customAttribute.name, customAttribute.author, customAttribute.version, customAttribute.guid, customAttribute.dependencies, customAttribute.modType, SHA256CheckSum(path));
mods.Add(mod3);
ResourceManager.RegisterAssetBundle(customAttribute.guid);
}
}
}
catch (ReflectionTypeLoadException ex)
{
Log("UML", ex.ToString());
}
if (mod3 == null)
Log("UML", " Failed to load mod (No Type has an attribute of ModInfo set)");
}
public static void _Start()
{
if (HooksMB.instance != null)
return;
GameObject gameObject = new GameObject();
gameObject.AddComponent<HooksMB>();
UnityEngine.Object.DontDestroyOnLoad(gameObject);
}
public static string SHA256CheckSum(string filePath)
{
string result;
using (SHA256 sha = SHA256.Create())
using (FileStream fileStream = File.OpenRead(filePath))
result = BitConverter.ToString(sha.ComputeHash(fileStream)).Replace("-", "").ToLowerInvariant();
return result;
}
public static void Log(string app, string message, bool onlyInGame = false)
{
while (app.Length < 9)
app += " ";
LogString += $"[{app}] {message}\n";
while (LogString.Split('\n').Length > 67)
LogString = LogString.Substring(LogString.IndexOf('\n') + 1);
if (onlyInGame)
return;
Console.WriteLine($"[{app}] {message}");
if (Config.config.logfile)
File.AppendAllText(Path.Combine(HooksMB.modloader, "log"), $"[{app}] {message}\n");
}
public class ConsoleCommand
{
public ConsoleCommand(string _label, Action<string[]> _run)
{
label = _label;
run = _run;
}
public readonly string label;
public readonly Action<string[]> run;
}
private static List<ConsoleCommand> commands = new List<ConsoleCommand>();
public static void RegisterCommand(ConsoleCommand cmd)
{
commands.Add(cmd);
}
public static string LogString { get; private set; }
public class HooksMB : MonoBehaviour
{
private void Start()
{
instance = this;
if (!Directory.Exists(modloader))
Directory.CreateDirectory(modloader);
if (!Directory.Exists(modss))
Directory.CreateDirectory(modss);
if (!Directory.Exists(depss))
Directory.CreateDirectory(depss);
if (!Directory.Exists(ress))
Directory.CreateDirectory(ress);
if (!File.Exists(Path.Combine(modloader, "config")))
File.WriteAllText(Path.Combine(modloader, "config"), "console=true\nunitylog=true\nlogfile=true");
new Config(File.ReadAllLines(Path.Combine(modloader, "config")));
if (Config.config.console)
{
WinConsole.Initialize(true);
Log("UML", "Initialized console");
}
if (Config.config.unitylog)
Application.logMessageReceivedThreaded += delegate (string condition, string stackTrace, LogType type)
{
Log("Unity", condition + " " + stackTrace);
};
if (Config.config.logfile)
File.WriteAllText(Path.Combine(modloader, "log"), "");
Log("UML", "Unity Version: " + Application.unityVersion);
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
Log("UML", "Preloading mods..");
if (File.Exists(Path.Combine(modloader, "autoload.dll")))
PreloadMod(Path.Combine(modloader, "autoload.dll"), mods);
foreach (string file in from x in Directory.GetFiles(modss)
where x.EndsWith(".dll")
select x)
PreloadMod(file, mods);
Log("UML", "Loading mods..");
int lastRemMods = 0;
remainingMods = mods.Count;
while (remainingMods > 0)
{
foreach (var mod in from x in mods
where !x.isLoaded && x.dependecies.Count == 0
select x)
{
Log("UML", $"Loading mod {mod.name} {mod.version} ({mod.version}) - {mod.modType}");
object obj = Activator.CreateInstance(mod.type, null);
if (!(obj is IMod mod1))
Log("UML", " Failed to load mod (The Type with an attribute of ModInfo is not inhereting from IMod)");
else
{
mod.StartInstance(mod1);
foreach (Mod mod2 in from x in mods
where !x.isLoaded && x.dependecies.Contains(mod.guid)
select x)
mod2.dependecies.Remove(mod.guid);
remainingMods--;
}
}
if(lastRemMods == remainingMods && remainingMods > 0)
{
Log("UML", "Some mods could not be loaded, because they are missing a dependency:");
foreach(var mod in from x in mods
where !x.isLoaded && x.dependecies.Count != 0
select x)
{
Log("UML", $" Missing deps in mod {mod.name}:");
foreach (var dep in mod.dependecies)
Log("UML", $" {dep}");
}
break;
}
lastRemMods = remainingMods;
}
Log("UML", "Loaded all mods");
RegisterCommand(new ConsoleCommand("help", args =>
{
string output = "Available commands: ";
foreach(var cmd in commands)
{
if (cmd.label == "help")
continue;
output += $"{cmd.label}, ";
}
Log("UML", output, true);
}));
}
private void Update()
{
foreach(var mod in mods)
if (mod.isLoaded)
mod.mod.Update(Time.deltaTime);
fadeSeconds += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.BackQuote))
debugGuiOpen = !debugGuiOpen;
}
private void FixedUpdate()
{
foreach(var mod in mods)
if (mod.isLoaded)
mod.mod.FixedUpdate(Time.fixedDeltaTime);
}
private void OnGUI()
{
foreach (var mod in mods)
if (mod.isLoaded)
mod.mod.OnGUI();
if (fadeSeconds < 6f)
{
GUIStyle middleright = new GUIStyle();
middleright.normal.background = null;
if (fadeSeconds < 5f)
middleright.normal.textColor = Color.white;
else
middleright.normal.textColor = new Color(255f, 255f, 255f, (6f - fadeSeconds) / 1f);
middleright.alignment = TextAnchor.MiddleRight;
middleright.fontStyle = FontStyle.Bold;
middleright.fontSize = 20;
string loadedMods = "Loaded mods:";
foreach(var mod in mods)
loadedMods += $"\n{mod.name} ({mod.version}) by {mod.author}";
GUI.Label(new Rect(0f, 0f, Screen.width, Screen.height), loadedMods, middleright);
}
GUIStyle bottomright = new GUIStyle();
bottomright.normal.background = null;
bottomright.normal.textColor = Color.white;
bottomright.alignment = TextAnchor.LowerLeft;
bottomright.fontStyle = FontStyle.Bold;
bottomright.fontSize = 17;
GUI.Label(new Rect(0f, 0f, Screen.width, Screen.height), $"UML by devilExE | Loaded {mods.Count} mods", bottomright);
if (debugGuiOpen)
{
GUIStyle center = new GUIStyle();
center.normal.textColor = Color.white;
center.alignment = TextAnchor.UpperCenter;
GUI.Box(new Rect(-5f, -5f, Screen.width + 10f, Screen.height + 10f), "");
GUI.Label(new Rect(0f, 10f, Screen.width, Screen.height), "<size=25>[Universal Mod Loader]</size>", center);
GUI.Label(new Rect(5f, 40f, Screen.width - 5f, Screen.height - 60f), LogString);
GUI.SetNextControlName("consoleinput");
debugCommand = GUI.TextArea(new Rect(0f, Screen.height - 20f, Screen.width, 20f), debugCommand);
GUI.FocusControl("consoleinput");
if (debugCommand.Contains("\n"))
{
debugCommand = debugCommand.Replace("\n", "");
HandleCommand(debugCommand);
debugCommand = "";
}
if(debugCommand.Contains("`"))
{
debugCommand = debugCommand.Replace("`", "");
debugGuiOpen = false;
}
}
}
private void OnApplicationQuit()
{
foreach(var mod in mods)
if (mod.isLoaded)
mod.mod.OnApplicationQuit();
}
public HooksMB()
{
mods = new List<Mod>();
debugGuiOpen = false;
debugCommand = "";
}
public static Mod[] GetMods()
{
return instance.mods.ToArray();
}
private Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
Log("UML", $" Resolving: {args.Name}");
return Assembly.LoadFrom(Path.Combine(depss, args.Name.Split(',')[0] + ".dll"));
}
private void HandleCommand(string command)
{
string[] args = command.Split(' ');
Log("UML", $"Executing: {command}", true);
ConsoleCommand cmd = (from x in commands
where x.label == args[0]
select x).First();
if(cmd == null)
{
Log("UML", $"Unknown command: {command}");
return;
}
cmd.run(args);
}
public static HooksMB instance;
public static readonly string root = Application.dataPath + "/../";
public static readonly string modloader = Path.Combine(root, "UML");
public static readonly string modss = Path.Combine(modloader, "mods");
public static readonly string depss = Path.Combine(modloader, "deps");
public static readonly string ress = Path.Combine(modloader, "res");
private readonly List<Mod> mods;
private float fadeSeconds;
private int remainingMods;
private bool debugGuiOpen;
private string debugCommand;
}
public class Mod
{
public void StartInstance(IMod _mod)
{
mod = _mod;
mod.Start();
isLoaded = true;
}
public IMod mod { get; private set; }
public bool isLoaded { get; private set; }
public Mod(Assembly _asm, Type _type, string _name, string _author, string _version, string _guid, string[] _dependencies, ModType _modType, string _sha256)
{
asm = _asm;
type = _type;
name = _name;
author = _author;
version = _version;
guid = _guid;
dependecies = _dependencies.ToList();
modType = _modType;
sha256 = _sha256;
}
public readonly Assembly asm;
public readonly string name;
public readonly string author;
public readonly string version;
public readonly string guid;
public List<string> dependecies;
public readonly Type type;
public readonly ModType modType;
public readonly string sha256;
}
private static class WinConsole
{
public static void Initialize(bool alwaysCreateNewConsole = true)
{
bool consoleAttached = true;
if (alwaysCreateNewConsole
|| (AttachConsole(ATTACH_PARRENT) == 0
&& Marshal.GetLastWin32Error() != ERROR_ACCESS_DENIED))
consoleAttached = AllocConsole() != 0;
if (consoleAttached)
{
InitializeOutStream();
InitializeInStream();
SetConsoleTitle("[UML] Universal Mod Loader");
}
}
private static void InitializeOutStream()
{
var fs = CreateFileStream("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, FileAccess.Write);
if (fs == null)
return;
var writer = new StreamWriter(fs) { AutoFlush = true };
Console.SetOut(writer);
Console.SetError(writer);
}
private static void InitializeInStream()
{
var fs = CreateFileStream("CONIN$", GENERIC_READ, FILE_SHARE_READ, FileAccess.Read);
if (fs != null)
Console.SetIn(new StreamReader(fs));
}
private static FileStream CreateFileStream(string name, uint win32DesiredAccess, uint win32ShareMode,
FileAccess dotNetFileAccess)
{
var file = new SafeFileHandle(CreateFileW(name, win32DesiredAccess, win32ShareMode, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero), true);
if (!file.IsInvalid)
{
var fs = new FileStream(file, dotNetFileAccess);
return fs;
}
return null;
}
[DllImport("kernel32.dll",
EntryPoint = "AllocConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
[DllImport("kernel32.dll",
EntryPoint = "AttachConsole",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern uint AttachConsole(uint dwProcessId);
[DllImport("kernel32.dll",
EntryPoint = "CreateFileW",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr CreateFileW(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("kernel32.dll",
EntryPoint = "SetConsoleTitle",
SetLastError = true,
CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern bool SetConsoleTitle(string lpConsoleTitle);
private const uint GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 0x00000003;
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const uint ERROR_ACCESS_DENIED = 5;
private const uint ATTACH_PARRENT = 0xFFFFFFFF;
}
public class Config
{
public Config(string[] lines)
{
foreach (string text in lines)
{
string label = text.Split('=')[0];
string value = text.Split('=')[1];
switch (label)
{
case "console":
console = (value == "true");
break;
case "unitylog":
unitylog = (value == "true");
break;
case "logfile":
logfile = (value == "true");
break;
default:
Log("Config", $"[ERR] Unknown label: {label}");
break;
}
}
config = this;
}
public static Config config;
public bool console = true;
public bool unitylog = true;
public bool logfile = true;
}
public class ResourceManager
{
public static Dictionary<string, AssetBundle> assetBundles = new Dictionary<string, AssetBundle>();
public static void RegisterAssetBundle(string guid)
{
if (!File.Exists(Path.Combine(HooksMB.ress, guid)))
return;
AssetBundle bundle = AssetBundle.LoadFromFile(Path.Combine(HooksMB.ress, guid));
assetBundles.Add(guid, bundle);
}
public static T Load<T>(string guid, string name) where T : UnityEngine.Object
{
// get calling guid
if(!assetBundles.ContainsKey(guid))
{
Log("UML", "[ERR] ResourceManager.Load(): Could not find the asset bundle (not existing / not loaded)");
return null;
}
return assetBundles[guid].LoadAsset<T>(name);
}
}
}