/
moduleManager.cs
3274 lines (2793 loc) · 125 KB
/
moduleManager.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 System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using TMPro;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace ModuleManager
{
[KSPAddon(KSPAddon.Startup.Instantly, false)]
public class ModuleManager : MonoBehaviour
{
#region state
private bool inRnDCenter;
private bool reloading;
public bool showUI = false;
private Rect windowPos = new Rect(80f, 60f, 240f, 40f);
private string version = "";
//private Texture2D tex;
//private Texture2D tex2;
private Sprite[] catFrames;
private Texture2D rainbow;
private bool nyan = false;
private PopupDialog menu;
#endregion state
#region Top Level - Update
private static bool loadedInScene;
internal void OnRnDCenterSpawn()
{
inRnDCenter = true;
}
internal void OnRnDCenterDeSpawn()
{
inRnDCenter = false;
}
public static void log(String s)
{
print("[ModuleManager] " + s);
}
private Stopwatch totalTime = new Stopwatch();
internal void Awake()
{
totalTime.Start();
// Allow loading the background in the laoding screen
Application.runInBackground = true;
// Ensure that only one copy of the service is run per scene change.
if (loadedInScene || !ElectionAndCheck())
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
log("Multiple copies of current version. Using the first copy. Version: " +
currentAssembly.GetName().Version);
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
Version v = Assembly.GetExecutingAssembly().GetName().Version;
version = v.Major + "." + v.Minor + "." + v.Build;
// Subscribe to the RnD center spawn/deSpawn events
GameEvents.onGUIRnDComplexSpawn.Add(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Add(OnRnDCenterDeSpawn);
LoadingScreen screen = FindObjectOfType<LoadingScreen>();
if (screen == null)
{
log("Can't find LoadingScreen type. Aborting ModuleManager execution");
return;
}
List<LoadingSystem> list = LoadingScreen.Instance.loaders;
if (list != null)
{
// So you can insert a LoadingSystem object in this list at any point.
// GameDatabase is first in the list, and PartLoader is second
// We could insert ModuleManager after GameDatabase to get it to run there
// and SaveGameFixer after PartLoader.
GameObject aGameObject = new GameObject("ModuleManager");
MMPatchLoader loader = aGameObject.AddComponent<MMPatchLoader>();
log(string.Format("Adding ModuleManager to the loading screen {0}", list.Count));
int gameDatabaseIndex = list.FindIndex(s => s is GameDatabase);
list.Insert(gameDatabaseIndex + 1, loader);
}
nyan = (DateTime.Now.Month == 4 && DateTime.Now.Day == 1)
|| (DateTime.Now < new DateTime(2016, 11, 1))
|| Environment.GetCommandLineArgs().Contains("-nyan-nyan");
loadedInScene = true;
}
private TextMeshProUGUI status;
private TextMeshProUGUI errors;
private TextMeshProUGUI warning;
private void Start()
{
SendCatToLaunchBay();
Canvas canvas = LoadingScreen.Instance.GetComponentInChildren<Canvas>();
status = CreateTextObject(canvas, "MMStatus");
errors = CreateTextObject(canvas, "MMErrors");
warning = CreateTextObject(canvas, "MMWarning");
warning.text = "";
//if (Versioning.version_major == 1 && Versioning.version_minor == 0 && Versioning.Revision == 5 && Versioning.BuildID == 1024)
//{
// warning.text = "Your KSP 1.0.5 is running on build 1024. You should upgrade to build 1028 to avoid problems with addons.";
// //if (GUI.Button(new Rect(Screen.width / 2f - 100, offsetY, 200, 20), "Click to open the Forum thread"))
// // Application.OpenURL("http://forum.kerbalspaceprogram.com/index.php?/topic/124998-silent-patch-for-ksp-105-published/");
//}
}
private TextMeshProUGUI CreateTextObject(Canvas canvas, string name)
{
GameObject statusGameObject = new GameObject(name);
TextMeshProUGUI text = statusGameObject.AddComponent<TextMeshProUGUI>();
text.text = "STATUS";
text.fontSize = 16;
text.autoSizeTextContainer = true;
text.font = Resources.Load("Fonts/Calibri SDF", typeof(TMP_FontAsset)) as TMP_FontAsset;
text.alignment = TextAlignmentOptions.Center;
text.enableWordWrapping = false;
text.isOverlay = true;
statusGameObject.transform.SetParent(canvas.transform);
return text;
}
private void SendCatToLaunchBay()
{
if (!nyan)
return;
// Nyancat are GO !!!
Texture2D[] tex = new Texture2D[12];
for (int i = 0; i < tex.Length; i++)
{
tex[i] = new Texture2D(70, 42, TextureFormat.ARGB32, false);
}
tex[0].LoadImage(Properties.Resources.cat1);
tex[1].LoadImage(Properties.Resources.cat2);
tex[2].LoadImage(Properties.Resources.cat3);
tex[3].LoadImage(Properties.Resources.cat4);
tex[4].LoadImage(Properties.Resources.cat5);
tex[5].LoadImage(Properties.Resources.cat6);
tex[6].LoadImage(Properties.Resources.cat7);
tex[7].LoadImage(Properties.Resources.cat8);
tex[8].LoadImage(Properties.Resources.cat9);
tex[9].LoadImage(Properties.Resources.cat10);
tex[10].LoadImage(Properties.Resources.cat11);
tex[11].LoadImage(Properties.Resources.cat12);
rainbow = new Texture2D(39, 36, TextureFormat.ARGB32, false);
rainbow.LoadImage(Properties.Resources.rainbow);
rainbow.Apply();
catFrames = new Sprite[12];
for (int i = 0; i < tex.Length; i++)
{
tex[i].Apply();
catFrames[i] = Sprite.Create(tex[i], new Rect(0, 0, tex[i].width, tex[i].height), new Vector2(.5f, .5f));
catFrames[i].name = "cat" + i;
}
GameObject cat = new GameObject("NyanCat");
SpriteRenderer sr = cat.AddComponent<SpriteRenderer>();
TrailRenderer trail = cat.AddComponent<TrailRenderer>();
CatMover catMover = cat.AddComponent<CatMover>();
sr.sprite = catFrames[0];
trail.material = new Material(Shader.Find("Particles/Alpha Blended"));
Debug.Log("material = " + trail.material);
trail.material.mainTexture = rainbow;
trail.time = 1.5f;
trail.startWidth = rainbow.height;
trail.endWidth = rainbow.height * 0.9f;
cat.layer = LayerMask.NameToLayer("UI");
catMover.frames = catFrames;
int scale = 70;
scale *= 1;
if (Screen.height >= 1080)
scale *= 2;
if (Screen.height > 1440)
scale *= 3;
cat.transform.localScale = scale * Vector3.one;
}
// Unsubscribe from events when the behavior dies
internal void OnDestroy()
{
GameEvents.onGUIRnDComplexSpawn.Remove(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Remove(OnRnDCenterDeSpawn);
}
internal void Update()
{
if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F11)
&& (HighLogic.LoadedScene == GameScenes.SPACECENTER || HighLogic.LoadedScene == GameScenes.MAINMENU)
&& !inRnDCenter)
{
if (menu == null)
{
menu = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
new Vector2(0.5f, 0.5f),
new MultiOptionDialog(
"ModuleManagerMenu",
"",
"ModuleManager",
HighLogic.UISkin,
new Rect(0.5f, 0.5f, 150f, 60f),
new DialogGUIFlexibleSpace(),
new DialogGUIVerticalLayout(
new DialogGUIFlexibleSpace(),
new DialogGUIButton("Reload Database",
delegate
{
MMPatchLoader.keepPartDB = false;
StartCoroutine(DataBaseReloadWithMM());
}, 140.0f, 30.0f, true),
new DialogGUIButton("Quick Reload Database",
delegate
{
MMPatchLoader.keepPartDB = true;
StartCoroutine(DataBaseReloadWithMM());
}, 140.0f, 30.0f, true),
new DialogGUIButton("Dump Database to Files",
delegate
{
StartCoroutine(DataBaseReloadWithMM(true));
}, 140.0f, 30.0f, true),
new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
)),
false,
HighLogic.UISkin);
}
else
{
menu.Dismiss();
menu = null;
}
}
if (totalTime.IsRunning && HighLogic.LoadedScene == GameScenes.MAINMENU)
{
totalTime.Stop();
log("Total loading Time = " + ((float)totalTime.ElapsedMilliseconds / 1000).ToString("F3") + "s");
Application.runInBackground = GameSettings.SIMULATE_IN_BACKGROUND;
}
float offsetY = Mathf.FloorToInt(0.23f * Screen.height);
float h;
if (warning)
{
warning.transform.localPosition = new Vector3(0, -offsetY);
h = warning.textBounds.size.y;
if (h > 0)
offsetY = offsetY + h + 10;
}
if (status)
{
status.transform.localPosition = new Vector3(0, -offsetY);
status.text = MMPatchLoader.Instance.status;
h = status.textBounds.size.y;
if (h > 0)
offsetY = offsetY + h + 10;
}
if (errors)
{
errors.transform.localPosition = new Vector3(0, -offsetY);
errors.text = MMPatchLoader.Instance.errors;
}
if (reloading)
{
float percent = 0;
if (!GameDatabase.Instance.IsReady())
percent = GameDatabase.Instance.ProgressFraction();
else if (!MMPatchLoader.Instance.IsReady())
percent = 1f + MMPatchLoader.Instance.ProgressFraction();
else if (!PartLoader.Instance.IsReady())
percent = 2f + PartLoader.Instance.ProgressFraction();
int intPercent = Mathf.CeilToInt(percent * 100f / 3f);
ScreenMessages.PostScreenMessage("Database reloading " + intPercent + "%", Time.deltaTime,
ScreenMessageStyle.UPPER_CENTER);
}
}
#region GUI stuff.
internal static IntPtr intPtr = new IntPtr(long.MaxValue);
/* Not required anymore. At least
public static bool IsABadIdea()
{
return (intPtr.ToInt64() == long.MaxValue) && (Environment.OSVersion.Platform == PlatformID.Win32NT);
}
*/
private IEnumerator DataBaseReloadWithMM(bool dump = false)
{
reloading = true;
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
ScreenMessages.PostScreenMessage("Database reloading started", 1, ScreenMessageStyle.UPPER_CENTER);
yield return null;
GameDatabase.Instance.Recompile = true;
GameDatabase.Instance.StartLoad();
// wait for it to finish
while (!GameDatabase.Instance.IsReady())
yield return null;
MMPatchLoader.Instance.StartLoad();
while (!MMPatchLoader.Instance.IsReady())
yield return null;
log("DB Reload OK with patchCount=" + MMPatchLoader.Instance.patchedNodeCount + " errorCount=" +
MMPatchLoader.Instance.errorCount + " needsUnsatisfiedCount=" +
MMPatchLoader.Instance.needsUnsatisfiedCount + " exceptionCount=" + MMPatchLoader.Instance.exceptionCount);
PartResourceLibrary.Instance.LoadDefinitions();
PartUpgradeManager.Handler.FillUpgrades();
if (dump)
OutputAllConfigs();
PartLoader.Instance.StartLoad();
while (!PartLoader.Instance.IsReady())
yield return null;
// Needs more work.
//ConfigNode game = HighLogic.CurrentGame.config.GetNode("GAME");
//if (game != null && ResearchAndDevelopment.Instance != null)
//{
// ScreenMessages.PostScreenMessage("GAME found");
// ConfigNode scenario = game.GetNodes("SCENARIO").FirstOrDefault((ConfigNode n) => n.name == "ResearchAndDevelopment");
// if (scenario != null)
// {
// ScreenMessages.PostScreenMessage("SCENARIO found");
// ResearchAndDevelopment.Instance.OnLoad(scenario);
// }
//}
QualitySettings.vSyncCount = GameSettings.SYNC_VBL;
Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;
reloading = false;
ScreenMessages.PostScreenMessage("Database reloading finished", 1, ScreenMessageStyle.UPPER_CENTER);
}
private static void OutputAllConfigs()
{
string path = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "_MMCfgOutput"
+ Path.DirectorySeparatorChar;
Directory.CreateDirectory(path);
foreach (UrlDir.UrlConfig d in GameDatabase.Instance.root.AllConfigs)
File.WriteAllText(path + d.url.Replace('/', '.') + ".cfg", d.config.ToString());
}
#endregion GUI stuff.
public bool ElectionAndCheck()
{
#region Type election
// TODO : Move the old version check in a process that call Update.
// Check for old version and MMSarbianExt
IEnumerable<AssemblyLoader.LoadedAssembly> oldMM =
AssemblyLoader.loadedAssemblies.Where(
a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name)
.Where(a => a.assembly.GetName().Version.CompareTo(new System.Version(1, 5, 0)) == -1);
IEnumerable<AssemblyLoader.LoadedAssembly> oldAssemblies =
oldMM.Concat(AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == "MMSarbianExt"));
if (oldAssemblies.Any())
{
IEnumerable<string> badPaths =
oldAssemblies.Select(a => a.path)
.Select(
p =>
Uri.UnescapeDataString(
new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p))
.ToString()
.Replace('/', Path.DirectorySeparatorChar)));
string status =
"You have old versions of Module Manager (older than 1.5) or MMSarbianExt.\nYou will need to remove them for Module Manager and the mods using it to work\nExit KSP and delete those files :\n" +
String.Join("\n", badPaths.ToArray());
PopupDialog.SpawnPopupDialog(new Vector2(0f, 1f), new Vector2(0f, 1f), "ModuleManagerOldVersions", "Old versions of Module Manager", status, "OK", false, UISkinManager.defaultSkin);
log("Old version of Module Manager present. Stopping");
return false;
}
//PopupDialog.SpawnPopupDialog(new Vector2(0.1f, 1f), new Vector2(0.2f, 1f), "Test of the dialog", "Stuff", "OK", false, UISkinManager.defaultSkin);
Assembly currentAssembly = Assembly.GetExecutingAssembly();
IEnumerable<AssemblyLoader.LoadedAssembly> eligible = from a in AssemblyLoader.loadedAssemblies
let ass = a.assembly
where ass.GetName().Name == currentAssembly.GetName().Name
orderby ass.GetName().Version descending, a.path ascending
select a;
// Elect the newest loaded version of MM to process all patch files.
// If there is a newer version loaded then don't do anything
// If there is a same version but earlier in the list, don't do anything either.
if (eligible.First().assembly != currentAssembly)
{
//loaded = true;
log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
" lost the election");
Destroy(gameObject);
return false;
}
string candidates = "";
foreach (AssemblyLoader.LoadedAssembly a in eligible)
{
if (currentAssembly.Location != a.path)
candidates += "Version " + a.assembly.GetName().Version + " " + a.path + " " + "\n";
}
if (candidates.Length > 0)
{
log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
" won the election against\n" + candidates);
}
#endregion Type election
return true;
}
}
public delegate void ModuleManagerPostPatchCallback();
[SuppressMessage("ReSharper", "StringLastIndexOfIsCultureSpecific.1")]
[SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
public class MMPatchLoader : LoadingSystem
{
public int totalPatchCount = 0;
public int appliedPatchCount = 0;
public int patchedNodeCount = 0;
public int errorCount = 0;
public int exceptionCount = 0;
public int needsUnsatisfiedCount = 0;
private int catEatenCount = 0;
private Dictionary<String, int> errorFiles;
private List<string> mods;
public string status = "";
public string errors = "";
public static bool keepPartDB = false;
private string activity = "Module Manager";
private static readonly Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
private static readonly Stack<ConfigNode> nodeStack = new Stack<ConfigNode>();
private static ConfigNode topNode;
private static string cachePath;
internal static string techTreeFile;
internal static string techTreePath;
internal static string physicsFile;
internal static string physicsPath;
private static string defaultPhysicsPath;
internal static string partDatabasePath;
private static string shaPath;
private UrlDir.UrlFile physicsUrlFile;
private string configSha;
private Dictionary<string, string> filesSha = new Dictionary<string, string>();
private bool useCache = false;
private readonly Stopwatch patchSw = new Stopwatch();
private static readonly List<ModuleManagerPostPatchCallback> postPatchCallbacks = new List<ModuleManagerPostPatchCallback>();
private const float yieldInterval = 1f/30f; // Patch at ~30fps
public static MMPatchLoader Instance { get; private set; }
private void Awake()
{
if (Instance != null)
{
DestroyImmediate(this);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
cachePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "GameData" + Path.DirectorySeparatorChar + "ModuleManager.ConfigCache";
techTreeFile = "GameData" + Path.DirectorySeparatorChar + "ModuleManager.TechTree";
techTreePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + techTreeFile;
physicsFile = "GameData" + Path.DirectorySeparatorChar + "ModuleManager.Physics";
physicsPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + physicsFile;
defaultPhysicsPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "Physics.cfg";
partDatabasePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "PartDatabase.cfg";
shaPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "GameData" + Path.DirectorySeparatorChar + "ModuleManager.ConfigSHA";
}
private bool ready;
public override bool IsReady()
{
//return false;
if (ready)
{
patchSw.Stop();
log("Ran in " + ((float)patchSw.ElapsedMilliseconds / 1000).ToString("F3") + "s");
}
return ready;
}
public override float ProgressFraction()
{
if (totalPatchCount > 0)
return (appliedPatchCount + needsUnsatisfiedCount) / (float)totalPatchCount;
return 0;
}
public override string ProgressTitle()
{
return activity;
}
public override void StartLoad()
{
StartLoad(false);
}
public void Update()
{
if (appliedPatchCount > 0 && HighLogic.LoadedScene == GameScenes.LOADING)
StatusUpdate();
}
public void StartLoad(bool blocking)
{
patchSw.Reset();
patchSw.Start();
totalPatchCount = 0;
appliedPatchCount = 0;
patchedNodeCount = 0;
errorCount = 0;
needsUnsatisfiedCount = 0;
errorFiles = new Dictionary<string, int>();
#endregion Top Level - Update
ready = false;
// DB check used to track the now fixed TextureReplacer corruption
//checkValues();
StartCoroutine(ProcessPatch(blocking), blocking);
}
public static void addPostPatchCallback(ModuleManagerPostPatchCallback callback)
{
if (!postPatchCallbacks.Contains(callback))
postPatchCallbacks.Add(callback);
}
private List<string> PrePatchInit()
{
#region Excluding directories
// Build a list of subdirectory that won't be processed
List<string> excludePaths = new List<string>();
//if (ModuleManager.IsABadIdea())
//{
// foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs)
// {
// if (mod.name == "MODULEMANAGER[NOWIN64]")
// {
// string fullpath = mod.url.Substring(0, mod.url.LastIndexOf('/'));
// string excludepath = fullpath.Substring(0, fullpath.LastIndexOf('/'));
// excludePaths.Add(excludepath);
// log("excludepath: " + excludepath);
// }
// }
// if (excludePaths.Any())
// log("will not process patches in these subdirectories since they were disbaled on KSP Win64:\n" + String.Join("\n", excludePaths.ToArray()));
//}
#endregion Excluding directories
#region List of mods
//string envInfo = "ModuleManager env info\n";
//envInfo += " " + Environment.OSVersion.Platform + " " + ModuleManager.intPtr.ToInt64().ToString("X16") + "\n";
//envInfo += " " + Convert.ToString(ModuleManager.intPtr.ToInt64(), 2) + " " + Convert.ToString(ModuleManager.intPtr.ToInt64() >> 63, 2) + "\n";
//string gamePath = Environment.GetCommandLineArgs()[0];
//envInfo += " Args: " + gamePath.Split(Path.DirectorySeparatorChar).Last() + " " + string.Join(" ", Environment.GetCommandLineArgs().Skip(1).ToArray()) + "\n";
//envInfo += " Executable SHA256 " + FileSHA(gamePath);
//
//log(envInfo);
mods = new List<string>();
string modlist = "compiling list of loaded mods...\nMod DLLs found:\n";
foreach (AssemblyLoader.LoadedAssembly mod in AssemblyLoader.loadedAssemblies)
{
if (string.IsNullOrEmpty(mod.assembly.Location)) //Diazo Edit for xEvilReeperx AssemblyReloader mod
continue;
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(mod.assembly.Location);
AssemblyName assemblyName = mod.assembly.GetName();
string modInfo = " " + assemblyName.Name
+ " v" + assemblyName.Version
+
(fileVersionInfo.ProductVersion != " " && fileVersionInfo.ProductVersion != assemblyName.Version.ToString()
? " / v" + fileVersionInfo.ProductVersion
: "")
+
(fileVersionInfo.FileVersion != " " &&fileVersionInfo.FileVersion != assemblyName.Version.ToString() && fileVersionInfo.FileVersion != fileVersionInfo.ProductVersion
? " / v" + fileVersionInfo.FileVersion
: "");
modlist += String.Format(" {0,-50} SHA256 {1}\n", modInfo, FileSHA(mod.assembly.Location));
if (!mods.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase))
mods.Add(assemblyName.Name);
}
modlist += "Non-DLL mods added (:FOR[xxx]):\n";
foreach (UrlDir.UrlConfig cfgmod in GameDatabase.Instance.root.AllConfigs)
{
string name;
if (ParseCommand(cfgmod.type, out name) != Command.Insert)
{
totalPatchCount++;
if (name.Contains(":FOR["))
{
name = RemoveWS(name);
// check for FOR[] blocks that don't match loaded DLLs and add them to the pass list
try
{
string dependency = name.Substring(name.IndexOf(":FOR[") + 5);
dependency = dependency.Substring(0, dependency.IndexOf(']'));
if (!mods.Contains(dependency, StringComparer.OrdinalIgnoreCase))
{
// found one, now add it to the list.
mods.Add(dependency);
modlist += " " + dependency + "\n";
}
}
catch (ArgumentOutOfRangeException)
{
log("Skipping :FOR init for line " + name +
". The line most likely contains a space that should be removed");
errorCount++;
}
}
}
}
modlist += "Mods by directory (sub directories of GameData):\n";
string gameData = Path.Combine(Path.GetFullPath(KSPUtil.ApplicationRootPath), "GameData");
foreach (string subdir in Directory.GetDirectories(gameData))
{
string name = Path.GetFileName(subdir);
string cleanName = RemoveWS(name);
if (!mods.Contains(cleanName, StringComparer.OrdinalIgnoreCase))
{
mods.Add(cleanName);
modlist += " " + cleanName + "\n";
}
}
log(modlist);
mods.Sort();
return excludePaths;
#endregion List of mods
}
Coroutine StartCoroutine(IEnumerator enumerator, bool blocking)
{
if (blocking)
{
while (enumerator.MoveNext()) { }
return null;
}
else
{
return StartCoroutine(enumerator);
}
}
private IEnumerator ProcessPatch(bool blocking)
{
status = "Checking Cache";
log(status);
yield return null;
try
{
IsCacheUpToDate();
}
catch (Exception ex)
{
log("Exception in IsCacheUpToDate : " + ex.Message + "\n" + ex.StackTrace);
useCache = false;
}
#if DEBUG
//useCache = false;
#endif
status = "Pre patch init";
log(status);
yield return null;
List<string> excludePaths = PrePatchInit();
if (!useCache)
{
yield return null;
// If we don't use the cache then it is best to clean the PartDatabase.cfg
if (!keepPartDB && File.Exists(partDatabasePath))
File.Delete(partDatabasePath);
LoadPhysicsConfig();
#region Check Needs
// Do filtering with NEEDS
status = "Checking NEEDS.";
log(status);
yield return null;
CheckNeeds(excludePaths);
#endregion Check Needs
#region Applying patches
status = "Applying patches";
log(status);
yield return null;
// :First node
yield return StartCoroutine(ApplyPatch(excludePaths, ":FIRST"), blocking);
// any node without a :pass
yield return StartCoroutine(ApplyPatch(excludePaths, ":LEGACY"), blocking);
foreach (string mod in mods)
{
string upperModName = mod.ToUpper();
yield return StartCoroutine(ApplyPatch(excludePaths, ":BEFORE[" + upperModName + "]"), blocking);
yield return StartCoroutine(ApplyPatch(excludePaths, ":FOR[" + upperModName + "]"), blocking);
yield return StartCoroutine(ApplyPatch(excludePaths, ":AFTER[" + upperModName + "]"), blocking);
}
// :Final node
yield return StartCoroutine(ApplyPatch(excludePaths, ":FINAL"), blocking);
PurgeUnused(excludePaths);
#endregion Applying patches
#region Logging
if (errorCount > 0 || exceptionCount > 0)
{
foreach (string file in errorFiles.Keys)
{
errors += errorFiles[file] + " error" + (errorFiles[file] > 1 ? "s" : "") + " related to GameData/" + file
+ "\n";
}
log("Errors in patch prevents the creation of the cache");
try
{
if (File.Exists(cachePath))
File.Delete(cachePath);
if (File.Exists(shaPath))
File.Delete(shaPath);
}
catch (Exception e)
{
log("Exception while deleting stale cache " + e);
}
}
else
{
status = "Saving Cache";
log(status);
yield return null;
CreateCache();
}
SaveModdedTechTree();
SaveModdedPhysics();
}
else
{
status = "Loading from Cache";
log(status);
yield return null;
LoadCache();
}
StatusUpdate();
log(status + "\n" + errors);
#endregion Logging
#if DEBUG
RunTestCases();
#endif
// TODO : Remove if we ever get a way to load sooner
log("Reloading resources definitions");
PartResourceLibrary.Instance.LoadDefinitions();
log("Reloading Trait configs");
GameDatabase.Instance.ExperienceConfigs.LoadTraitConfigs();
log("Reloading Part Upgrades");
PartUpgradeManager.Handler.FillUpgrades();
foreach (ModuleManagerPostPatchCallback callback in postPatchCallbacks)
{
try
{
callback();
}
catch (Exception e)
{
log("Exception while running a post patch callback\n" + e);
}
yield return null;
}
yield return null;
// Call all "public static void ModuleManagerPostLoad()" on all class
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (Type type in ass.GetTypes())
{
MethodInfo method = type.GetMethod("ModuleManagerPostLoad", BindingFlags.Public | BindingFlags.Static);
if (method != null && method.GetParameters().Length == 0)
{
try
{
log("Calling " + ass.GetName().Name + "." + type.Name + "." + method.Name + "()");
method.Invoke(null, null);
}
catch (Exception e)
{
log("Exception while calling " + ass.GetName().Name + "." + type.Name + "." + method.Name + "() :\n" + e);
}
}
}
}
catch (Exception e)
{
log("Post run call threw an exception in loading " + ass.FullName + ": " + e);
}
}
yield return null;
// Call "public void ModuleManagerPostLoad()" on all active MonoBehaviour instance
foreach (MonoBehaviour obj in FindObjectsOfType<MonoBehaviour>())
{
MethodInfo method = obj.GetType().GetMethod("ModuleManagerPostLoad", BindingFlags.Public | BindingFlags.Instance);
if (method != null && method.GetParameters().Length == 0)
{
try
{
log("Calling " + obj.GetType().Name + "." + method.Name + "()");
method.Invoke(obj, null);
}
catch (Exception e)
{
log("Exception while calling " + obj.GetType().Name + "." + method.Name + "() :\n" + e);
}
}
}
yield return null;
ready = true;
}
private void LoadPhysicsConfig()
{
log("Loading Physics.cfg");
UrlDir gameDataDir = GameDatabase.Instance.root.AllDirectories.First(d => d.path.EndsWith("GameData") && d.name == "" && d.url == "");
// need to use a file with a cfg extenssion to get the right fileType or you can't AddConfig on it
physicsUrlFile = new UrlDir.UrlFile(gameDataDir, new FileInfo(defaultPhysicsPath));
// Since it loaded the default config badly (sub node only) we clear it first
physicsUrlFile.configs.Clear();
// And reload it properly
ConfigNode physicsContent = ConfigNode.Load(defaultPhysicsPath);
physicsContent.name = "PHYSICSGLOBALS";
physicsUrlFile.AddConfig(physicsContent);
gameDataDir.files.Add(physicsUrlFile);
}
private void SaveModdedPhysics()
{
List<UrlDir.UrlConfig> configs = physicsUrlFile.configs;
if (configs.Count == 0)
{
log("No PHYSICSGLOBALS node found. No custom Physics config will be saved");
return;
}
if (configs.Count > 1)