forked from ppebb/tConfigWrapper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LoadStep.cs
1047 lines (906 loc) · 42.7 KB
/
LoadStep.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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Gajatko.IniFiles;
using Mono.Cecil;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SevenZip;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using tConfigWrapper.Common;
using tConfigWrapper.Common.DataTemplates;
using static tConfigWrapper.Common.Utilities;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
namespace tConfigWrapper {
public static class LoadStep {
public static Action<string> LoadProgressText; // Heading text during loading
public static Action<float> LoadProgress; // Progress bar during loading: 0-1 scale
public static Action<string> LoadSubProgressText; // Subtext during loading
public static int TaskCompletedCount; // Int used for tracking load progress during content loading
internal static ConcurrentDictionary<int, ItemInfo> globalItemInfos = new ConcurrentDictionary<int, ItemInfo>(); // Dictionaries are selfexplanatory, concurrent so that multiple threads can access them without dying
private static ConcurrentDictionary<string, IniFileSection> recipeDict = new ConcurrentDictionary<string, IniFileSection>();
private static ConcurrentDictionary<string, ModItem> itemsToLoad = new ConcurrentDictionary<string, ModItem>();
private static ConcurrentDictionary<string, (ModTile tile, string texture)> tilesToLoad = new ConcurrentDictionary<string, (ModTile, string)>();
private static ConcurrentDictionary<string, ModNPC> npcsToLoad = new ConcurrentDictionary<string, ModNPC>();
private static ConcurrentDictionary<string, ModProjectile> projectilesToLoad = new ConcurrentDictionary<string, ModProjectile>();
private static ConcurrentDictionary<string, (ModWall wall, string texture)> wallsToLoad = new ConcurrentDictionary<string, (ModWall, string)>();
private static ConcurrentDictionary<string, ModPrefix> prefixesToLoad = new ConcurrentDictionary<string, ModPrefix>();
internal static ConcurrentBag<ModPrefix> suffixes = new ConcurrentBag<ModPrefix>();
internal static ConcurrentDictionary<ModTile, (bool, string)> tileMapData = new ConcurrentDictionary<ModTile, (bool, string)>();
internal static ConcurrentDictionary<string, MemoryStream> streamsGlobal = new ConcurrentDictionary<string, MemoryStream>();
internal static string CurrentLoadingMod;
internal static Mod mod => ModContent.GetInstance<tConfigWrapper>();
public static void Setup() { // Method to load everything
recipeDict.TryGetValue("", out _); // Sanity check to make sure it's initialized
// Cringe reflection
Assembly assembly = Assembly.GetAssembly(typeof(Mod));
Type UILoadModsType = assembly.GetType("Terraria.ModLoader.UI.UILoadMods");
object loadModsValue = assembly.GetType("Terraria.ModLoader.UI.Interface").GetField("loadMods", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
MethodInfo LoadStageMethod = UILoadModsType.GetMethod("SetLoadStage", BindingFlags.Instance | BindingFlags.Public);
PropertyInfo ProgressProperty = UILoadModsType.GetProperty("Progress", BindingFlags.Instance | BindingFlags.Public);
PropertyInfo SubProgressTextProperty = UILoadModsType.GetProperty("SubProgressText", BindingFlags.Instance | BindingFlags.Public);
LoadProgressText = (string s) => LoadStageMethod.Invoke(loadModsValue, new object[] { s, -1 });
LoadProgress = (float f) => ProgressProperty.SetValue(loadModsValue, f);
LoadSubProgressText = (string s) => SubProgressTextProperty.SetValue(loadModsValue, s);
LoadProgressText?.Invoke("tConfig Wrapper: Loading Mods");
LoadProgress?.Invoke(0f);
foreach (var modName in ModState.AllMods) {
if (ModState.EnabledMods.Contains(Path.GetFileNameWithoutExtension(modName)))
mod.Logger.Debug($"tConfig Mod: {Path.GetFileNameWithoutExtension(modName)} is enabled!"); // Writes all mod names to logs
}
for (int i = 0; i < ModState.EnabledMods.Count; i++) { // Iterates through every mod
string currentMod = ModState.EnabledMods[i];
string currentModNoExt = Path.GetFileNameWithoutExtension(ModState.EnabledMods[i]);
CurrentLoadingMod = currentModNoExt;
LoadProgressText?.Invoke($"tConfig Wrapper: Loading {currentModNoExt}"); // Sets heading text to display the mod being loaded
mod.Logger.Debug($"Loading tConfig Mod: {currentModNoExt}"); // Logs the mod being loaded
using (var finished = new CountdownEvent(1)) {
using (SevenZipExtractor extractor = new SevenZipExtractor(currentMod)) {
bool CursedMod = extractor.ArchiveFileNames[0].Contains("Pickaxe+ v1.3a"); // Cursed mod bad
if (CursedMod)
LoadSubProgressText?.Invoke("You are loading a cursed mod, it's not our fault it takes so long to load");
mod.Logger.Debug($"Loading Content: {currentModNoExt}");
ConcurrentDictionary<string, MemoryStream> streams = new ConcurrentDictionary<string, MemoryStream>();
DecompressMod(currentMod, extractor, streams); // Decompresses mods since .obj files are literally just 7z files
streamsGlobal.Clear();
streamsGlobal = streams;
// Get the first stream that is an obj file
var obj = streams.First(s => s.Key.EndsWith(".obj"));
BinaryReader reader = new BinaryReader(obj.Value);
// Create an Obj Loader and load the obj
var loader = new ObjLoader(reader, currentModNoExt);
loader.LoadObj(); // This was causing errors for some reason.
// Clear dictionaries and task count or else stuff from other mods will interfere with the current mod being loaded
itemsToLoad.Clear();
tilesToLoad.Clear();
npcsToLoad.Clear();
projectilesToLoad.Clear();
wallsToLoad.Clear();
prefixesToLoad.Clear();
TaskCompletedCount = 0;
// Slowass linq sorts content and then is assigned to individual threads
IEnumerable<string> itemFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\Item\\") && Path.GetExtension(name) == ".ini");
IEnumerable<string> npcFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\NPC\\") && Path.GetExtension(name) == ".ini");
IEnumerable<string> tileFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\Tile\\") && Path.GetExtension(name) == ".ini");
IEnumerable<string> projectileFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\Projectile\\") && Path.GetExtension(name) == ".ini");
IEnumerable<string> wallFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\Wall\\") && Path.GetExtension(name) == ".ini");
IEnumerable<string> prefixFiles = extractor.ArchiveFileNames.Where(name => name.Contains("\\Prefix\\") && Path.GetExtension(name) == ".ini");
int contentCount = itemFiles.Count() + npcFiles.Count() + tileFiles.Count() + projectileFiles.Count() + wallFiles.Count() + prefixFiles.Count(); // Count all loadable content in mod for accurate loading progress
if (contentCount != 0)
{
Thread itemThread = new Thread(CreateItem);
itemThread.Start(new object[] { itemFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
Thread npcThread = new Thread(CreateNPC);
npcThread.Start(new object[] { npcFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
Thread tileThread = new Thread(CreateTile);
tileThread.Start(new object[] { tileFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
Thread projectileThread = new Thread(CreateProjectile);
projectileThread.Start(new object[] { projectileFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
Thread wallThread = new Thread(CreateWall);
wallThread.Start(new object[] { wallFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
Thread prefixThread = new Thread(CreatePrefix);
prefixThread.Start(new object[] { prefixFiles, currentModNoExt, currentMod, finished, extractor, contentCount, streams });
finished.AddCount();
//Thread assemblyThread = new Thread(LoadAssembly);
//assemblyThread.Start(new object[] { finished, currentModNoExt, currentMod, });
//finished.AddCount();
finished.Signal();
finished.Wait();
}
foreach (var memoryStream in streams) {
memoryStream.Value.Dispose();
}
//Load content from dictionaries
foreach (var item in itemsToLoad) {
mod.AddItem(item.Key, item.Value);
}
foreach (var tile in tilesToLoad) {
mod.AddTile(tile.Key, tile.Value.tile, tile.Value.texture);
}
foreach (var npc in npcsToLoad) {
mod.AddNPC(npc.Key, npc.Value);
}
foreach (var projectile in projectilesToLoad) {
mod.AddProjectile(projectile.Key, projectile.Value);
}
foreach (var wall in wallsToLoad) {
mod.AddWall(wall.Key, wall.Value.wall, wall.Value.texture);
}
foreach (var prefix in prefixesToLoad) {
mod.AddPrefix(prefix.Key, prefix.Value);
}
}
}
}
//Reset progress bar
LoadSubProgressText?.Invoke("");
LoadProgressText?.Invoke("Loading mod");
LoadProgress?.Invoke(0f);
CurrentLoadingMod = null;
}
private static void DecompressMod(string objPath, SevenZipExtractor extractor, ConcurrentDictionary<string, MemoryStream> streams) {
List<string> fileNames = extractor.ArchiveFileNames.ToList();
LoadSubProgressText?.Invoke("Decompressing");
double numThreads = Math.Min((double)ModContent.GetInstance<LoadConfig>().NumThreads, fileNames.Count);
using (CountdownEvent decompressCount = new CountdownEvent(1)) {
// Split the files into numThreads chunks
var chunks = new List<List<string>>();
int chunkSize = (int) Math.Round(fileNames.Count / numThreads, MidpointRounding.AwayFromZero);
for (int i = 0; i < fileNames.Count; i += chunkSize) {
chunks.Add(fileNames.GetRange(i, Math.Min(chunkSize, fileNames.Count - i)));
}
// Create threads and decompress the chunks
foreach (var chunk in chunks) {
ThreadPool.QueueUserWorkItem(DecompressMod, new object[] {objPath, chunk, streams, decompressCount});
decompressCount.AddCount();
}
// Wait for the CountdownEvent to end
decompressCount.Signal();
decompressCount.Wait();
}
}
public static int decompressTasksCompleted = 0; // Total number of items decompressed
public static int decompressTotalFiles = 0; // Total number of items that need to be decompressed
private static void DecompressMod(object callback) {
// Process the parameters
object[] parameters = (object[])callback;
string objPath = parameters[0] as string;
List<string> files = parameters[1] as List<string>;
ConcurrentDictionary<string, MemoryStream> streams = parameters[2] as ConcurrentDictionary<string, MemoryStream>;
CountdownEvent countdown = parameters[3] as CountdownEvent;
// Create a FileStream with the following arguments to be able to have multiple threads access it
using (FileStream fileStream = new FileStream(objPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (SevenZipExtractor extractor = new SevenZipExtractor(fileStream)) {
decompressTotalFiles += files.Count; // Counts the number of items that need to be loaded for accurate progress bar
foreach (var fileName in files) {
LoadProgress?.Invoke((float)decompressTasksCompleted / decompressTotalFiles); // Sets the progress bar
// If the extension is not valid, skip the file
string extension = Path.GetExtension(fileName);
if (!(extension == ".ini" || extension == ".cs" || extension == ".png" || extension == ".dll" || extension == ".obj"))
continue;
// Create a MemoryStream and extract the file
MemoryStream stream = new MemoryStream();
extractor.ExtractFile(fileName, stream);
stream.Position = 0;
streams.TryAdd(fileName, stream);
decompressTasksCompleted++; // Increments the number of tasks completed for accurate progress display
}
}
// Signal the end of the thread
countdown.Signal();
}
public static void LoadAssembly(object stateInfo) {
object[] parameters = (object[])stateInfo;
CountdownEvent finished = (CountdownEvent)parameters[0];
ModuleDefinition module = AssemblyLoader.GetModule(Path.GetFileNameWithoutExtension((string)parameters[2]));
AssemblyLoader.FixIL((string)parameters[1], module);
finished.Signal();
}
public static void SetupRecipes() { // Sets up recipes, what were you expecting?
LoadProgressText.Invoke("tConfig Wrapper: Adding Recipes"); // Ah yes, more reflection
LoadProgress.Invoke(0f);
int progressCount = 0;
bool initialized = (bool)Assembly.GetAssembly(typeof(Mod)).GetType("Terraria.ModLoader.MapLoader").GetField("initialized", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); // Check if the map is already initialized
foreach (var iniFileSection in recipeDict) { // Load every recipe in the recipe dict
progressCount++; // Count the number of recipes, still broken somehow :(
string modName = iniFileSection.Key.Split(':')[0];
ModRecipe recipe = null;
if (initialized) // Only make the recipe if the maps have already been initialized. The checks for initialized are because I run this method in GetTileMapEntires() to see what tiles are used in recipes and need to have a name in their map entry
recipe = new ModRecipe(mod);
foreach (var element in iniFileSection.Value.elements) { // ini recipe loading, code is readable enough.
string[] splitElement = element.Content.Split('=');
string key = splitElement[0];
string value = splitElement[1];
switch (key) {
case "Amount" when initialized: {
int id;
string[] splitKey = iniFileSection.Key.Split(':');
string itemName = splitKey.Length == 1 ? splitKey[0] : splitKey[1];
if ((id = ItemID.FromLegacyName(itemName, 4)) != 0)
recipe?.SetResult(id, int.Parse(value));
else
recipe?.SetResult(mod, iniFileSection.Key, int.Parse(value));
break;
}
case "needWater" when initialized:
recipe.needWater = bool.Parse(value);
break;
case "Items" when initialized: {
foreach (string recipeItem in value.Split(',')) {
var recipeItemInfo = recipeItem.Split(null, 2);
int amount = int.Parse(recipeItemInfo[0]);
int itemID = mod.ItemType($"{modName}:{recipeItemInfo[1].RemoveIllegalCharacters()}");
if (itemID == 0)
itemID = ItemID.FromLegacyName(recipeItemInfo[1], 4);
var numberIngredients =
recipe?.requiredItem.Count(i => i != null & i.type != ItemID.None);
if (numberIngredients < 14)
recipe?.AddIngredient(itemID, amount);
else {
mod.Logger.Debug($"The following item has exceeded the max ingredient limit! -> {iniFileSection.Key}");
tConfigWrapper.ReportErrors = true;
}
}
break;
}
case "Tiles": { // Does stuff to check for modtiles and vanilla tiles that have changed their name since 1.1.2
foreach (string recipeTile in value.Split(',')) {
string recipeTileIR = recipeTile.RemoveIllegalCharacters();
int tileInt = mod.TileType($"{modName}:{recipeTileIR}");
var tileModTile = mod.GetTile($"{modName}:{recipeTileIR}");
if (!TileID.Search.ContainsName(recipeTileIR) && !CheckIDConversion(recipeTileIR) && tileInt == 0 && tileModTile == null) { // Would love to replace this with Utilities.StringToContent() but this one is special and needs to add stuff to a dictionary so I can't
if (initialized) {
mod.Logger.Debug($"TileID {modName}:{recipeTileIR} does not exist"); // We will have to manually convert anything that breaks lmao
tConfigWrapper.ReportErrors = true;
}
}
else if (CheckIDConversion(recipeTileIR) || TileID.Search.ContainsName(recipeTileIR)) {
string converted = ConvertIDTo13(recipeTileIR);
if (initialized)
recipe?.AddTile(TileID.Search.GetId(converted));
}
else if (tileInt != 0) {
if (initialized) {
recipe?.AddTile(tileModTile);
mod.Logger.Debug($"{modName}:{recipeTileIR} added to recipe through mod.TileType!");
}
else {
tileMapData[tileModTile] = (true, tileMapData[tileModTile].Item2); // I do this because either I can't just change Item1 directly to true OR because I am very not smart and couldn't figure out how to set it individually.
}
}
}
break;
}
}
}
if (recipe?.createItem != null && recipe?.createItem.type != ItemID.None && initialized)
recipe?.AddRecipe();
if (initialized)
LoadProgress.Invoke(progressCount / recipeDict.Count);
}
}
private static void CreateItem(object stateInfo) { // This is literally just to simplify the threading and counting of content loading
object[] parameters = (object[])stateInfo;
CountdownEvent countdown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreateItem(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countdown.Signal();
}
private static void CreateItem(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) { // Loads content, I don't know how it works either
MemoryStream iniStream = streams[fileName];
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
object info = new ItemInfo();
List<string> toolTipList = new List<string>();
// Get the mod name
string itemName = Path.GetFileNameWithoutExtension(fileName);
string internalName = $"{modName}:{itemName.RemoveIllegalCharacters()}";
// TODO: If the item is from Terraria, make it a GlobalItem
if (ItemID.FromLegacyName(itemName, 4) != 0)
internalName = itemName;
bool logItemAndModName = false;
string createWall = null;
string createTile = null;
string shoot = null;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
switch (section.Name) {
case "Stats": {
var splitElement = element.Content.Split('=');
var statField = typeof(ItemInfo).GetField(splitElement[0]);
switch (splitElement[0]) {
// Set the tooltip, has to be done manually since the toolTip field doesn't exist in 1.3
case "toolTip":
case "toolTip1":
case "toolTip2":
case "toolTip3":
case "toolTip4":
case "toolTip5":
case "toolTip6":
case "toolTip7": {
toolTipList.Add(splitElement[1]);
continue;
}
case "useSound": {
var soundStyleId = int.Parse(splitElement[1]);
var soundStyle = new LegacySoundStyle(2, soundStyleId); // All items use the second sound ID
statField = typeof(ItemInfo).GetField("UseSound");
statField.SetValue(info, soundStyle);
continue;
}
case "createTileName": {
createTile = $"{modName}:{splitElement[1]}";
continue;
}
case "projectile": {
shoot = $"{modName}:{splitElement[1]}";
continue;
}
case "createWallName": {
createWall = $"{modName}:{splitElement[1]}";
continue;
}
case "type":
continue;
default: {
if (statField == null) {
mod.Logger.Debug($"Item field not found or invalid field! -> {splitElement[0]}");
logItemAndModName = true;
tConfigWrapper.ReportErrors = true;
continue;
}
break;
}
}
// Convert the value to an object of type statField.FieldType
TypeConverter converter = TypeDescriptor.GetConverter(statField.FieldType);
object realValue = converter.ConvertFromString(splitElement[1]);
statField.SetValue(info, realValue);
break;
}
case "Recipe": {
if (!recipeDict.ContainsKey(internalName))
recipeDict.TryAdd(internalName, section);
break;
}
}
}
}
if (logItemAndModName)
mod.Logger.Debug($"{internalName}"); //Logs the item and mod name if "Field not found or invalid field". Mod and item name show up below the other log line
string toolTip = null;
foreach (string toolTipLine in toolTipList) {
toolTip += "\n" + toolTipLine;
}
// Check if a texture for the .ini file exists
string texturePath = Path.ChangeExtension(fileName, "png");
Texture2D itemTexture = null;
if (!Main.dedServ && streams.TryGetValue(texturePath, out MemoryStream textureStream)) {
itemTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, textureStream); // Load a Texture2D from the stream
}
int id;
if ((id = ItemID.FromLegacyName(itemName, 4)) != 0) {
if (!globalItemInfos.ContainsKey(id))
globalItemInfos.TryAdd(id, (ItemInfo)info);
else
globalItemInfos[id] = (ItemInfo)info;
reader.Dispose();
return;
}
if (itemTexture != null)
itemsToLoad.TryAdd(internalName, new BaseItem((ItemInfo)info, internalName, itemName, createTile, shoot, createWall, toolTip, itemTexture));
else
itemsToLoad.TryAdd(internalName, new BaseItem((ItemInfo)info, internalName, itemName, createTile, shoot, createWall, toolTip));
reader.Dispose();
//}
}
private static void CreateNPC(object stateInfo) { // This is literally just to simplify threading and progress counting
object[] parameters = (object[])stateInfo;
CountdownEvent countdown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreateNPC(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countdown.Signal();
}
private static void CreateNPC(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) { // I don't know how this works either
List<(int, int?, string, float)> dropList = new List<(int, int?, string, float)>();
MemoryStream iniStream = streams[fileName];
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
object info = new NpcInfo();
string npcName = Path.GetFileNameWithoutExtension(fileName);
string internalName = $"{modName}:{npcName.RemoveIllegalCharacters()}";
bool logNPCAndModName = false;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
switch (section.Name) {
case "Stats": {
var splitElement = element.Content.Split('=');
string split1Correct = ConvertField13(splitElement[0]);
var statField = typeof(NpcInfo).GetField(split1Correct);
switch (splitElement[0]) {
case "soundHit": {
var soundStyleID = int.Parse(splitElement[1]);
var soundStyle = new LegacySoundStyle(3, soundStyleID); // All NPC hit sounds use 3
statField = typeof(NpcInfo).GetField("HitSound");
statField.SetValue(info, soundStyle);
continue;
}
case "soundKilled": {
var soundStyleID = int.Parse(splitElement[1]);
var soundStyle = new LegacySoundStyle(4, soundStyleID); // All death sounds use 4
statField = typeof(NpcInfo).GetField("DeathSound");
statField.SetValue(info, soundStyle);
continue;
}
case "type":
continue;
default: {
if (statField == null) {
mod.Logger.Debug($"NPC field not found or invalid field! -> {splitElement[0]}");
logNPCAndModName = true;
tConfigWrapper.ReportErrors = true;
continue;
}
break;
}
}
TypeConverter converter = TypeDescriptor.GetConverter(statField.FieldType);
object realValue = converter.ConvertFromString(splitElement[1]);
statField.SetValue(info, realValue);
break;
}
case "Buff Immunities": {
var splitElement = element.Content.Split('=');
splitElement[0].Replace(" ", "").Replace("!", "");
FieldInfo npcInfoImmunity = typeof(NpcInfo).GetField("buffImmune");
if (BuffID.Search.ContainsName(splitElement[0])) { // Will 100% need to adjust this once we get mod buff loading implemented
bool[] immunity = new bool[BuffLoader.BuffCount];
immunity[BuffID.Search.GetId(splitElement[0])] = bool.Parse(splitElement[1]);
npcInfoImmunity.SetValue(info, immunity);
}
else
mod.Logger.Debug($"{splitElement[0]} doesn't exist!"); // Will have to manually convert
break;
}
case "Drops":
// example of drop string: 1-4 Golden Flame=0.7
string dropRangeString = element.Content.Split(new[] { ' ' }, 2)[0]; // This gets the drop range, everthing before the first space
string dropItemString = element.Content.Split(new[] { ' ' }, 2)[1].Split('=')[0]; // This gets everything after the first space, then it splits at the = and gets everything before it
string dropChanceString = element.Content.Split('=')[1]; // Gets everything after the = sign
int min;
int? max = null;
if (dropRangeString.Contains("-")) {
min = int.Parse(dropRangeString.Split('-')[0]);
max = int.Parse(dropRangeString.Split('-')[1]) + 1; // + 1 because the max is exclusive in Main.rand.Next()
}
else {
min = int.Parse(dropRangeString);
}
dropList.Add((min, max, $"{modName}:{dropItemString}", float.Parse(dropChanceString) / 100));
break;
}
}
}
if (logNPCAndModName)
mod.Logger.Debug($"{internalName}"); //Logs the npc and mod name if "Field not found or invalid field". Mod and npc name show up below the other log line
// Check if a texture for the .ini file exists
string texturePath = Path.ChangeExtension(fileName, "png");
Texture2D npcTexture = null;
if (!Main.dedServ && streams.TryGetValue(texturePath, out MemoryStream textureStream)) {
npcTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, textureStream); // Load a Texture2D from the stream
}
if (npcTexture != null)
npcsToLoad.TryAdd(internalName, new BaseNPC((NpcInfo)info, dropList, npcName, npcTexture));
else
npcsToLoad.TryAdd(internalName, new BaseNPC((NpcInfo)info, dropList, npcName));
reader.Dispose();
}
private static void CreateTile(object stateInfo) { // This is literally for easier multithreading again
object[] parameters = (object[])stateInfo;
CountdownEvent countdown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreateTile(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countdown.Signal();
}
private static void CreateTile(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) { // I have no idea how this works either
Dictionary<string, int> tileNumberFields = new Dictionary<string, int>();
Dictionary<string, bool> tileBoolFields = new Dictionary<string, bool>();
Dictionary<string, string> tileStringFields = new Dictionary<string, string>();
MemoryStream iniStream = streams[fileName];
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
object info = new TileInfo();
string displayName = Path.GetFileNameWithoutExtension(fileName);
string internalName = $"{modName}:{displayName.RemoveIllegalCharacters()}";
bool logTileAndModName = false;
bool oreTile = false;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
if (section.Name == "Stats") {
var splitElement = element.Content.Split('=');
string converted = ConvertField13(splitElement[0]);
var statField = typeof(TileInfo).GetField(converted);
if ((converted == "tileShine" && splitElement[1] != "0") || displayName.Contains("Ore"))
oreTile = true;
switch (converted) {
case "minPick":
case "minAxe":
case "minHammer": {
if (converted == "minAxe")
splitElement[1] = (int.Parse(splitElement[1]) * 5).ToString();
statField = typeof(TileInfo).GetField("minPick");
int splitInt = int.Parse(splitElement[1]);
statField.SetValue(info, splitInt);
continue;
}
case "Width":
case "Height":
case "tileShine":
tileNumberFields.Add(converted, int.Parse(splitElement[1]));
continue;
case "tileLighted":
case "tileMergeDirt":
case "tileCut":
case "tileAlch":
case "tileShine2":
case "tileStone":
case "tileWaterDeath":
case "tileLavaDeath":
case "tileTable":
case "tileBlockLight":
case "tileNoSunLight":
case "tileDungeon":
case "tileSolidTop":
case "tileSolid":
case "tileNoAttach":
case "tileNoFail":
case "tileFrameImportant":
tileBoolFields.Add(converted, bool.Parse(splitElement[1]));
continue;
case "DropName":
tileStringFields.Add(converted, $"{modName}:{splitElement[1]}");
continue;
case "furniture": {
tileStringFields.Add(converted, splitElement[1]);
continue;
}
case "id":
case "type":
case "mineResist" when splitElement[1] == "0":
continue;
default: {
if (statField == null) {
mod.Logger.Debug($"Tile field not found or invalid field! -> {converted}");
logTileAndModName = true;
tConfigWrapper.ReportErrors = true;
continue;
}
break;
}
}
TypeConverter converter = TypeDescriptor.GetConverter(statField.FieldType);
object realValue = converter.ConvertFromString(splitElement[1]);
statField.SetValue(info, realValue);
}
}
}
string texturePath = Path.ChangeExtension(fileName, "png");
Texture2D tileTexture = null;
if (!Main.dedServ && streams.TryGetValue(texturePath, out MemoryStream textureStream)) {
tileTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, textureStream);
}
if (tileTexture != null) {
BaseTile baseTile = new BaseTile((TileInfo)info, internalName, tileTexture, tileBoolFields, tileNumberFields, tileStringFields);
tilesToLoad.TryAdd(internalName, (baseTile, "tConfigWrapper/Common/DataTemplates/MissingTexture"));
tileMapData.TryAdd(baseTile, (oreTile, displayName));
}
if (logTileAndModName)
mod.Logger.Debug($"{internalName}"); //Logs the tile and mod name if "Field not found or invalid field". Mod and tile name show up below the other log lines
}
private static int mapIterationCount;
public static void GetMapEntries() { // Loads tile map entries
mapIterationCount = 0;
LoadProgressText?.Invoke("tConfig Wrapper: Loading Map Entries");
LoadProgress?.Invoke(0f);
SetupRecipes(); // Check what tiles are used in recipes so it can add a name to it
int mapContentCount = tileMapData.Count + wallsToLoad.Count;
using (CountdownEvent finished = new CountdownEvent(1)) {
if (mapContentCount != 0) {
Thread tileMapEntryThread = new Thread(GetTileMapEntries);
tileMapEntryThread.Start(finished);
finished.AddCount();
Thread wallMapEntryThread = new Thread(GetWallMapEntries);
wallMapEntryThread.Start(finished);
finished.AddCount();
finished.Signal();
finished.Wait();
}
}
}
private static void GetTileMapEntries(object stateInfo) {
CountdownEvent countdown = (CountdownEvent)stateInfo;
foreach (var (modTile, (display, name)) in tileMapData) {
mapIterationCount++;
LoadSubProgressText?.Invoke(name);
Texture2D tileTex = Main.tileTexture[modTile.Type];
Color[] colors = new Color[tileTex.Width * tileTex.Height];
tileTex.GetData(colors);
Color[,] colorsGrid = colors.To2DColor(tileTex.Width, tileTex.Height);
List<Color> noLineColor = new List<Color>();
//Iterates through the 2D array of colors but it removes unwanted pixels.
for (int x = 0; x < colorsGrid.GetLength(0); x++) {
for (int y = 0; y < colorsGrid.GetLength(1); y++) {
if (colorsGrid[x, y] != new Color(151, 107, 75) && colorsGrid[x, y] != new Color(114, 81, 56) && colorsGrid[x, y] != Color.Black && colorsGrid[x, y].A != 0 && (x + 1) % 18 > 1 && (y + 1) % 18 > 1)
noLineColor.Add(colorsGrid[x, y]);
}
}
int r = noLineColor.Sum(x => x.R) / noLineColor.Count;
int g = noLineColor.Sum(x => x.G) / noLineColor.Count;
int b = noLineColor.Sum(x => x.B) / noLineColor.Count;
Color averageColor = new Color(r, g, b);
if (display)
modTile.AddMapEntry(averageColor, Language.GetText(name));
else
modTile.AddMapEntry(averageColor);
LoadProgress?.Invoke(mapIterationCount / (tileMapData.Count + wallsToLoad.Count));
}
countdown.Signal();
}
private static void GetWallMapEntries(object stateInfo) {
CountdownEvent countdown = (CountdownEvent)stateInfo;
foreach (var (wallName, (modWall, texture)) in wallsToLoad) {
mapIterationCount++;
LoadSubProgressText?.Invoke(wallName);
Texture2D wallTex = Main.wallTexture[modWall.Type];
Color[] colors = new Color[wallTex.Width * wallTex.Height];
wallTex.GetData(colors);
Color[,] colorsGrid = colors.To2DColor(wallTex.Width, wallTex.Height);
List<Color> noLineColor = new List<Color>();
for (int x = 0; x < colorsGrid.GetLength(0); x++) {
for (int y = 0; y < colorsGrid.GetLength(1); y++) {
if (colorsGrid[x, y].A != 0 && (x + 3) % 36 > 3 && (y + 3) % 36 > 3)
noLineColor.Add(colorsGrid[x, y]);
}
}
int r = noLineColor.Sum(x => x.R) / noLineColor.Count;
int g = noLineColor.Sum(x => x.G) / noLineColor.Count;
int b = noLineColor.Sum(x => x.B) / noLineColor.Count;
Color averageColor = new Color(r, g, b);
modWall.AddMapEntry(averageColor);
LoadProgress?.Invoke(mapIterationCount / (tileMapData.Count + wallsToLoad.Count));
}
countdown.Signal();
}
private static void CreateProjectile(object stateInfo) { // This is literally for easier multithreading again
object[] parameters = (object[])stateInfo;
CountdownEvent countdown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreateProjectile(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countdown.Signal();
}
private static void CreateProjectile(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) {
MemoryStream iniStream = streams[fileName];
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
object info = new ProjectileInfo();
string projectileName = Path.GetFileNameWithoutExtension(fileName);
string internalName = $"{modName}:{projectileName.RemoveIllegalCharacters()}";
bool logProjectileAndModName = false;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
switch (section.Name) {
case "Stats": {
var splitElement = element.Content.Split('=');
var statField = typeof(ProjectileInfo).GetField(splitElement[0]);
switch (splitElement[0]) {
case "type": {
continue;
}
default: {
if (statField == null) {
mod.Logger.Debug($"Projectile field not found or invalid field! -> {splitElement[0]}");
logProjectileAndModName = true;
tConfigWrapper.ReportErrors = true;
continue;
}
break;
}
}
//Conversion garbage
TypeConverter converter = TypeDescriptor.GetConverter(statField.FieldType);
object realValue = converter.ConvertFromString(splitElement[1]);
statField.SetValue(info, realValue);
break;
}
}
}
}
string texturePath = Path.ChangeExtension(fileName, "png");
Texture2D projectileTexture = null;
if (!Main.dedServ && streams.TryGetValue(texturePath, out MemoryStream textureStream)) {
projectileTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, textureStream);
}
if (logProjectileAndModName) {
mod.Logger.Debug($"{internalName}");
}
if (projectileTexture != null)
projectilesToLoad.TryAdd(internalName, new BaseProjectile((ProjectileInfo)info, projectileName, projectileTexture));
else
projectilesToLoad.TryAdd(internalName, new BaseProjectile((ProjectileInfo)info, projectileName));
}
private static void CreateWall(object stateInfo) {
object[] parameters = (object[])stateInfo;
CountdownEvent countDown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreateWall(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countDown.Signal();
}
private static void CreateWall(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) {
MemoryStream iniStream = streams[fileName];
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
string internalName = $"{modName}:{Path.GetFileNameWithoutExtension(fileName).RemoveIllegalCharacters()}";
string dropItem = null;
string house = null;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
var splitElement = element.Content.Split('=');
switch (splitElement[0]) {
case "id":
case "Blend": {
if (int.Parse(splitElement[1]) != -1)
mod.Logger.Debug($"{internalName}.{splitElement[0]} was not -1!");
continue;
}
case "DropName": {
dropItem = $"{modName}:{splitElement[1].RemoveIllegalCharacters()}";
continue;
}
case "House": {
house = splitElement[1];
continue;
}
}
}
}
string texturePath = Path.ChangeExtension(fileName, "png");
Texture2D wallTexture = null;
if (!Main.dedServ && streams.TryGetValue(texturePath, out MemoryStream textureStream)) {
wallTexture = Texture2D.FromStream(Main.instance.GraphicsDevice, textureStream);
}
if (wallTexture != null)
wallsToLoad.TryAdd(internalName, (new BaseWall(dropItem, house, wallTexture), "tConfigWrapper/Common/DataTemplates/MissingTexture"));
}
private static void CreatePrefix(object stateInfo) {
object[] parameters = (object[])stateInfo;
CountdownEvent countDown = (CountdownEvent)parameters[3];
foreach (var fileName in (IEnumerable<string>)parameters[0]) {
LoadSubProgressText?.Invoke(fileName);
CreatePrefix(fileName, (string)parameters[1], (string)parameters[2], (ConcurrentDictionary<string, MemoryStream>)parameters[6]);
TaskCompletedCount++;
LoadProgress?.Invoke((float)TaskCompletedCount / (int)parameters[5]);
}
countDown.Signal();
}
private static void CreatePrefix(string fileName, string modName, string extractPath, ConcurrentDictionary<string, MemoryStream> streams) {
MemoryStream iniStream = streams[fileName];
Dictionary<string, string> itemFields = new Dictionary<string, string>();
Dictionary<string, string> playerFields = new Dictionary<string, string>();
IniFileReader reader = new IniFileReader(iniStream);
IniFile iniFile = IniFile.FromStream(reader);
string internalName = $"{modName}:{Path.GetFileNameWithoutExtension(fileName).RemoveIllegalCharacters()}";
bool addToSuffixBag = false;
string name = null;
string requirementType = null;
string weight = null;
foreach (IniFileSection section in iniFile.sections) {
foreach (IniFileElement element in section.elements) {
var splitElement = element.Content.Split('=');
switch (section.Name) {
case "Stats": {
switch (splitElement[0]) {
case "name": {
name = splitElement[1];
continue;
}
case "suffix" when splitElement[1] == "True": {
addToSuffixBag = true;
continue;
}
case "weight": {
weight = splitElement[1];
continue;
}
}
break;
}
case "Requirements": {
switch (splitElement[0]) {
case "melee" when splitElement[1] == "True":
case "ranged" when splitElement[1] == "True":
case "magic" when splitElement[1] == "True":
case "accessory" when splitElement[1] == "True": {
requirementType = splitElement[0];
continue;
}
}
continue;
}
case "Item": {
itemFields.Add(splitElement[0], splitElement[1]);