-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathkOSProcessor.cs
More file actions
1221 lines (1049 loc) · 51.6 KB
/
Copy pathkOSProcessor.cs
File metadata and controls
1221 lines (1049 loc) · 51.6 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
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 kOS.Binding;
using kOS.Callback;
using kOS.Execution;
using kOS.Communication;
using kOS.Persistence;
using kOS.Safe;
using kOS.Safe.Serialization;
using kOS.Safe.Compilation;
using kOS.Safe.Compilation.KS;
using kOS.Safe.Module;
using kOS.Safe.Persistence;
using kOS.Safe.Screen;
using kOS.Safe.Utilities;
using kOS.Utilities;
using KSP.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using kOS.Safe.Execution;
using UnityEngine;
using kOS.Safe.Encapsulation;
using KSP.UI;
using kOS.Suffixed;
using kOS.Safe.Function;
namespace kOS.Module
{
public class kOSProcessor : PartModule, IProcessor, IPartCostModifier, IPartMassModifier
{
private const string PAWGroup = "kOS";
public ProcessorModes ProcessorMode { get; private set; }
public Harddisk HardDisk { get; private set; }
public Archive Archive { get; private set; }
public MessageQueue Messages { get; private set; }
private static bool bootListDirty;
public string Tag
{
get
{
KOSNameTag tag = part.Modules.OfType<KOSNameTag>().FirstOrDefault();
return tag == null ? string.Empty : tag.nameTag;
}
set
{
KOSNameTag tag = part.Modules.OfType<KOSNameTag>().FirstOrDefault();
// Really a null tag shouldn't ever happen. It would mean kOS is installed but KOSNameTag's aren't on all the things.
// And that should only happen if someone has a bad ModuleManager config that's screwing with kOS.
if (tag != null)
tag.nameTag = value;
}
}
private int vesselPartCount;
private SharedObjects shared;
private static readonly List<kOSProcessor> allMyInstances = new List<kOSProcessor>();
public bool HasBooted { get; set; }
private bool objectsInitialized = false;
private int numUpdatesAfterStartHappened = 0;
private bool finishedRP1ProceduralAvionicsUpdate = false;
public float AdditionalMass { get; set; }
/// How many times have instances of this class been constructed during this process run?
private static int constructorCount;
private int kOSCoreId;
/// <summary>Can be used as a unique ID of which processor this is, but unlike Guid,
/// it doesn't remain unique across runs so you shouldn't use it for serialization.</summary>
public int KOSCoreId { get { return kOSCoreId; } }
private MovingAverage averagePower = new MovingAverage();
// This is the "constant" byte count used when calculating the EC
// required by the archive volume (which has infinite space).
// TODO: This corresponds to the existing value and should be adjusted for balance.
private const int ARCHIVE_EFFECTIVE_BYTES = 50000;
private const string BootDirectoryName = "boot";
[KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Boot File", groupName = PAWGroup, groupDisplayName = PAWGroup), UI_ChooseOption(scene = UI_Scene.Editor)]
public string bootFile = "None";
[KSPField(isPersistant = true, guiName = "kOS Disk Space", guiActive = true, groupName = PAWGroup, groupDisplayName = PAWGroup)]
public int diskSpace = 1024;
[KSPField(isPersistant = true, guiName = "kOS Base Disk Space", guiActive = false, groupName = PAWGroup, groupDisplayName = PAWGroup)]
public int baseDiskSpace = 0;
[KSPField(isPersistant = false, guiName = "kOS Base Module Cost", guiActive = false, groupName = PAWGroup, groupDisplayName = PAWGroup)]
public float baseModuleCost = 0F; // this is the base cost added to a part for including the kOSProcessor, default to 0.
[KSPField(isPersistant = true, guiName = "kOS Base Module Mass", guiActive = false, groupName = PAWGroup, groupDisplayName = PAWGroup)]
public float baseModuleMass = 0F; // this is the base mass added to a part for including the kOSProcessor, default to 0.
[KSPField(isPersistant = false, guiName = "kOS Disk Space", guiActive = false, guiActiveEditor = true, groupName = PAWGroup, groupDisplayName = PAWGroup), UI_FloatRange(scene = UI_Scene.Editor)]
public float diskSpaceUI = 1024f; //needed for the slider, Could convert from String back into float or int. but works better and feels natural to have as a float to begin with --> raised to 2048 to mimich Apollo
[KSPField(isPersistant = true, guiName = "CPU/Disk Upgrade Cost", guiActive = false, guiActiveEditor = true, groupName = PAWGroup, groupDisplayName = PAWGroup)]
public float additionalCost = 0F;
[KSPField(isPersistant = false, guiName = "CPU/Disk Upgrade Mass", guiActive = false, guiActiveEditor = true, guiUnits = "Kg", guiFormat = "0.00", groupName = PAWGroup, groupDisplayName = PAWGroup)]
public float additionalMassGui = 0F;
[KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false)]
public float diskSpaceCostFactor = 0.0984140625F; //implies approx 100funds for 4096bytes of diskSpace. SliderNote: would recommend a small increase to: 0.0484140625F
[KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false)]
public float diskSpaceMassFactor = 0.0000000048829F; //implies approx 0.020kg for 4096bytes of diskSpace
[KSPField(isPersistant = true, guiActive = false)]
public int MaxPartId = 100;
// This represents how much EC to consume per executed instruction.
// This would be the "variable" component of the processor's power.
// Important: This value should be overriden in the part.cfg file
// for the kOS processor. The only reason it's being given a value
// here is as a fallback for those cases where an old legacy part
// might be loaded from before the part files had this value.
[KSPField(isPersistant = true, guiActive = false)]
public float ECPerInstruction = 0.000004F;
// This represents how much EC to consume per Byte of the current volume, per second.
// This would be the "continuous" component of the processor's power (though it varies
// when you change to another volume).
// IMPORTANT: The value defaults to zero and must be overriden in the module
// definition for any given part (within the part.cfg file).
[KSPField(isPersistant = true, guiActive = false)]
public float ECPerBytePerSecond = 0.000002F; //needs tuning, MM can be used for more modern specs
public kOSProcessor()
{
ProcessorMode = ProcessorModes.READY;
kOSCoreId = ++constructorCount;
}
public VolumePath BootFilePath {
get
{
if (string.IsNullOrEmpty(bootFile) || bootFile.Equals("None", StringComparison.OrdinalIgnoreCase))
return null;
return VolumePath.FromString(bootFile);
}
}
[KSPEvent(guiActive = true, guiName = "Open Terminal", category = "skip_delay;", groupName = PAWGroup, groupDisplayName = PAWGroup)]
public void Activate()
{
SafeHouse.Logger.Log("Open Window by event");
OpenWindow();
}
[KSPEvent(guiActive = true, guiName = "Close Terminal", category = "skip_delay;", groupName = PAWGroup, groupDisplayName = PAWGroup)]
public void Deactivate()
{
SafeHouse.Logger.Log("Close Window by event");
CloseWindow();
}
[KSPField(isPersistant = true, guiName = "kOS Average Power", guiActive = true, guiActiveEditor = true, guiUnits = "EC/s", guiFormat = "0.000", groupName = PAWGroup, groupDisplayName = PAWGroup)]
public float RequiredPower = 0;
[KSPEvent(guiActive = true, guiName = "Toggle Power", groupName = PAWGroup, groupDisplayName = PAWGroup)]
public void TogglePower()
{
SafeHouse.Logger.Log("Toggle Power");
ProcessorModes newProcessorMode = (ProcessorMode != ProcessorModes.OFF) ? ProcessorModes.OFF : ProcessorModes.STARVED;
SetMode(newProcessorMode);
}
[KSPAction("Open Terminal", actionGroup = KSPActionGroup.None)]
public void Activate(KSPActionParam param)
{
SafeHouse.Logger.Log("Open Terminal from ActionGroup");
Activate();
}
[KSPAction("Close Terminal", actionGroup = KSPActionGroup.None)]
public void Deactivate(KSPActionParam param)
{
SafeHouse.Logger.Log("Close Terminal from ActionGroup");
CloseWindow();
}
[KSPAction("Toggle Terminal", actionGroup = KSPActionGroup.None)]
public void Toggle(KSPActionParam param)
{
SafeHouse.Logger.Log("Toggle Terminal from ActionGroup");
ToggleWindow();
}
[KSPAction("Toggle Power", actionGroup = KSPActionGroup.None)]
public void TogglePower(KSPActionParam param)
{
SafeHouse.Logger.Log("Toggle Power from ActionGroup");
TogglePower();
}
[KSPAction("Suppress On", actionGroup = KSPActionGroup.None)]
public void StartSuppressAutopilot(KSPActionParam param)
{
SafeHouse.Logger.Log("Start Suppress Autopilot from ActionGroup");
SafeHouse.Config.SuppressAutopilot = true;
}
[KSPAction("Suppress Off", actionGroup = KSPActionGroup.None)]
public void StopSuppressAutopilot(KSPActionParam param)
{
SafeHouse.Logger.Log("Stop Suppress Autopilot from ActionGroup");
SafeHouse.Config.SuppressAutopilot = false;
}
[KSPAction("Toggle Suppression", actionGroup = KSPActionGroup.None)]
public void ToggleSuppressAutopilot(KSPActionParam param)
{
SafeHouse.Logger.Log("Toggle Suppress Autopilot from ActionGroup");
SafeHouse.Config.SuppressAutopilot = !SafeHouse.Config.SuppressAutopilot;
}
public void OpenWindow()
{
shared.Window.Open();
}
public void CloseWindow()
{
shared.Window.Close();
}
public void ToggleWindow()
{
shared.Window.Toggle();
}
public bool WindowIsOpen()
{
return shared.Window.IsOpen;
}
public bool TelnetIsAttached()
{
return shared.Window.NumTelnets() > 0;
}
public IScreenBuffer GetScreen()
{
return shared.Screen;
}
// TODO - later refactor making this kOS.Safer so it can work on ITermWindow, which also means moving all of UserIO's classes too.
public Screen.TermWindow GetWindow()
{
if (shared.Window != null)
return shared.Window;
return GetComponent<Screen.TermWindow>();
}
//returns basic information on kOSProcessor module in Editor
public override string GetInfo()
{
int defaultAvgInstructions = 200;
string format =
"Default disk capacity: {0}\n\n" +
"<color=#99ff00ff>Requires:</color>\n" +
" - ElectricCharge: {1}\n" +
"<color=#99ff00ff>Example:</color>\n" +
" - {2:N3}EC/s if IPU={3} and no wait instructions.";
// For the sake of GetInfo, prorate the EC usage based on the smallest physics frame currently selected
// Because this is called before the part is set, we need to manually calculate it instead of letting Update handle it.
double power = diskSpace * ECPerBytePerSecond + defaultAvgInstructions * ECPerInstruction / Time.fixedDeltaTime;
string chargeText = (ECPerInstruction == 0) ?
"None. It's powered by pure magic ... apparently." : // for cheaters who use MM or editing part.cfg, to get rid of it.
string.Format("1 per {0} instructions executed", (int)(1 / ECPerInstruction));
return string.Format(format, diskSpace, chargeText, power, defaultAvgInstructions);
}
//implement IPartCostModifier component
public float GetModuleCost(float defaultCost, ModifierStagingSituation sit)
{
// the 'sit' arg is irrelevant to us, but the interface requires it.
return baseModuleCost + additionalCost;
}
//implement IPartMassModifier component
public ModifierChangeWhen GetModuleCostChangeWhen()
{
return ModifierChangeWhen.FIXED;
}
private void UpdateCostAndMass()
{
// Clamp this to prevent negative cost and mass.
// (Can happen when people edit part.cfg data or
// use ModuleManager.)
float spaceDelta = Mathf.Max(diskSpace - baseDiskSpace, 0.0f);
additionalCost = (float)System.Math.Round(spaceDelta * diskSpaceCostFactor, 0);
AdditionalMass = spaceDelta * diskSpaceMassFactor;
additionalMassGui = AdditionalMass * 1000;
}
private PartModule RP1AvionicsModule = null;
private void FindRP1Modules()
{
RP1AvionicsModule = null;
foreach (PartModule otherModule in part.Modules)
{
for (System.Type t = otherModule.GetType(); t != null; t = t.BaseType)
{
if (t.Name.Contains("ModuleProceduralAvionics"))
{
RP1AvionicsModule = otherModule;
break;
}
}
if (RP1AvionicsModule != null)
break;
}
SafeHouse.Logger.Log(string.Format("FindRP1Module: {0}", RP1AvionicsModule != null ? "Found" : "Not Found"));
}
private void UpdateRP1TechLevel(bool InEditor)
{
if (RP1AvionicsModule != null)
{
var techNodePropInfo = RP1AvionicsModule.GetType().GetProperty("CurrentProceduralAvionicsTechNode");
if (techNodePropInfo != null)
{
var techNodeProp = techNodePropInfo.GetValue(RP1AvionicsModule);
if (techNodeProp != null)
{
System.Type techNodeType = techNodeProp.GetType();
System.Reflection.FieldInfo fieldInfo;
if (InEditor)
{
fieldInfo = techNodeType.GetField("kosDiskSpace");
int newDiskSpace = (fieldInfo != null) ? (int)fieldInfo.GetValue(techNodeProp) : 0;
if (newDiskSpace != baseDiskSpace && newDiskSpace > 0)
{
SafeHouse.Logger.Log(string.Format("Changing base disk space for RP-1 config change: {0} -> {1}", baseDiskSpace, newDiskSpace));
// Adjust disk space to be the same multiple of the new base disk space
diskSpace = newDiskSpace * diskSpace / baseDiskSpace;
baseDiskSpace = newDiskSpace;
PopulateDiskSpaceUI();
}
}
fieldInfo = techNodeType.GetField("kosSpaceCostFactor");
if (fieldInfo != null)
diskSpaceCostFactor = (float)fieldInfo.GetValue(techNodeProp);
fieldInfo = techNodeType.GetField("kosSpaceMassFactor");
if (fieldInfo != null)
diskSpaceMassFactor = (float)fieldInfo.GetValue(techNodeProp);
fieldInfo = techNodeType.GetField("kosECPerInstruction");
if (fieldInfo != null)
ECPerInstruction = (float)fieldInfo.GetValue(techNodeProp);
}
}
}
}
private void PopulateDiskSpaceUI()
{
//populate diskSpaceUI selector
// Set the initial value to current disk space
diskSpaceUI = diskSpace;
// Get the field and setup the slider
BaseField field = Fields["diskSpaceUI"];
UI_FloatRange slider = new UI_FloatRange
{
minValue = baseDiskSpace,
maxValue = baseDiskSpace * 8, //Set i Little higher based on what nasa flew with read only ROM space (4kb is rough and read only doesnt exist in KOS)
stepIncrement = baseDiskSpace / 8f,
scene = UI_Scene.Editor
};
//These should be here, yes they are declared above but this is good practice to include parms when making the ui object
field.uiControlEditor = slider;
field.guiActiveEditor = true;
field.guiName = "KOS Disk Space";
}
//implement IPartMassModifier component
public float GetModuleMass(float defaultMass, ModifierStagingSituation sit)
{
// the 'sit' arg is irrelevant to us, but the interface requires it.
return baseModuleMass + AdditionalMass;
}
//implement IPartMassModifier component
public ModifierChangeWhen GetModuleMassChangeWhen()
{
return ModifierChangeWhen.FIXED;
}
public override void OnStart(StartState state)
{
numUpdatesAfterStartHappened = 0;
finishedRP1ProceduralAvionicsUpdate = false;
try
{
FindRP1Modules();
UpdateRP1TechLevel(state == StartState.Editor);
//if in Editor, populate boot script selector, diskSpace selector and etc.
if (state == StartState.Editor)
{
if (baseDiskSpace == 0)
baseDiskSpace = diskSpace;
InitUI();
}
// Removed: UpdateCostAndMass();
// Please do not call UpdateCostAndMass() here because during OnStart() in RP-1, diskSpaceMassFactor is still
// the very heavy default value - ProceduralAvionics Tech has not yet been updated for tech level during OnStart(),
// so if we reported our mass now back to KSP, we'd have a super heavy probe core for just one physics frame that
// might unfairly break wheels and legs and joints, etc.
//Do not start from editor and at KSP first loading
if (state == StartState.Editor || state == StartState.None)
{
return;
}
SafeHouse.Logger.Log(string.Format("OnStart: {0} {1}", state, ProcessorMode));
InitObjects();
}
catch (Exception e)
{
SafeHouse.Logger.LogException(e);
}
}
public static void SetBootListDirty()
{
bootListDirty = true;
}
private void InitUI()
{
//Populate selector for boot scripts
BaseField field = Fields["bootFile"];
var options = (UI_ChooseOption)field.uiControlEditor;
var bootFiles = new List<VolumePath>();
bootFiles.AddRange(BootDirectoryFiles());
//no need to show the control if there are no available boot files
options.controlEnabled = bootFiles.Count >= 1;
field.guiActiveEditor = bootFiles.Count >= 1;
var availableOptions = bootFiles.Select(e => e.ToString()).ToList();
var availableDisplays = bootFiles.Select(e => e.Name).ToList();
availableOptions.Insert(0, "None");
availableDisplays.Insert(0, "None");
var bootFilePath = BootFilePath; // store the selected path temporarily
if (bootFilePath != null && !bootFiles.Contains(bootFilePath))
{
// if the path is not null ("None", null, or empty) and if it isn't in list of files
var archive = new Archive(SafeHouse.ArchiveFolder);
var file = archive.Open(bootFilePath) as VolumeFile; // try to open the file as saved
if (file == null)
{
// check the same file name, but in the boot directory.
var path = VolumePath.FromString(BootDirectoryName).Combine(bootFilePath.Name);
file = archive.Open(path) as VolumeFile; // try to open the new path
if (file == null)
{
// try the file name without "boot" prefix
var name = bootFilePath.Name;
if (name.StartsWith("boot", StringComparison.OrdinalIgnoreCase) && name.Length > 4)
{
// strip the boot prefix and try that file name
name = name.Substring(4);
path = VolumePath.FromString(BootDirectoryName).Combine(name);
file = name.StartsWith(".") ? null : archive.Open(path) as VolumeFile; // try to open the new path
if (file == null)
{
// try the file name without "boot_" prefix
if (name.StartsWith("_", StringComparison.OrdinalIgnoreCase) && name.Length > 1)
{
// only need to strip "_" here
name = name.Substring(1);
path = VolumePath.FromString(BootDirectoryName).Combine(name);
file = name.StartsWith(".") ? null : archive.Open(path) as VolumeFile; // try to open the new path
}
}
}
}
}
// now, if we have a file object, use its values.
if (file != null)
{
// store the boot file information
bootFile = file.Path.ToString();
if (!bootFiles.Contains(file.Path))
{
availableOptions.Insert(1, bootFile);
availableDisplays.Insert(1, "*" + file.Path.Name); // "*" is indication the file is not normally available
}
}
}
SafeHouse.Logger.SuperVerbose("bootFile: " + bootFile);
options.options = availableOptions.ToArray();
options.display = availableDisplays.ToArray();
bootListDirty = false;
ForcePAWRefresh();
PopulateDiskSpaceUI();
}
public void ForcePAWRefresh()
{
// Thanks to https://github.com/blowfishpro for finding this API call for me:
UIPartActionWindow paw = UIPartActionController.Instance?.GetItem(part, false);
if (paw != null)
{
paw.ClearList();
paw.displayDirty = true;
}
}
private IEnumerable<VolumePath> BootDirectoryFiles()
{
var result = new List<VolumePath>();
var archive = new Archive(SafeHouse.ArchiveFolder);
var path = VolumePath.FromString(BootDirectoryName);
var bootDirectory = archive.Open(path) as VolumeDirectory;
if (bootDirectory == null)
{
return result;
}
var files = bootDirectory.List();
foreach (KeyValuePair<string, VolumeItem> pair in files)
{
if (pair.Value is VolumeFile && (pair.Value.Extension.Equals(Volume.KERBOSCRIPT_EXTENSION)
|| pair.Value.Extension.Equals(Volume.KOS_MACHINELANGUAGE_EXTENSION)))
{
result.Add(pair.Value.Path);
}
}
return result;
}
private static Regex VolumeNameRemoveChars = new Regex("[/\\\\<>:\"|?*]*", RegexOptions.Compiled);
public void InitObjects()
{
if (objectsInitialized)
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.InitObjects() - objects already initialized");
return;
}
objectsInitialized = true;
CalcConstsFromKSP();
shared = new SharedObjects();
shared.Vessel = vessel;
shared.Processor = this;
shared.KSPPart = part;
shared.UpdateHandler = new UpdateHandler();
shared.BindingMgr = new BindingManager(shared);
shared.Interpreter = new Screen.ConnectivityInterpreter(shared);
shared.Screen = shared.Interpreter;
shared.ScriptHandler = new KSScript();
shared.Logger = new KSPLogger(shared);
shared.VolumeMgr = new ConnectivityVolumeManager(shared);
shared.ProcessorMgr = new ProcessorManager();
shared.FunctionManager = new FunctionManager(shared);
shared.TransferManager = new TransferManager(shared);
shared.Cpu = new CPU(shared);
shared.AddonManager = new AddOns.AddonManager(shared);
shared.GameEventDispatchManager = new GameEventDispatchManager(shared);
// Make the window that is going to correspond to this kOS part:
shared.Window = gameObject.AddComponent<Screen.TermWindow>();
shared.Window.AttachTo(shared);
shared.SoundMaker = shared.Window.GetSoundMaker();
// initialize archive
Archive = new Archive(SafeHouse.ArchiveFolder);
shared.VolumeMgr.Add(Archive);
Messages = new MessageQueue();
// initialize harddisk
if (HardDisk == null)
{
HardDisk = new Harddisk(diskSpace);
if (!string.IsNullOrEmpty(Tag))
{
// Tag could contain characters that are not allowed.
var tmpTag = VolumeNameRemoveChars.Replace(Tag, "");
if( !string.IsNullOrWhiteSpace(tmpTag))
{
HardDisk.Name = tmpTag.Replace(' ', '_');
}
}
var path = BootFilePath;
// populate it with the boot file, but only if using a new disk:
if (path != null && !SafeHouse.Config.StartOnArchive)
{
var bootVolumeFile = Archive.Open(BootFilePath) as VolumeFile;
if (bootVolumeFile != null)
{
if (HardDisk.SaveFile(BootFilePath, bootVolumeFile.ReadAll()) == null)
{
// Throwing an exception during InitObjects will break the initialization and won't show
// the error to the user. So we just log the error instead. At some point in the future
// it would be nice to queue up these init errors and display them to the user somewhere.
SafeHouse.Logger.LogError("Error copying boot file to local volume: not enough space.");
}
}
}
}
shared.VolumeMgr.Add(HardDisk);
// process setting
if (!SafeHouse.Config.StartOnArchive)
{
shared.VolumeMgr.SwitchTo(HardDisk);
}
// initialize processor mode if different than READY
if (ProcessorMode != ProcessorModes.READY)
{
ProcessorModeChanged();
}
InitProcessorTracking();
}
// The official value of some physics constants change over time as standards bodies re-calculate them.
// This code below ensures we're using whatever value KSP itself is using.
// The reason this code is *here* not in ConstantValue is because ConstantValue can't call
// the KSP API. It's in kOS.Safe.
private void CalcConstsFromKSP()
{
// GravitationalAcceleration did not exist in PhysicsGlobals prior to KSP 1.6.x.
// This code has to use reflection to avoid calling it on older backports:
Type physGlobType = typeof(PhysicsGlobals);
if (physGlobType != null)
{
// KSP often changes its mind whether a member is a Field or Property, so let's write this
// to future-proof against them changing which it is by trying both ways:
FieldInfo asField = (physGlobType.GetField("GravitationalAcceleration", BindingFlags.Public | BindingFlags.Static));
if (asField != null)
ConstantValue.G0 = (double) asField.GetValue(null);
else
{
PropertyInfo asProperty = (physGlobType.GetProperty("GravitationalAcceleration", BindingFlags.Public | BindingFlags.Static));
if (asProperty != null)
ConstantValue.G0 = (double)asProperty.GetValue(null, null);
}
}
// Fallback: Note if none of the above work, G0 still does have a reasonable value because we
// hardcode it to a literal in ConstantValue before doing any of the above work.
// Cannot find anything in KSP's API exposing their value of G, so this indirect means
// of calculating it from an arbitrary body is used:
CelestialBody anyBody = FlightGlobals.fetch.bodies.FirstOrDefault();
if (anyBody == null)
SafeHouse.Logger.LogError("kOSProcessor: This game installation is badly broken. It appears to have no planets in it.");
else
ConstantValue.GravConst = anyBody.gravParameter / anyBody.Mass;
ConstantValue.AvogadroConst = PhysicsGlobals.AvogadroConstant;
ConstantValue.BoltzmannConst = PhysicsGlobals.BoltzmannConstant;
ConstantValue.IdealGasConst = PhysicsGlobals.IdealGasConstant;
}
private void InitProcessorTracking()
{
// Track a list of all instances of me that exist:
if (!allMyInstances.Contains(this))
{
allMyInstances.Add(this);
SortAllInstances();
}
}
public static void SortAllInstances()
{
allMyInstances.Sort(delegate (kOSProcessor a, kOSProcessor b)
{
// THIS SORT IS EXPENSIVE BECAUSE IT KEEPS RECALCULATING THE CRITERIA
// (DISTANCE BETWEEN VESSELS, HOPS TO ROOT PART) ON EACH PAIRWISE
// COMPARISON OF TWO ITEMS DURING THE SORT, RATHER THAN REMEMBERING A
// PART'S SCORE AND RE-USING THAT ON SUBSEQUENT PAIRWISE COMPARISONS WITH THAT PART.
// I DON'T THINK OPTOMIZING IT IS WORTH IT WHEN THIS SORT WON"T BE DONE SUPER FREQUENTLY,
// MAYBE ONCE EVERY 1 or 2 SECONDS AT MOST.
// sort "nulls" to be last:
if (a.part == null || a.part.vessel == null)
return 1;
if (b.part == null || b.part.vessel == null)
return -1;
// If on diffrent vessels, sort by distance of vessel from active vessel - nearest vessels first:
if (a.part.vessel != b.part.vessel)
{
Vector3d activePos = FlightGlobals.ActiveVessel.GetWorldPos3D();
// May as well use square magnitude - it's faster and sorts things in the same order:
double aSquareDistance = (activePos - a.part.vessel.GetWorldPos3D()).sqrMagnitude;
double bSquareDistance = (activePos - b.part.vessel.GetWorldPos3D()).sqrMagnitude;
return (aSquareDistance < bSquareDistance) ? -1 : 1;
}
// If it gets to here, they're on the same vessel.
// So sort by number of parent links to walk to get to root part (closest to root goes first).
int aCountParts = 0;
int bCountParts = 0;
for (Part p = a.part; p != null; p = p.parent)
++aCountParts;
for (Part p = b.part; p != null; p = p.parent)
++bCountParts;
if (aCountParts != bCountParts)
return aCountParts - bCountParts;
// If it gets to here it's a tie so far - two parts were an equal number of parts away from root,
// which can easily happen if the kOS CPUs were attached with symmetry in the VAB/SPH.
// We CANNOT have a tie. We need a deterministic order because differences in the list is
// how we discover the CPU list has chnaged. So make one final arbitrary thing to break the
// tie with:
uint aUID = a.part.uid();
uint bUID = b.part.uid();
return (aUID < bUID ? -1 : 1);
});
}
public void OnDestroy()
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.OnDestroy()!");
allMyInstances.RemoveAll(m => m == this);
SortAllInstances();
if (shared != null)
{
shared.Cpu.BreakExecution(false);
shared.Cpu.Dispose();
shared.DestroyObjects();
shared = null;
}
}
/// <summary>
/// Return a list of all existing runtime instances of this PartModule.
/// The list is guaranteed to be ordered by the Vessel that it's on.
/// (i.e. all the instances of no vessel are first ,then all the module instances
/// on vessel A, then all the instances on vessel B, and so on)
/// </summary>
/// <returns></returns>
public static List<kOSProcessor> AllInstances()
{
// Doing it this way to force return value to be a shallow-level copy,
// rather than an exact reference to the internal private list.
// So if the caller adds/removes from it, it won't mess with the
// private list we're internally maintaining:
return allMyInstances.GetRange(0, allMyInstances.Count);
}
public void RegisterkOSExternalFunction(object[] parameters)
{
//SafeHouse.Logger.Log("*** External Function Registration Succeeded");
//cpu.RegisterkOSExternalFunction(parameters);
}
public static int AssignNewId()
{
var config = PluginConfiguration.CreateForType<kOSProcessor>();
config.load();
var id = config.GetValue<int>("CpuIDMax") + 1;
config.SetValue("CpuIDMax", id);
config.save();
return id;
}
public void Update()
{
bool isInEditor = false;
if (HighLogic.LoadedScene == GameScenes.EDITOR && EditorLogic.fetch != null)
{
isInEditor = true;
if (bootListDirty)
{
InitUI();
}
UpdateRP1TechLevel(true);
// This part is now just rounding from INT, this counters any issue with DiskSpace or BaseDiskSpace being incorrect or "Out of range"
if (diskSpace != Convert.ToInt32(Mathf.RoundToInt(diskSpaceUI))) //Tested in-game, no issues found
{
diskSpace = Mathf.RoundToInt(diskSpaceUI); ///Tested as well
UpdateCostAndMass();
GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
}
RequiredPower = this.diskSpace * ECPerBytePerSecond + SafeHouse.Config.InstructionsPerUpdate * ECPerInstruction / Time.fixedDeltaTime;
}
if (!IsAlive()) return;
// Conceptually this next bit really belongs in OnStart() because it should only happen
// once up front during scene load, but when RP-1 is installed and this KOSProcessor
// is inside the same part as RP-1's ModuleProceduralAvionics, a race condition develops
// between the two if KOSProcessor.OnStart() tries to do the following work.
// The values queried from ModuleProceduralAvionics for mass cost per byte of disk
// are defaulted to the bottom rung starting 1950's tech *at first* until it has had a chance
// to run its OnStart() to correct those values to the actual avionics tech level of the part.
// Thus if KOSProcessor tried to do the following code in its OnStart(), and KOS's OnStart()
// happened before ModuleProceduralAvionics' OnStart(), the KOSProcessor would end up being
// several tonnes when it should only be a few kilograms. (Issue #3081)
//
// It is *hoped* that this work will occur before physics is turned on, so the part gets the
// corrected mass before it has a chance to start crushing landing legs and wheels and so on.
// Allegedly, Unity will invoke all the Update()s several times before KSP turns physics on so
// this *should* be okay.
if (!finishedRP1ProceduralAvionicsUpdate && !isInEditor )
{
float massFactorBefore = diskSpaceMassFactor;
UpdateRP1TechLevel(false);
UpdateCostAndMass();
// Stop wasting CPU time doing this recalculation when either the value has changed to a new number (proving
// that RP-1 has finally applied its tech upgrade which is why the value changed), or because we tried long
// enough to prove we really are at the default starting tech level so it's not going to change.)
if (diskSpaceMassFactor != massFactorBefore || numUpdatesAfterStartHappened > 60 )
{
finishedRP1ProceduralAvionicsUpdate = true;
}
}
UpdateVessel();
UpdateObservers();
++numUpdatesAfterStartHappened;
}
public void FixedUpdate()
{
if (!IsAlive()) return;
if (!vessel.HoldPhysics)
{
if (!HasBooted)
{
SafeHouse.Logger.LogWarning("First Update()");
shared.Cpu.Boot();
HasBooted = true;
}
UpdateVessel();
UpdateFixedObservers();
ProcessElectricity(part, TimeWarp.fixedDeltaTime);
}
}
private void UpdateVessel()
{
if (shared != null && shared.Vessel != vessel)
{
shared.Vessel = vessel;
}
}
private void UpdateObservers()
{
if (ProcessorMode == ProcessorModes.READY)
{
if (shared.UpdateHandler != null) shared.UpdateHandler.UpdateObservers(TimeWarp.deltaTime);
UpdateParts();
}
}
private void UpdateFixedObservers()
{
if (ProcessorMode == ProcessorModes.READY)
{
if (shared.UpdateHandler != null) shared.UpdateHandler.UpdateFixedObservers(TimeWarp.fixedDeltaTime);
}
}
private bool IsAlive()
{
if (shared == null) return false;
if (part.State == PartStates.DEAD)
{
ProcessorMode = ProcessorModes.OFF;
return false;
}
return true;
}
public void UpdateParts()
{
// Trigger whenever the number of parts in the vessel changes (like when staging, docking or undocking).
if (vessel.parts.Count == vesselPartCount) return;
var missingHardDisks = false;
var attachedVolumes = new List<Volume>();
var processors = new List<kOSProcessor>();
// Look for all the processors that exists in the vessel
foreach (var partObj in vessel.parts)
{
kOSProcessor processorPart;
if (!PartIsKosProc(partObj, out processorPart)) continue;
processors.Add(processorPart);
// A harddisk may be null because the kOS part haven't been initialized yet
// Wait until the next update and everything should be fine
if (processorPart.HardDisk != null)
{
attachedVolumes.Add(processorPart.HardDisk);
}
else
{
missingHardDisks = true;
break;
}
}
if (missingHardDisks) return;
shared.VolumeMgr.UpdateVolumes(attachedVolumes);
shared.ProcessorMgr.UpdateProcessors(processors);
vesselPartCount = vessel.parts.Count;
}
public bool PartIsKosProc(Part input, out kOSProcessor proc)
{
foreach (var processor in input.Modules.OfType<kOSProcessor>())
{
proc = processor;
return true;
}
proc = null;
return false;
}
public override void OnFixedUpdate()
{
}
public override void OnInactive()
{
SafeHouse.Logger.Log("Processor Stop");
}
public override void OnLoad(ConfigNode node)
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.OnLoad");
try
{
// KSP Seems to want to make an instance of my partModule during initial load
if (vessel == null) return;
if (node.HasValue("activated") && !bool.Parse(node.GetValue("activated")))
{
ProcessorMode = ProcessorModes.OFF;
}
if (node.HasNode("harddisk"))
{
var newDisk = node.GetNode("harddisk").ToHardDisk();
HardDisk = newDisk;
}