-
Notifications
You must be signed in to change notification settings - Fork 216
/
KCTUtilities.cs
1735 lines (1486 loc) · 67.5 KB
/
KCTUtilities.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 KSP.UI;
using KSP.UI.Screens;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UniLinq;
using UnityEngine;
using UnityEngine.Profiling;
namespace RP0
{
public static class KCTUtilities
{
private static bool? _isPrincipiaInstalled = null;
private static bool? _isTestFlightInstalled = null;
private static bool? _isTestLiteInstalled = null;
private static PropertyInfo _piTFInstance;
private static PropertyInfo _piTFSettingsEnabled;
private static Type _tlSettingsType;
private static FieldInfo _fiTLSettingsDisabled;
internal const string _iconPath = "RP-1/PluginData/Icons/";
internal const string _icon_KCT_Off_24 = _iconPath + "KCT_off-24";
internal const string _icon_KCT_Off_38 = _iconPath + "KCT_off-38";
internal const string _icon_KCT_On_24 = _iconPath + "KCT_on-24";
internal const string _icon_KCT_On_38 = _iconPath + "KCT_on-38";
internal const string _icon_KCT_Off = _iconPath + "KCT_off";
internal const string _icon_KCT_On = _iconPath + "KCT_on";
internal const string _icon_plane = _iconPath + "KCT_flight";
internal const string _icon_rocket = _iconPath + "KCT_rocket";
internal const string _icon_settings = _iconPath + "KCT_setting";
public static AvailablePart GetAvailablePartByName(string partName) => PartLoader.getPartInfoByName(partName);
public static string GetPartNameFromNode(ConfigNode part)
{
string name = part.GetValue("part");
if (name != null)
name = name.Split('_')[0];
else
name = part.GetValue("name");
return name;
}
public static double GetBuildRate(int index, LaunchComplex LC, bool isHumanRated, bool forceRecalc)
{
bool useCap = LC.IsHumanRated && !isHumanRated;
// optimization: if we are checking index 0 use the cached rate, otherwise recalc
if (forceRecalc || index != 0)
{
return Formula.GetVesselBuildRate(index, LC, useCap, 0);
}
return useCap ? LC.Rate : LC.RateHRCapped;
}
public static double GetBuildRate(LaunchComplex LC, double mass, double BP, bool isHumanRated, int delta = 0)
{
if (!LC.IsOperational)
return 0d;
bool useCap = LC.IsHumanRated && !isHumanRated;
int engCap = LC.MaxEngineersFor(mass, BP, isHumanRated);
if (engCap < LC.Engineers + delta)
delta = engCap - LC.Engineers;
if (delta != 0)
{
return Formula.GetVesselBuildRate(0, LC, useCap, delta);
}
return useCap ? LC.RateHRCapped : LC.Rate;
}
public static double GetBuildRate(int index, ProjectType type, LaunchComplex LC, bool isHumanRated, int upgradeDelta = 0)
{
if (type == ProjectType.VAB ? LC.LCType == LaunchComplexType.Hangar : LC.LCType == LaunchComplexType.Pad)
return 0.0001d;
return Formula.GetVesselBuildRate(index, LC, LC.IsHumanRated && !isHumanRated, upgradeDelta);
}
public static double GetBuildRate(VesselProject ship)
{
int engCap = ship.LC.MaxEngineersFor(ship);
int delta = 0;
if (engCap < ship.LC.Engineers)
delta = engCap - ship.LC.Engineers;
return GetBuildRate(ship.LC.BuildList.IndexOf(ship), ship.Type, ship.LC, ship.humanRated, delta);
}
public static double GetConstructionRate(int index, LCSpaceCenter KSC, SpaceCenterFacility facilityType)
{
return Formula.GetConstructionBuildRate(index, KSC, facilityType);
}
public static double GetResearcherEfficiencyMultipliers()
{
return Database.SettingsSC.ResearcherEfficiency;
}
public static bool IsClamp(Part part)
{
return part.FindModuleImplementing<LaunchClamp>() != null || part.HasTag(ModuleTagList.PadInfrastructure);
}
public static bool IsClampOrChild(this ProtoPartSnapshot p)
{
return IsClamp(p.partPrefab) || (p.parent != null && IsClampOrChild(p.parent));
}
public static bool IsClampOrChild(this Part p)
{
return IsClamp(p) || (p.parent != null && IsClampOrChild(p.parent));
}
public static float GetTotalVesselCost(ProtoVessel vessel, bool includeFuel = true)
{
float total = 0, totalDry = 0;
foreach (ProtoPartSnapshot part in vessel.protoPartSnapshots)
{
total += ShipConstruction.GetPartCosts(part, part.partInfo, out float dry, out float wet);
totalDry += dry;
}
return includeFuel ? total : totalDry;
}
public static float GetTotalVesselCost(ConfigNode vessel, bool includeFuel = true)
{
float total = 0;
foreach (ConfigNode part in vessel.GetNodes("PART"))
{
total += GetPartCostFromNode(part, includeFuel);
}
return total;
}
public static float GetTotalVesselCost(List<Part> parts, bool includeFuel = true)
{
Profiler.BeginSample("RP0SaveShip");
float total = 0f;
float resCost = 0f;
int count = parts.Count;
while (count-- > 0)
{
Part part = parts[count];
AvailablePart partInfo = part.partInfo;
float dryCost = partInfo.cost + part.GetModuleCosts(partInfo.cost);
int resCount = part.Resources.Count;
while (resCount-- > 0)
{
PartResource partResource = part.Resources[resCount];
PartResourceDefinition info = partResource.info;
dryCost -= info.unitCost * (float)partResource.maxAmount;
resCost += info.unitCost * (float)partResource.amount;
}
total += dryCost;
}
if (includeFuel)
total += resCost;
Profiler.EndSample();
return total;
}
public static float GetPartCostFromNode(ConfigNode part, bool includeFuel = true)
{
string name = GetPartNameFromNode(part);
if (!(GetAvailablePartByName(name) is AvailablePart aPart))
return 0;
ShipConstruction.GetPartCostsAndMass(part, aPart, out float dryCost, out float fuelCost, out _, out _);
return includeFuel ? dryCost + fuelCost : dryCost;
}
public static float GetPartMassFromNode(ConfigNode part, bool includeFuel = true, bool includeClamps = true)
{
AvailablePart aPart = GetAvailablePartByName(GetPartNameFromNode(part));
if (aPart == null)
{
return 0;
}
else if (!includeClamps)
{
if (IsClamp(aPart.partPrefab))
return 0;
}
ShipConstruction.GetPartCostsAndMass(part, aPart, out _, out _, out float dryMass, out float fuelMass);
return includeFuel ? dryMass + fuelMass : dryMass;
}
public static float GetShipMass(this ShipConstruct sc, bool excludeClamps, out float dryMass, out float fuelMass)
{
Profiler.BeginSample("RP0GetShipMass");
dryMass = 0f;
fuelMass = 0f;
foreach (var part in sc.parts)
{
AvailablePart partInfo = part.partInfo;
if (excludeClamps)
{
if (part.IsClampOrChild())
continue;
}
float partDryMass = partInfo.partPrefab.mass + part.GetModuleMass(partInfo.partPrefab.mass, ModifierStagingSituation.CURRENT);
float partFuelMass = 0f;
foreach (var resource in part.Resources)
{
partFuelMass += resource.info.density * (float)resource.amount;
}
dryMass += partDryMass;
fuelMass += partFuelMass;
}
Profiler.EndSample();
return dryMass + fuelMass;
}
// Reimplemented from stock so we ignore tags.
public static Vector3 GetShipSize(ShipConstruct ship, bool excludeClamps, bool excludeChutes)
{
if (ship.parts.Count == 0)
return Vector3.zero;
Profiler.BeginSample("RP0GetShipSize");
Bounds craftBounds = new Bounds();
Vector3 rootPos = ship.parts[0].orgPos;
craftBounds.center = rootPos;
List<Bounds> pBounds = new List<Bounds>();
Vector3 sz;
Part p;
int iC = ship.parts.Count;
for (int i = 0; i < iC; ++i)
{
p = ship.parts[i];
if (excludeClamps)
{
if (p.IsClampOrChild())
continue;
}
if (excludeChutes)
{
if (p.Modules["RealChuteModule"] != null)
continue;
}
Bounds[] bounds = GetPartRendererBounds(p);
Bounds b;
Bounds cb;
int jC = bounds.Length;
for (int j = 0; j < jC; ++j)
{
b = bounds[j];
cb = b;
cb.size *= p.boundsMultiplier;
sz = cb.size;
cb.Expand(p.GetModuleSize(sz));
pBounds.Add(b);
}
}
craftBounds = PartGeometryUtil.MergeBounds(pBounds.ToArray(), ship.parts[0].transform.root);
Profiler.EndSample();
return craftBounds.size;
}
// Reimplemented from stock so we ignore disabled renderers.
public static Bounds[] GetPartRendererBounds(Part p)
{
List<MeshRenderer> mRenderers = p.FindModelComponents<MeshRenderer>();
List<SkinnedMeshRenderer> smRenderers = p.FindModelComponents<SkinnedMeshRenderer>();
for (int i = mRenderers.Count - 1; i >= 0; --i)
{
if (!mRenderers[i].enabled)
mRenderers.RemoveAt(i);
}
for (int i = smRenderers.Count - 1; i >= 0; --i)
{
if (!smRenderers[i].enabled)
smRenderers.RemoveAt(i);
}
Bounds[] bs = new Bounds[mRenderers.Count + smRenderers.Count];
int j = 0;
for (int i = 0; i < mRenderers.Count; ++i)
{
bs[j++] = mRenderers[i].bounds;
}
for (int i = 0; i < smRenderers.Count; ++i)
{
bs[j++] = smRenderers[i].bounds;
}
return bs;
}
/// <summary>
/// Tests to see if two ConfigNodes have the same information. Currently requires same ordering of subnodes
/// </summary>
/// <param name="node1"></param>
/// <param name="node2"></param>
/// <returns></returns>
public static bool ConfigNodesAreEquivalent(ConfigNode node1, ConfigNode node2)
{
//Check that the number of subnodes are equal
if (node1.GetNodes().Length != node2.GetNodes().Length)
return false;
//Check that all the values are identical
foreach (string valueName in node1.values.DistinctNames())
{
if (!node2.HasValue(valueName))
return false;
if (node1.GetValue(valueName) != node2.GetValue(valueName))
return false;
}
//Check all subnodes for equality
for (int index = 0; index < node1.GetNodes().Length; ++index)
{
if (!ConfigNodesAreEquivalent(node1.nodes[index], node2.nodes[index]))
return false;
}
//If all these tests pass, we consider the nodes to be equivalent
return true;
}
public static double SpendFunds(double toSpend, TransactionReasons reason)
{
if (!KSPUtils.CurrentGameIsCareer())
return 0;
RP0Debug.Log($"Removing funds: {toSpend}, New total: {Funding.Instance.Funds - toSpend}");
Funding.Instance.AddFunds(-toSpend, reason);
return Funding.Instance.Funds;
}
public static double SpendFunds(double toSpend, TransactionReasonsRP0 reason)
{
return SpendFunds(toSpend, reason.Stock());
}
public static double AddFunds(double toAdd, TransactionReasons reason)
{
if (!KSPUtils.CurrentGameIsCareer())
return 0;
RP0Debug.Log($"Adding funds: {toAdd}, New total: {Funding.Instance.Funds + toAdd}");
Funding.Instance.AddFunds(toAdd, reason);
return Funding.Instance.Funds;
}
public static double AddFunds(double toAdd, TransactionReasonsRP0 reason)
{
return AddFunds(toAdd, reason.Stock());
}
public static void ProcessSciPointTotalChange(float changeDelta)
{
// Earned point totals shouldn't decrease. This would only make sense when done through the cheat menu.
if (changeDelta <= 0f || SpaceCenterManagement.IsRefundingScience) return;
SpaceCenterManagement.Instance.SciPointsTotal += changeDelta;
RP0Debug.Log("Total sci points earned is now: " + SpaceCenterManagement.Instance.SciPointsTotal);
}
public static void TryAddVesselToBuildList() => TryAddVesselToBuildList(EditorLogic.fetch.launchSiteName);
public static void TryAddVesselToBuildList(string launchSite)
{
if (string.IsNullOrEmpty(launchSite))
{
launchSite = EditorLogic.fetch.launchSiteName;
}
ProjectType type = EditorLogic.fetch.ship.shipFacility == EditorFacility.VAB ? ProjectType.VAB : ProjectType.SPH;
if ((type == ProjectType.VAB) != (SpaceCenterManagement.Instance.ActiveSC.ActiveLC.LCType == LaunchComplexType.Pad))
{
string dialogStr;
if (type == ProjectType.VAB)
{
if (SpaceCenterManagement.Instance.ActiveSC.IsAnyLCOperational)
dialogStr = $"a launch complex. Please switch to a launch complex and try again.";
else
dialogStr = $"a launch complex. You must build a launch complex (or wait for a launch complex to finish building or renovating) before you can integrate this vessel.";
}
else
{
if (SpaceCenterManagement.Instance.ActiveSC.Hangar.IsOperational)
dialogStr = $"the Hangar. Please switch to the Hangar as active launch complex and try again.";
else
dialogStr = $"the Hangar. You must wait for the Hangar to finish renovating before you can integrate this vessel.";
}
PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "editorChecksFailedPopup",
"Wrong Launch Complex!",
$"Warning! This vessel needs to be built in {dialogStr}",
"Acknowledged",
false,
HighLogic.UISkin).HideGUIsWhilePopup();
return;
}
var vp = new VesselProject(EditorLogic.fetch.ship, launchSite, EditorLogic.FlagURL, true)
{
shipName = EditorLogic.fetch.shipNameField.text
};
TryAddVesselToBuildList(vp);
}
public static void TryAddVesselToBuildList(VesselProject vp, bool skipPartChecks = false, LaunchComplex overrideLC = null)
{
if (overrideLC != null)
vp.LCID = overrideLC.ID;
var v = new VesselBuildValidator
{
CheckPartAvailability = !skipPartChecks,
CheckPartConfigs = !skipPartChecks,
SuccessAction = AddVesselToBuildList
};
v.ProcessVessel(vp);
}
public static void AddVesselToBuildList(VesselProject vp) => AddVesselToBuildList(vp, true);
public static void AddVesselToBuildList(VesselProject vp, bool spendFunds)
{
if (spendFunds)
SpendFunds(vp.GetTotalCost(), TransactionReasonsRP0.VesselPurchase);
if (vp.Type == ProjectType.SPH)
vp.launchSite = "Runway";
else
vp.launchSite = "LaunchPad";
LaunchComplex lc = vp.LC;
if (lc != null)
{
lc.BuildList.Add(vp);
}
else
{
RP0Debug.LogError($"Error! Tried to add {vp.shipName} to build list but couldn't find LC! KSC {SpaceCenterManagement.Instance.ActiveSC.KSCName} and active LC {SpaceCenterManagement.Instance.ActiveSC.ActiveLC}");
return;
}
try
{
SCMEvents.OnVesselAddedToBuildQueue.Fire(vp);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
RP0Debug.Log($"Added {vp.shipName} to build list at {lc.Name} at {SpaceCenterManagement.Instance.ActiveSC.KSCName}. Cost: {vp.cost}.");
RP0Debug.Log("Launch site is " + vp.launchSite);
string text = $"Added {vp.shipName} to integration list at {lc.Name}.";
var message = new ScreenMessage(text, 4f, ScreenMessageStyle.UPPER_CENTER);
ScreenMessages.PostScreenMessage(message);
}
/// <summary>
/// Validates and saves the vessel edits as a new buildlist item.
/// </summary>
/// <param name="editableShip">Must be the pre-edits (i.e what was initially loaded into the edit session) state of the vessel</param>
public static void TrySaveShipEdits(VesselProject editableShip)
{
// Load the current editor state as a fresh BuildListVessel
string launchSite = EditorLogic.fetch.launchSiteName;
var postEditShip = new VesselProject(EditorLogic.fetch.ship, launchSite, EditorLogic.FlagURL, true)
{
shipName = EditorLogic.fetch.shipNameField.text,
FacilityBuiltIn = editableShip.FacilityBuiltIn,
KCTPersistentID = editableShip.KCTPersistentID,
LCID = editableShip.LCID
};
double usedShipsCost = editableShip.GetTotalCost();
foreach (VesselProject v in SpaceCenterManagement.Instance.MergedVessels)
{
usedShipsCost += v.GetTotalCost();
v.RemoveFromBuildList(out _);
}
var validator = new VesselBuildValidator();
validator.CostOffset = usedShipsCost;
validator.SuccessAction = (postEditShip2) => SaveShipEdits(usedShipsCost, editableShip, postEditShip2);
validator.FailureAction = () => {; };
validator.ProcessVessel(postEditShip);
}
private static void SaveShipEdits(double oldCost, VesselProject editableShip, VesselProject newShip)
{
double costDelta;
if (KSPUtils.CurrentGameIsCareer() && (costDelta = oldCost - newShip.cost) != 0d)
{
Funding.Instance.AddFunds((float)costDelta, TransactionReasonsRP0.VesselPurchase.Stock());
}
AddVesselToBuildList(newShip, false);
int oldIdx;
editableShip.RemoveFromBuildList(out oldIdx);
if (KCTSettings.Instance.InPlaceEdit && oldIdx >= 0)
{
// Remove and reinsert at right place.
// We *could* insert at the right place to start with, but
// that requires changing AddVesselToBuildList, which is used as
// a void delegate elsewhere, so...
List<VesselProject> lst = newShip.LC.BuildList;
lst.RemoveAt(lst.Count - 1);
lst.Insert(oldIdx, newShip);
}
newShip.LC.RecalculateBuildRates();
GetShipEditProgress(editableShip, out double progressBP, out _, out _);
newShip.progress = progressBP;
RP0Debug.Log($"Finished? {editableShip.IsFinished}");
if (editableShip.IsFinished)
newShip.cannotEarnScience = true;
GamePersistence.SaveGame("persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
SpaceCenterManagement.ClearVesselEditMode();
RP0Debug.Log("Edits saved.");
HighLogic.LoadScene(GameScenes.SPACECENTER);
}
public static void GetShipEditProgress(VesselProject ship, out double newProgressBP, out double originalCompletionPercent, out double newCompletionPercent)
{
double origTotalBP;
double oldProgressBP;
if (SpaceCenterManagement.Instance.MergedVessels.Count == 0)
{
origTotalBP = ship.buildPoints;
oldProgressBP = ship.IsFinished ? origTotalBP : ship.progress;
}
else
{
double totalEffectiveCost = ship.effectiveCost;
foreach (VesselProject v in SpaceCenterManagement.Instance.MergedVessels)
{
totalEffectiveCost += v.effectiveCost;
}
origTotalBP = oldProgressBP = Formula.GetVesselBuildPoints(totalEffectiveCost);
oldProgressBP *= (1 - Database.SettingsSC.MergingTimePenalty);
}
double newTotalBP = SpaceCenterManagement.Instance.EditorVessel.buildPoints;
double totalBPDiff = Math.Abs(newTotalBP - origTotalBP);
newProgressBP = Math.Max(0, oldProgressBP - (1.1 * totalBPDiff));
originalCompletionPercent = oldProgressBP / origTotalBP;
newCompletionPercent = newProgressBP / newTotalBP;
}
public static int FindUnlockCost(List<AvailablePart> availableParts)
{
return (int)RealFuels.EntryCostManager.Instance.EntryCostForParts(availableParts);
}
public static void UnlockExperimentalParts(List<AvailablePart> availableParts)
{
// this will spend the funds, which is why we set costsFunds=false below.
UnlockCreditHandler.Instance.SpendCreditAndCost(availableParts);
foreach (var ap in availableParts)
{
ProtoTechNode protoNode = ResearchAndDevelopment.Instance.GetTechState(ap.TechRequired);
if (!protoNode.partsPurchased.Contains(ap))
{
protoNode.partsPurchased.Add(ap);
ap.costsFunds = false;
GameEvents.OnPartPurchased.Fire(ap);
ap.costsFunds = true;
HandlePurchase(ap);
}
}
EditorPartList.Instance?.Refresh();
EditorPartList.Instance?.Refresh(EditorPartList.State.PartsList);
if (HighLogic.LoadedSceneIsEditor)
SpaceCenterManagement.Instance.IsEditorRecalcuationRequired = true;
GamePersistence.SaveGame("persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
}
public static void AddResearchedPartsToExperimental()
{
if (ResearchAndDevelopment.Instance == null) return;
foreach (var ap in PartLoader.LoadedPartsList)
{
if (PartIsUnlockedButNotPurchased(ap))
{
AddExperimentalPart(ap);
}
}
}
public static void AddNodePartsToExperimental(string techID)
{
foreach (var ap in PartLoader.LoadedPartsList)
{
if (ap.TechRequired == techID && PartIsUnlockedButNotPurchased(ap))
{
AddExperimentalPart(ap);
}
}
}
public static void RemoveResearchedPartsFromExperimental()
{
foreach (var ap in PartLoader.LoadedPartsList)
{
if (PartIsUnlockedButNotPurchased(ap))
{
RemoveExperimentalPart(ap);
}
}
}
public static bool PartIsUnlockedButNotPurchased(AvailablePart ap)
{
bool nodeIsInList = ResearchAndDevelopment.Instance.protoTechNodes.TryGetValue(ap.TechRequired, out ProtoTechNode ptn);
if (!nodeIsInList) return SpaceCenterManagement.Instance.TechListHas(ap.TechRequired);
bool nodeIsUnlocked = ptn.state == RDTech.State.Available;
bool partNotPurchased = !ptn.partsPurchased.Contains(ap);
return nodeIsUnlocked && partNotPurchased;
}
public static bool AddExperimentalPart(AvailablePart ap)
{
if (ap is null || !KSPUtils.CurrentGameIsCareer() || ResearchAndDevelopment.IsExperimentalPart(ap))
return false;
ResearchAndDevelopment.AddExperimentalPart(ap);
return true;
}
public static bool RemoveExperimentalPart(AvailablePart ap)
{
if (ap is null || !KSPUtils.CurrentGameIsCareer())
return false;
ResearchAndDevelopment.RemoveExperimentalPart(ap);
return true;
}
public static void HandlePurchase(AvailablePart partInfo)
{
ProtoTechNode techState = ResearchAndDevelopment.Instance.GetTechState(partInfo.TechRequired);
foreach (var name in partInfo.identicalParts.Split(','))
{
if (PartLoader.getPartInfoByName(name.Replace('_', '.').Trim()) is AvailablePart info
&& info.TechRequired == partInfo.TechRequired)
{
info.costsFunds = false;
techState.partsPurchased.Add(info);
GameEvents.OnPartPurchased.Fire(info);
info.costsFunds = true;
}
}
}
private static void _checkTime(in ISpaceCenterProject item, ref double shortestTime, ref ISpaceCenterProject closest)
{
if (item.IsComplete()) return;
if (item.GetBuildRate() == 0) return;
double time = item.GetTimeLeft();
if (time < shortestTime)
{
closest = item;
shortestTime = time;
}
}
public static ISpaceCenterProject GetNextThingToFinish()
{
ISpaceCenterProject thing = null;
if (SpaceCenterManagement.Instance.ActiveSC == null)
return null;
double shortestTime = double.PositiveInfinity;
foreach (LCSpaceCenter KSC in SpaceCenterManagement.Instance.KSCs)
{
foreach (LaunchComplex LC in KSC.LaunchComplexes)
{
if (!LC.IsOperational)
continue;
foreach (ISpaceCenterProject vp in LC.BuildList)
_checkTime(vp, ref shortestTime, ref thing);
foreach (ISpaceCenterProject rr in LC.Recon_Rollout)
_checkTime(rr, ref shortestTime, ref thing);
}
foreach (ISpaceCenterProject ub in KSC.Constructions)
_checkTime(ub, ref shortestTime, ref thing);
}
foreach (ResearchProject tech in SpaceCenterManagement.Instance.TechList)
{
if (tech.GetBlockingTech() == null) // Ignore items that are blocked
_checkTime(tech, ref shortestTime, ref thing);
}
foreach (ISpaceCenterProject course in Crew.CrewHandler.Instance.TrainingCourses)
_checkTime(course, ref shortestTime, ref thing);
if (SpaceCenterManagement.Instance.fundTarget.IsValid)
_checkTime(SpaceCenterManagement.Instance.fundTarget, ref shortestTime, ref thing);
return thing;
}
public static void DisableModFunctionality()
{
DisableSimulationLocks();
InputLockManager.RemoveControlLock(SpaceCenterManagement.KCTLaunchLock);
KCT_GUI.HideAll();
}
public static List<string> GetLaunchSites(bool isVAB)
{
EditorDriver.editorFacility = isVAB ? EditorFacility.VAB : EditorFacility.SPH;
EditorDriver.setupValidLaunchSites();
return EditorDriver.ValidLaunchSites;
}
public static bool IsPrincipiaInstalled
{
get
{
if (!_isPrincipiaInstalled.HasValue)
{
_isPrincipiaInstalled = AssemblyLoader.loadedAssemblies.Any(a => string.Equals(a.name, "ksp_plugin_adapter", StringComparison.OrdinalIgnoreCase));
}
return _isPrincipiaInstalled.Value;
}
}
public static PQSCity FindKSC(CelestialBody home)
{
if (home?.pqsController?.transform?.Find("KSC") is Transform t &&
t.GetComponent(typeof(PQSCity)) is PQSCity KSC)
{
return KSC;
}
return Resources.FindObjectsOfTypeAll<PQSCity>().FirstOrDefault(x => x.name == "KSC");
}
public static bool IsLaunchFacilityIntact(ProjectType type)
{
bool intact = true;
if (type == ProjectType.VAB)
{
intact = new PreFlightTests.FacilityOperational("LaunchPad", "LaunchPad").Test();
}
else if (type == ProjectType.SPH)
{
if (!new PreFlightTests.FacilityOperational("Runway", "Runway").Test())
intact = false;
}
return intact;
}
public static bool IsApproximatelyEqual(double d1, double d2, double error = 0.01)
{
return (1 - error) <= (d1 / d2) && (d1 / d2) <= (1 + error);
}
public static bool ReconditioningActive(LaunchComplex LC, string launchSite = "LaunchPad")
{
if (LC == null) LC = SpaceCenterManagement.Instance.ActiveSC.ActiveLC;
return LC.GetReconditioning(launchSite) is ReconRolloutProject;
}
public static VesselProject FindVPByID(LaunchComplex hintLC, Guid id)
{
VesselProject b;
if (hintLC != null)
{
b = FindVPByIDInLC(id, hintLC);
if (b != null)
return b;
}
foreach (LCSpaceCenter ksc in SpaceCenterManagement.Instance.KSCs)
{
if (FindVPByID(id, ksc) is VesselProject vp)
return vp;
}
return null;
}
public static VesselProject FindVPByIDInLC(Guid id, LaunchComplex lc)
{
VesselProject ves = lc.Warehouse.Find(vp => vp.shipID == id);
if (ves != null)
return ves;
ves = lc.BuildList.Find(vp => vp.shipID == id);
if (ves != null)
return ves;
return null;
}
public static VesselProject FindVPByID(Guid id, LCSpaceCenter ksc)
{
if (ksc != null)
{
foreach (LaunchComplex lc in ksc.LaunchComplexes)
{
VesselProject ves = FindVPByIDInLC(id, lc);
if (ves != null)
return ves;
}
}
return null;
}
public static bool PartIsUnlocked(string partName)
{
if (partName == null) return false;
AvailablePart partInfoByName = PartLoader.getPartInfoByName(partName);
return PartIsUnlocked(partInfoByName);
}
public static bool PartIsUnlocked(AvailablePart ap)
{
if (ap == null) return false;
string partName = ap.name;
ProtoTechNode techState = ResearchAndDevelopment.Instance.GetTechState(ap.TechRequired);
bool partIsUnlocked = techState != null && techState.state == RDTech.State.Available &&
RUIutils.Any(techState.partsPurchased, (a => a.name == partName));
return partIsUnlocked;
}
public static bool PartIsExperimental(string partName)
{
if (partName == null) return false;
AvailablePart partInfoByName = PartLoader.getPartInfoByName(partName);
if (partInfoByName == null) return false;
return ResearchAndDevelopment.IsExperimentalPart(partInfoByName);
}
public static bool PartIsProcedural(Part part)
{
if (part?.Modules != null)
{
for (int i = 0; i < part.Modules.Count; i++)
{
if (part.Modules[i]?.moduleName?.IndexOf("procedural", StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
}
return false;
}
public static int GetBuildingUpgradeLevel(SpaceCenterFacility facility)
{
int lvl = GetBuildingUpgradeMaxLevel(facility);
if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
{
lvl = (int)Math.Round(lvl * ScenarioUpgradeableFacilities.GetFacilityLevel(facility));
}
return lvl;
}
public static int GetBuildingUpgradeLevel(string facilityID)
{
int lvl = GetBuildingUpgradeMaxLevel(facilityID);
if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
{
lvl = (int)Math.Round(lvl * ScenarioUpgradeableFacilities.GetFacilityLevel(facilityID));
}
return lvl;
}
public static int GetBuildingUpgradeMaxLevel(string facilityID)
{
int lvl = ScenarioUpgradeableFacilities.GetFacilityLevelCount(facilityID);
if (lvl < 0)
{
return Database.GetFacilityLevelCount(Database.FacilityIDToFacility.ValueOrDefault(facilityID));
}
return lvl;
}
public static int GetBuildingUpgradeMaxLevel(SpaceCenterFacility facility)
{
int lvl = ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility);
if (lvl < 0)
{
return Database.GetFacilityLevelCount(facility);
}
return lvl;
}
public static bool RecoverActiveVesselToStorage(ProjectType listType)
{
try
{
RP0Debug.Log("Attempting to recover active vessel to storage. listType: " + listType);
GamePersistence.SaveGame("KCT_Backup", HighLogic.SaveFolder, SaveMode.OVERWRITE);
SpaceCenterManagement.Instance.RecoveredVessel = new VesselProject(FlightGlobals.ActiveVessel, listType);
KCTVesselData vData = FlightGlobals.ActiveVessel.GetKCTVesselData();
SpaceCenterManagement.Instance.RecoveredVessel.KCTPersistentID = vData?.VesselID;
SpaceCenterManagement.Instance.RecoveredVessel.FacilityBuiltIn = vData?.FacilityBuiltIn ?? EditorFacility.None;
SpaceCenterManagement.Instance.RecoveredVessel.LCID = vData?.LCID ?? Guid.Empty;
SpaceCenterManagement.Instance.RecoveredVessel.LandedAt = FlightGlobals.ActiveVessel.landedAt;
//KCT_GameStates.recoveredVessel.type = listType;
if (listType == ProjectType.SPH)
SpaceCenterManagement.Instance.RecoveredVessel.launchSite = "Runway";
else
SpaceCenterManagement.Instance.RecoveredVessel.launchSite = "LaunchPad";
//check for symmetry parts and remove those references if they can't be found
SpaceCenterManagement.Instance.RecoveredVessel.RemoveMissingSymmetry();
// debug, save to a file
SpaceCenterManagement.Instance.RecoveredVessel.UpdateNodeAndSave("KCTVesselSave", false);
//test if we can actually convert it
var test = SpaceCenterManagement.Instance.RecoveredVessel.CreateShipConstructAndRelease();
if (test != null)
ShipConstruction.CreateBackup(test);
RP0Debug.Log("Load test reported success = " + (test == null ? "false" : "true"));
if (test == null)
{
SpaceCenterManagement.Instance.RecoveredVessel = new VesselProject();
return false;
}
// Recovering the vessel in a coroutine was generating an exception insideKSP if a mod had added
// modules to the vessel or it's parts at runtime.
//
// This is the way KSP does it
//
GameEvents.OnVesselRecoveryRequested.Fire(FlightGlobals.ActiveVessel);
return true;
}
catch (Exception ex)
{
RP0Debug.LogError("Error while recovering craft into inventory.");
RP0Debug.LogError("error: " + ex);
SpaceCenterManagement.Instance.RecoveredVessel = new VesselProject();
ShipConstruction.ClearBackups();
return false;
}
}
/// <summary>
/// Overrides or disables the editor's launch button (and individual site buttons) depending on settings
/// </summary>
public static void HandleEditorButton()
{
if (KCT_GUI.IsPrimarilyDisabled) return;
//also set the editor ui to 1 height
KCT_GUI.EditorWindowPosition.height = 1;
if (EditorLogic.fetch == null)
return;
if (KCTSettings.Instance.OverrideLaunchButton)
{
if (SpaceCenterManagement.EditorShipEditingMode)
{
// Prevent switching between VAB and SPH in edit mode.