-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGadgetCore.cs
More file actions
636 lines (612 loc) · 28.4 KB
/
Copy pathGadgetCore.cs
File metadata and controls
636 lines (612 loc) · 28.4 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Reflection;
using System.Collections.Generic;
using System;
using System.Linq;
using GadgetCore.API;
using System.IO;
using GadgetCore.Loader;
using HarmonyLib;
using IniParser.Model;
using System.Diagnostics.CodeAnalysis;
using System.IO.IsolatedStorage;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Ionic.Zip;
using Debug = UnityEngine.Debug;
namespace GadgetCore
{
/// <summary>
/// The 'Core' of GadgetCore - where the magic happens, or more accurately where it begins. Among other things, contains the <see cref="Initialize"/> method,
/// which is the entrypoint for all of GadgetCore's functionality. However, this class is not intended for mods to access at all, and is only public
/// because it needs to be in order to make that entrypoint accessible.
/// </summary>
public class GadgetCore : MonoBehaviour
{
private static bool Initialized;
internal static volatile bool Quitting = false;
public static IGadgetCoreLib CoreLib { get; private set; }
public static IUMFAPI UMFAPI { get; private set; }
internal static Dictionary<string, Assembly> LoadedAssemblies = new Dictionary<string, Assembly>();
internal static GadgetLogger CoreLogger;
internal static GadgetLogger UnityLogger;
internal static Harmony HarmonyInstance;
static GadgetCore()
{
Initialize();
}
[SuppressMessage("Code Quality", "IDE0051:Remove unused private members", Justification = "Unity Event")]
private void Awake()
{
string updateTempFilePath = Path.Combine(GadgetPaths.GadgetCorePath, "Update.tmp");
if (File.Exists(updateTempFilePath))
{
try
{
string oldVersion = File.ReadAllText(updateTempFilePath);
GadgetCoreAPI.DisplayInfoDialog($"GadgetCore has been updated!\n{oldVersion} -> {GadgetCoreAPI.GetFullVersion()}");
}
catch (Exception) { }
try
{
File.Delete(updateTempFilePath);
}
catch (Exception) { }
}
}
[SuppressMessage("Code Quality", "IDE0051:Remove unused private members", Justification = "Unity Event")]
private void Update()
{
if (EventSystem.current?.currentSelectedGameObject == null || EventSystem.current.currentSelectedGameObject.GetComponent<InputField>()?.IsActive() != true)
{
foreach (KeyCode key in GadgetCoreAPI.keyDownListeners.Keys)
{
if (Input.GetKeyDown(key))
{
foreach (Action action in GadgetCoreAPI.keyDownListeners[key])
{
action();
}
}
}
foreach (KeyCode key in GadgetCoreAPI.keyUpListeners.Keys)
{
if (Input.GetKeyUp(key))
{
foreach (Action action in GadgetCoreAPI.keyUpListeners[key])
{
action();
}
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.Return) && GadgetCoreAPI.keyDownListeners.ContainsKey(KeyCode.Return))
{
foreach (Action action in GadgetCoreAPI.keyDownListeners[KeyCode.Return])
{
action();
}
}
if (Input.GetKeyDown(KeyCode.UpArrow) && GadgetCoreAPI.keyDownListeners.ContainsKey(KeyCode.UpArrow))
{
foreach (Action action in GadgetCoreAPI.keyDownListeners[KeyCode.UpArrow])
{
action();
}
}
if (Input.GetKeyDown(KeyCode.DownArrow) && GadgetCoreAPI.keyDownListeners.ContainsKey(KeyCode.DownArrow))
{
foreach (Action action in GadgetCoreAPI.keyDownListeners[KeyCode.DownArrow])
{
action();
}
}
if (Input.GetKeyDown(KeyCode.Escape) && GadgetCoreAPI.keyDownListeners.ContainsKey(KeyCode.Escape))
{
foreach (Action action in GadgetCoreAPI.keyDownListeners[KeyCode.Escape])
{
action();
}
}
}
GadgetConsole.hidThisFrame = false;
}
/// <summary>
/// The entrypoint for all of GadgetCore. Will do nothing if called again by a mod.
/// </summary>
public static void Initialize()
{
if (Initialized) return;
Initialized = true;
Debug.Log("GadgetCore v" + GadgetCoreAPI.FULL_VERSION);
bool earlyConfigLoaded = false;
try
{
GadgetCoreConfig.EarlyLoad();
earlyConfigLoaded = true;
}
catch (Exception e)
{
Debug.Log("Failed to load GadgetCore config file early: " + e);
}
try
{
if (GadgetCoreConfig.MaxLogArchives > 0) BackupLogFiles();
}
catch (Exception) { }
try
{
CoreLogger = new GadgetLogger("GadgetCore", "Core");
CoreLogger.Log("GadgetCore v" + GadgetCoreAPI.FULL_VERSION + " Initializing!");
UnityLogger = new GadgetLogger("Unity Output", "Unity");
Application.SetStackTraceLogType(LogType.Exception, StackTraceLogType.Full);
Application.logMessageReceivedThreaded += (text, stackTrace, type) =>
{
switch (type)
{
case LogType.Log:
UnityLogger.Log(text);
break;
case LogType.Warning:
UnityLogger.LogWarning(text, false);
break;
case LogType.Error:
case LogType.Assert:
UnityLogger.LogError(text, false);
break;
case LogType.Exception:
if (!string.IsNullOrEmpty(stackTrace))
{
GadgetMod blameMod = null;
foreach (string frame in stackTrace.Split('\n'))
{
try
{
if (GadgetLoader.BlameMap.TryGetValue(
frame.Substring(0, frame.LastIndexOf('.', stackTrace.IndexOf(' '))),
out blameMod)) break;
} catch (Exception) {}
}
if (blameMod != null)
{
UnityLogger.LogError($"<Exception from {blameMod.Name}> " + text, GadgetCoreConfig.LogExceptions);
}
else
{
UnityLogger.LogError("<Exception> " + text, GadgetCoreConfig.LogExceptions);
}
UnityLogger.LogRaw(string.Join("\n", stackTrace.Split('\n').Where(frame => !string.IsNullOrEmpty(frame)).Select(frame => "[StackTrace] " + frame).ToArray()));
}
else
{
UnityLogger.LogError("<Exception> " + text, GadgetCoreConfig.LogExceptions);
}
break;
}
};
string logPath = Application.dataPath + "\\output_log.txt";
if (!File.Exists(logPath)) logPath = Application.persistentDataPath + "\\output_log.txt";
if (!File.Exists(logPath))
{
string homeVar = Environment.GetEnvironmentVariable("HOME");
if (homeVar != null)
{
logPath = Path.Combine(homeVar, "Library/Logs/Unity/Player.log");
if (!File.Exists(logPath)) logPath = Path.Combine(homeVar, ".config/unity3d/DefaultCompany/Roguelands/Player.log");
}
}
if (File.Exists(logPath))
{
try
{
using FileStream fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using StreamReader streamReader = new StreamReader(fileStream);
string logData = string.Join("\n",
streamReader.ReadToEnd().Replace('\r', '\n')
.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(frame => string.IsNullOrEmpty(frame) ? frame : " " + frame).ToArray());
UnityLogger.LogRaw("=====Begin Unity log prior to GadgetCore initialization=====");
UnityLogger.LogRaw(logData);
UnityLogger.LogRaw("=====End Unity log prior to GadgetCore initialization=====");
}
catch (Exception)
{
UnityLogger.LogWarning("Error reading Unity output log file!");
}
}
else
{
UnityLogger.LogWarning("Unable to find Unity output log file!");
}
}
catch (Exception e)
{
Debug.Log("GadgetCore Logger Initialization Failed: " + e);
}
try
{
try
{
GadgetLoader.LoadSymbolsInternal("GadgetCore",
File.ReadAllBytes(Path.Combine(GadgetPaths.ManagedPath, "GadgetCore.dll")),
File.ReadAllBytes(Path.Combine(GadgetPaths.ManagedPath, "GadgetCore.pdb")))
.Wait(10000);
}
catch (Exception e)
{
CoreLogger.LogWarning("Failed to log GadgetCore symbols due to an exception: " + e.Message, false);
}
if (File.Exists(Application.persistentDataPath + "/PlayerPrefs.txt"))
{
if (VerifySaveFile())
{
if (GadgetCoreConfig.MaxBackups > 0)
{
File.Copy(Application.persistentDataPath + "/PlayerPrefs.txt", Path.Combine(GadgetPaths.SaveBackupsPath, "Save Backup - " + DateTime.Now.ToString("yyyy-dd-M_HH-mm-ss") + ".txt"));
FileInfo[] backups = new DirectoryInfo(GadgetPaths.SaveBackupsPath).GetFiles().OrderByDescending(x => x.LastWriteTime.Year <= 1601 ? x.CreationTime : x.LastWriteTime).ToArray();
if (backups.Length > GadgetCoreConfig.MaxBackups)
{
for (int i = GadgetCoreConfig.MaxBackups; i < backups.Length; i++)
{
backups[i].Delete();
}
}
}
}
else
{
CoreLogger.LogError("Quitting game due to corrupt save file!");
GadgetCoreAPI.Quit();
return;
}
}
HarmonyInstance = new Harmony("GadgetCore.core");
Type[] types;
try
{
types = Assembly.GetExecutingAssembly().GetTypes();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).ToArray();
}
types.Do(delegate (Type type)
{
object[] attributes = type.GetCustomAttributes(true);
if (!attributes.Any(x => x.GetType() == typeof(HarmonyGadgetAttribute)))
{
try
{
HarmonyInstance.CreateClassProcessor(type).Patch();
}
catch (HarmonyException e)
{
if (e.InnerException == null || !e.InnerException.Message.EndsWith("returned an unexpected result: null")) throw e;
}
}
});
AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) =>
{
string name = new AssemblyName(args.Name).Name;
if (LoadedAssemblies.ContainsKey(name)) return LoadedAssemblies[name];
foreach (string file in Directory.GetFiles(GadgetPaths.LibsPath))
{
if (AssemblyName.GetAssemblyName(file).Name == name)
{
Assembly assembly = Assembly.LoadFrom(file);
LoadedAssemblies[name] = assembly;
return assembly;
}
}
return null;
};
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (object sender, ResolveEventArgs args) =>
{
string name = new AssemblyName(args.Name).Name;
if (LoadedAssemblies.ContainsKey("ReflectionOnly: " + name)) return LoadedAssemblies["ReflectionOnly: " + name];
foreach (string file in Directory.GetFiles(GadgetPaths.LibsPath))
{
if (AssemblyName.GetAssemblyName(file).Name == name)
{
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
LoadedAssemblies["ReflectionOnly: " + name] = assembly;
return assembly;
}
}
return null;
};
LoadMainMenu();
try
{
UMFAPI = new UMFAPI();
UMFAPI.GetModNames();
CoreLogger.Log("Enabling UMF API as UMF is installed.");
}
catch (Exception)
{
UMFAPI = null;
CoreLogger.Log("Disabling UMF API as UMF is not installed.");
}
CoreLib = Activator.CreateInstance(Assembly.LoadFile(Path.Combine(Path.Combine(GadgetPaths.GadgetCorePath, "DependentLibs"), "GadgetCoreLib.dll")).GetTypes().First(x => typeof(IGadgetCoreLib).IsAssignableFrom(x))) as IGadgetCoreLib;
CoreLib.ProvideLogger(CoreLogger);
if (!earlyConfigLoaded) GadgetCoreConfig.EarlyLoad();
GadgetCoreConfig.Load();
CoreLogger.Log("Finished loading config.");
RegisterKeys();
IniData coreManifest = new IniData();
coreManifest["Metadata"]["Name"] = "GadgetCore";
coreManifest["Metadata"]["Assembly"] = Path.Combine(GadgetPaths.ManagedPath, "GadgetCore.dll");
GadgetMod coreMod = new GadgetMod(GadgetPaths.GadgetCorePath, coreManifest, Assembly.GetExecutingAssembly());
GadgetMods.RegisterMod(coreMod);
VanillaRegistration();
SceneManager.sceneLoaded += OnSceneLoaded;
SceneInjector.InjectMainMenu();
GadgetLoader.LoadAllMods();
DontDestroyOnLoad(new GameObject("GadgetCore", typeof(GadgetCore)));
CoreLogger.LogConsole("GadgetCore v" + GadgetCoreAPI.FULL_VERSION + " Initialized!");
#if DEBUG
CoreLogger.LogWarning("You are currently running a beta version of GadgetCore! Be prepared for bugs!");
#endif
}
catch (Exception e)
{
CoreLogger.LogError("There was a fatal error loading GadgetCore: " + e);
}
}
private static void BackupLogFiles()
{
string[] logFiles = Directory.GetFiles(GadgetPaths.LogsPath, "*.log");
if (logFiles == null || logFiles.Length < 1) return;
DateTime logZipTime = File.GetCreationTime(File.Exists(Path.Combine(GadgetPaths.LogsPath, "GadgetCore.log")) ? Path.Combine(GadgetPaths.LogsPath, "GadgetCore.log") : logFiles[0]);
int warningCount = 0, errorCount = 0, exceptionCount = 0;
bool warningErr = false, errorErr = false, exceptionErr = false;
foreach (string logFile in logFiles)
{
if (Path.GetFileName(logFile) == "Unity Output.log")
{
try
{
exceptionCount += File.ReadAllLines(logFile).Count(x => x.Contains("Exception"));
}
catch (Exception)
{
exceptionErr = true;
}
}
else
{
string[] lines;
try
{
lines = File.ReadAllLines(logFile);
}
catch (Exception)
{
warningErr = true;
errorErr = true;
continue;
}
try
{
warningCount += lines.Count(x => x.Contains("[Warning]"));
}
catch (Exception)
{
warningErr = true;
}
try
{
errorCount += lines.Count(x => x.Contains("[Error]"));
}
catch (Exception)
{
errorErr = true;
}
}
}
string logZipName = $"Archived Logs ({logZipTime:yyyy-MM-dd hh.mm.ss tt}) - " +
(warningCount < 0 || errorCount < 0 || exceptionCount < 0 ? "[Possibly Corrupt] " : "") +
$"[{(warningErr ? $"{warningCount}?" : warningCount.ToString())} Warnings] " +
$"[{(errorErr ? $"{errorCount}?" : errorCount.ToString())} Errors] " +
$"[{(exceptionErr ? $"{exceptionCount}?" : exceptionCount.ToString())} Exceptions]" +
".zip";
using (ZipFile logZip = new ZipFile())
{
logZip.AddFiles(logFiles, string.Empty);
logZip.Save(Path.Combine(GadgetPaths.LogArchivesPath, logZipName));
}
foreach (string file in logFiles)
{
try
{
File.Delete(file);
}
catch (Exception) { }
}
FileInfo[] archives = new DirectoryInfo(GadgetPaths.LogArchivesPath).GetFiles().OrderByDescending(x => x.LastWriteTime.Year <= 1601 ? x.CreationTime : x.LastWriteTime).ToArray();
if (archives.Length > GadgetCoreConfig.MaxLogArchives)
{
for (int i = GadgetCoreConfig.MaxLogArchives; i < archives.Length; i++)
{
archives[i].Delete();
}
}
}
internal static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
GadgetCoreAPI.SceneReset();
if (scene.buildIndex == 0)
{
GadgetNetwork.ResetIDMatrix();
LoadMainMenu();
SceneInjector.InjectMainMenu();
}
else
{
LoadIngame();
SceneInjector.InjectIngame();
}
}
internal static void LoadMainMenu()
{
InstanceTracker.MainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
InstanceTracker.Menuu = InstanceTracker.MainCamera.GetComponent<Menuu>();
}
internal static void LoadIngame()
{
InstanceTracker.MainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
}
private static bool VerifySaveFile()
{
bool loadedBackup = false;
DateTime time = DateTime.Now;
while (true)
{
if (ValidateSaveFileContent(File.ReadAllText(Application.persistentDataPath + "/PlayerPrefs.txt")))
{
if (loadedBackup)
{
CoreLogger.LogWarning("There was an error loading the save file, but a save backup was successfully loaded!\n" +
"Be prepared for lost progress due to loading the backup. The backup that was loaded was created at: " +
time);
}
return true;
}
else
{
FileInfo[] backups = new DirectoryInfo(GadgetPaths.SaveBackupsPath).GetFiles().OrderByDescending(x => x.LastWriteTime.Year <= 1601 ? x.CreationTime : x.LastWriteTime).ToArray();
int fileIndex = 0;
string fileContent = null;
while (string.IsNullOrEmpty(fileContent) && fileIndex < backups.Length)
{
time = backups[fileIndex].LastWriteTime.Year <= 1601 ? backups[fileIndex].CreationTime : backups[fileIndex].LastWriteTime;
fileContent = File.ReadAllText(backups[fileIndex].FullName);
fileIndex++;
}
if (string.IsNullOrEmpty(fileContent))
{
CoreLogger.LogError("There was an error loading the save file, and no viable backups were found!");
return false;
}
File.Delete(Application.persistentDataPath + "/PlayerPrefs.txt");
File.Move(backups[fileIndex - 1].FullName, Application.persistentDataPath + "/PlayerPrefs.txt");
loadedBackup = true;
}
}
}
private static bool ValidateSaveFileContent(string content)
{
try
{
if (!string.IsNullOrEmpty(content))
{
if (content.Length > 0 && content[content.Length - 1] == '\n')
{
content = content.Substring(0, content.Length - 1);
if (content.Length > 0 && content[content.Length - 1] == '\r')
{
content = content.Substring(0, content.Length - 1);
}
}
string[] array = content.Split(new[]
{
" ; "
}, StringSplitOptions.RemoveEmptyEntries);
foreach (string text in array)
{
string[] array3 = text.Split(new[]
{
" : "
}, StringSplitOptions.None);
if (array3.Length < 3) return false;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
private static void RegisterKeys()
{
GadgetCoreAPI.RegisterKeyDownListener(KeyCode.Escape, GadgetConsole.HideConsole);
}
private static void VanillaRegistration()
{
Registry.gadgetRegistering = -1;
Registry.registeringVanilla = true;
GameRegistry.RegisterRegistry(ItemRegistry.Singleton);
GameRegistry.RegisterRegistry(ChipRegistry.Singleton);
GameRegistry.RegisterRegistry(TileRegistry.Singleton);
GameRegistry.RegisterRegistry(EntityRegistry.Singleton);
GameRegistry.RegisterRegistry(MenuRegistry.Singleton);
GameRegistry.RegisterRegistry(ObjectRegistry.Singleton);
GameRegistry.RegisterRegistry(PlanetRegistry.Singleton);
GameRegistry.RegisterRegistry(AllegianceRegistry.Singleton);
GameRegistry.RegisterRegistry(CharacterRaceRegistry.Singleton);
GameRegistry.RegisterRegistry(CharacterAugmentRegistry.Singleton);
GameRegistry.RegisterRegistry(CharacterUniformRegistry.Singleton);
GadgetCoreAPI.MissingItemMaterial = new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("missing_item")
};
GadgetCoreAPI.MissingTileSprite = GadgetCoreAPI.AddTextureToSheet(GadgetCoreAPI.LoadTexture2D("missing_tile"));
GameObject expCustom = Instantiate(Resources.Load<GameObject>("exp/exp7"));
GadgetCoreAPI.AddCustomResource("exp/expCustom", expCustom);
GadgetCoreAPI.AddCustomResource("mat/mRaceBack", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_race_select.png")
});
GadgetCoreAPI.AddCustomResource("mat/mRaceSlot", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_race_slot.png")
});
GadgetCoreAPI.AddCustomResource("mat/mUniformBack", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_uniform_select.png")
});
GadgetCoreAPI.AddCustomResource("mat/mUniformSlot", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_uniform_slot.png")
});
GadgetCoreAPI.AddCustomResource("mat/mAugmentBack", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_augment_select.png")
});
GadgetCoreAPI.AddCustomResource("mat/mAugmentSlot", new Material(Shader.Find("Unlit/Transparent"))
{
mainTexture = GadgetCoreAPI.LoadTexture2D("blank_augment_slot.png")
});
Registry.registeringVanilla = false;
}
internal static void GenerateSpriteSheet()
{
GadgetCoreAPI.spriteSheetSize = MathUtils.SmallestPerfectSquare(GadgetCoreAPI.spriteSheetSprites.Count + 16);
int spritesOnAxis = (int)Mathf.Sqrt(GadgetCoreAPI.spriteSheetSize);
int spritesOnFirstFourRows = spritesOnAxis - 4;
int spriteSheetDimensions = spritesOnAxis * 32;
GadgetCoreAPI.spriteSheet = new Texture2D(spriteSheetDimensions, spriteSheetDimensions, InstanceTracker.GameScript.TileManager.GetComponent<ChunkWorld>().Texture.format, false, false)
{
filterMode = FilterMode.Point
};
for (int i = 0;i < GadgetCoreAPI.spriteSheetSprites.Count;i++)
{
Vector2 coords;
if (i < spritesOnFirstFourRows * 4)
{
coords = new Vector2(4 + (i % spritesOnFirstFourRows), i / spritesOnFirstFourRows);
}
else
{
coords = new Vector2((i - (spritesOnFirstFourRows * 4)) % spritesOnAxis, 4 + ((i - (spritesOnFirstFourRows * 4)) / spritesOnAxis));
}
GadgetCoreAPI.spriteSheetSprites[i].coords = coords;
GadgetUtils.SafeCopyTexture(GadgetCoreAPI.spriteSheetSprites[i].tex, 0, 0, 0, 0, 32, 32, GadgetCoreAPI.spriteSheet, 0, 0, (int)coords.x * 32, (int)coords.y * 32);
}
}
}
}