-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathKerbalHealthScenario.cs
1199 lines (1059 loc) · 56.5 KB
/
KerbalHealthScenario.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.Localization;
using KSP.UI.Screens;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using static KerbalHealth.Core;
namespace KerbalHealth
{
/// <summary>
/// Main class for processing kerbals' health
/// </summary>
[KSPScenario(ScenarioCreationOptions.AddToAllGames, GameScenes.SPACECENTER, GameScenes.TRACKSTATION, GameScenes.FLIGHT, GameScenes.EDITOR)]
public class KerbalHealthScenario : ScenarioModule
{
// Current Kerbal Health version
Version version;
// UT at last health update
static double lastUpdated;
// List of scheduled radstorms
List<RadStorm> radStorms = new List<RadStorm>();
// Button handles
ApplicationLauncherButton appLauncherButton;
IButton toolbarButton;
// Health Monitor dimensions
const int colNumMain = 8, colNumDetails = 6;
const int colWidth = 100;
const int colSpacing = 10;
const int gridWidthList = colNumMain * (colWidth + colSpacing) - colSpacing;
const int gridWidthDetails = colNumDetails * (colWidth + colSpacing) - colSpacing;
// Health Monitor window
PopupDialog monitorWindow;
// Saved position of the Health Monitor window
static Rect windowPosition = new Rect(0.5f, 0.5f, gridWidthList, 200);
// Health Monitor grid's labels
List<DialogGUIBase> gridContent;
// List of displayed kerbal, sorted according to current settings
SortedList<ProtoCrewMember, KerbalHealthStatus> kerbals;
// Change flags
bool dirty = false, crewChanged = false, vesselChanged = false;
// Currently selected kerbal for details view, null if list is shown
KerbalHealthStatus selectedKHS = null;
// Current page in the list of kerbals
int page = 1;
// Whether the current vessel should be checked for untrained kerbals, to show notification
bool checkUntrainedKerbals = false;
// Message handle for untrained kerbals warning
ScreenMessage untrainedKerbalsWarningMessage;
// Comparer object for sorting kerbals in the Health Monitor
KerbalComparer kerbalComparer = new KerbalComparer(KerbalHealthGeneralSettings.Instance.SortByLocation);
// Profiling timers
#if DEBUG
IterationTimer mainloopTimer = new IterationTimer("MAIN LOOP");
IterationTimer updateTimer = new IterationTimer("GUI UPDATE", 25);
static IterationTimer saveTimer = new IterationTimer("SAVE");
static IterationTimer loadTimer = new IterationTimer("LOAD");
#endif
int LinesPerPage => KerbalHealthGeneralSettings.Instance.LinesPerPage;
bool ShowPages => Core.KerbalHealthList.Count > LinesPerPage;
int PageCount => (int)Math.Ceiling((double)(Core.KerbalHealthList.Count) / LinesPerPage);
int FirstLine => (page - 1) * LinesPerPage;
int LineCount => Math.Min(Core.KerbalHealthList.Count - FirstLine, LinesPerPage);
public void Start()
{
if (IsInEditor)
return;
// Automatically updating settings from older versions
Version currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (version != currentVersion)
version = currentVersion;
else Log($"Kerbal Health v{version}");
#if DEBUG
Log("Debug mode", LogLevel.Important);
#endif
// This needs to be run even if the mod is disabled, so that its settings can be reset:
GameEvents.OnGameSettingsApplied.Add(OnGameSettingsApplied);
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log("KerbalHealthScenario.Start", LogLevel.Important);
Core.KerbalHealthList.RegisterKerbals();
vesselChanged = true;
lastUpdated = Planetarium.GetUniversalTime();
GameEvents.onCrewOnEva.Add(OnKerbalEva);
GameEvents.onCrewBoardVessel.Add(OnCrewBoardVessel);
GameEvents.onCrewKilled.Add(OnCrewKilled);
GameEvents.OnCrewmemberHired.Add(OnCrewmemberHired);
GameEvents.OnCrewmemberSacked.Add(OnCrewmemberSacked);
GameEvents.onKerbalAdded.Add(OnKerbalAdded);
GameEvents.onKerbalRemoved.Add(OnKerbalRemoved);
GameEvents.onKerbalNameChanged.Add(OnKerbalNameChanged);
GameEvents.OnProgressComplete.Add(OnProgressComplete);
GameEvents.onVesselWasModified.Add(OnVesselWasModified);
SetupDeepFreeze();
SetupKerbalism();
if (CLS.Enabled)
Log("ConnectedLivingSpace detected.", LogLevel.Important);
else Log("ConnectedLivingSpace not found.");
if (RemoteTech.Installed)
Log("RemoteTech detected.", LogLevel.Important);
else Log("RemoteTech not found.");
if (KerbalHealthGeneralSettings.Instance.ShowAppLauncherButton)
RegisterAppLauncherButton();
if (ToolbarManager.ToolbarAvailable)
{
Log("Registering Toolbar button...");
toolbarButton = ToolbarManager.Instance.add("KerbalHealth", "HealthMonitor");
toolbarButton.Text = "Kerbal Health Monitor";
toolbarButton.TexturePath = "KerbalHealth/toolbar";
toolbarButton.ToolTip = "Kerbal Health";
toolbarButton.OnClick += _ => OnAppLauncherClicked();
}
if (VesselNeedsCheckForUntrainedCrew(FlightGlobals.ActiveVessel))
checkUntrainedKerbals = true;
}
public void OnDisable()
{
Log("KerbalHealthScenario.OnDisable", LogLevel.Important);
if (IsInEditor)
return;
HideWindow();
GameEvents.OnGameSettingsApplied.Remove(OnGameSettingsApplied);
GameEvents.onCrewOnEva.Remove(OnKerbalEva);
GameEvents.onCrewBoardVessel.Remove(OnCrewBoardVessel);
GameEvents.onCrewKilled.Remove(OnCrewKilled);
GameEvents.OnCrewmemberHired.Remove(OnCrewmemberHired);
GameEvents.OnCrewmemberSacked.Remove(OnCrewmemberSacked);
GameEvents.onKerbalAdded.Remove(OnKerbalAdded);
GameEvents.onKerbalRemoved.Remove(OnKerbalRemoved);
GameEvents.onKerbalNameChanged.Remove(OnKerbalNameChanged);
GameEvents.OnProgressComplete.Remove(OnProgressComplete);
GameEvents.onVesselWasModified.Remove(OnVesselWasModified);
GameEvents.FindEvent<EventData<Part, ProtoCrewMember>>("onKerbalFrozen")?.Remove(OnKerbalFrozen);
GameEvents.FindEvent<EventData<Part, ProtoCrewMember>>("onKerbalThaw")?.Remove(OnKerbalThaw);
UnregisterAppLauncherButton();
toolbarButton?.Destroy();
}
/// <summary>
/// Called to check and reset Kerbal Health settings, if needed
/// </summary>
public void OnGameSettingsApplied()
{
Log("OnGameSettingsApplied", LogLevel.Important);
if (KerbalHealthGeneralSettings.Instance.ResetSettings)
{
KerbalHealthGeneralSettings.Instance.Reset();
KerbalHealthFactorsSettings.Instance.Reset();
KerbalHealthQuirkSettings.Instance.Reset();
KerbalHealthRadiationSettings.Instance.Reset();
LoadSettingsFromConfig();
ScreenMessages.PostScreenMessage(Localizer.Format("#KH_MSG_SettingsReset"), 5);
}
if (KerbalHealthGeneralSettings.Instance.modEnabled && KerbalHealthGeneralSettings.Instance.ShowAppLauncherButton && appLauncherButton == null)
RegisterAppLauncherButton();
if (!KerbalHealthGeneralSettings.Instance.ShowAppLauncherButton || !KerbalHealthGeneralSettings.Instance.modEnabled)
UnregisterAppLauncherButton();
if (KerbalHealthGeneralSettings.Instance.modEnabled)
SetupKerbalism();
kerbalComparer = new KerbalComparer(KerbalHealthGeneralSettings.Instance.SortByLocation);
}
/// <summary>
/// Marks the kerbal as being on EVA to apply EVA-only effects
/// </summary>
public void OnKerbalEva(GameEvents.FromToAction<Part, Part> action)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log($"{action.to.protoModuleCrew[0].name} went on EVA from {action.from.name}.", LogLevel.Important);
Core.KerbalHealthList[action.to.protoModuleCrew[0]].IsOnEVA = true;
vesselChanged = true;
UpdateKerbals(true);
}
public void OnCrewBoardVessel(GameEvents.FromToAction<Part, Part> action)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log($"OnCrewBoardVessel(<'{action.from.name}', '{action.to.name}'>)");
for (int i = 0; i < action.to.protoModuleCrew.Count; i++)
Core.KerbalHealthList[action.to.protoModuleCrew[i]].IsOnEVA = false;
vesselChanged = true;
UpdateKerbals(true);
}
public void OnCrewKilled(EventReport er)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || er == null)
return;
Log($"OnCrewKilled(<'{er.msg}', {er.sender}, {er.other}>)", LogLevel.Important);
Core.KerbalHealthList.Remove(er.sender);
dirty = crewChanged = true;
}
public void OnCrewmemberHired(ProtoCrewMember pcm, int i)
{
Log($"OnCrewmemberHired('{pcm.name}', {i})", LogLevel.Important);
dirty = crewChanged = true;
}
public void OnCrewmemberSacked(ProtoCrewMember pcm, int i)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log($"OnCrewmemberSacked('{pcm.name}', {i})", LogLevel.Important);
Core.KerbalHealthList.Remove(pcm.name);
dirty = crewChanged = true;
}
public void OnKerbalAdded(ProtoCrewMember pcm)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || pcm == null)
return;
Log($"OnKerbalAdded('{pcm.name}')", LogLevel.Important);
if (pcm.type == ProtoCrewMember.KerbalType.Applicant || pcm.type == ProtoCrewMember.KerbalType.Unowned)
{
Log($"The kerbal is {pcm.type}. Skipping.", LogLevel.Important);
return;
}
Core.KerbalHealthList.Add(pcm);
dirty = crewChanged = true;
}
public void OnKerbalRemoved(ProtoCrewMember pcm)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || pcm == null)
return;
Log($"OnKerbalRemoved('{pcm.name}')", LogLevel.Important);
Core.KerbalHealthList.Remove(pcm.name);
dirty = crewChanged = true;
}
public void OnKerbalNameChanged(ProtoCrewMember pcm, string name1, string name2)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || pcm == null)
return;
Log($"OnKerbalNameChanged('{pcm.name}', '{name1}', '{name2}')", LogLevel.Important);
Core.KerbalHealthList.Rename(name1, name2);
dirty = true;
}
public void OnKerbalFrozen(Part part, ProtoCrewMember pcm)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || pcm == null)
return;
Log($"OnKerbalFrozen('{part.name}', '{pcm.name}')", LogLevel.Important);
Core.KerbalHealthList[pcm].AddCondition(KerbalHealthStatus.Condition_Frozen);
dirty = true;
}
public void OnKerbalThaw(Part part, ProtoCrewMember pcm)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled || pcm == null)
return;
Log($"OnKerbalThaw('{part.name}', '{pcm.name}')", LogLevel.Important);
Core.KerbalHealthList[pcm].RemoveCondition(KerbalHealthStatus.Condition_Frozen);
dirty = true;
}
/// <summary>
/// Checks if an anomaly has just been discovered and awards quirks to a random discoverer + clearing radiation
/// </summary>
public void OnProgressComplete(ProgressNode n)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log($"OnProgressComplete({n.Id})");
if (n is KSPAchievements.PointOfInterest poi && FlightGlobals.ActiveVessel.GetCrewCount() > 0)
{
Log($"Reached anomaly: {poi.Id} on {poi.body}", LogLevel.Important);
List<ProtoCrewMember> crew = FlightGlobals.ActiveVessel.GetVesselCrew();
if (Rand.NextDouble() < KerbalHealthQuirkSettings.Instance.AnomalyQuirkChance)
{
ProtoCrewMember pcm = crew[Rand.Next(crew.Count)];
Quirk quirk = Core.KerbalHealthList[pcm].AddRandomQuirk();
if (quirk != null)
Log($"{pcm.name} was awarded {quirk.Name} quirk for discovering an anomaly.", LogLevel.Important);
}
if (Rand.NextDouble() < KerbalHealthRadiationSettings.Instance.AnomalyDecontaminationChance)
{
ProtoCrewMember pcm = crew[Rand.Next(crew.Count)];
Log($"Clearing {pcm.name}'s radiation dose of {Core.KerbalHealthList[pcm].Dose:N0} BED.");
ShowMessage(Localizer.Format("#KH_MSG_AnomalyDecontamination", pcm.nameWithGender, Core.KerbalHealthList[pcm].Dose.PrefixFormat()), pcm);
Core.KerbalHealthList[pcm].Dose = 0;
}
}
}
public void OnVesselWasModified(Vessel v)
{
Log($"OnVesselWasModified('{v.vesselName}')");
vesselChanged = true;
}
public void FixedUpdate()
{
if (KerbalHealthGeneralSettings.Instance.modEnabled && !IsInEditor)
UpdateKerbals(false);
}
/// <summary>
/// Displays actual values in Health Monitor
/// </summary>
public void Update()
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
{
monitorWindow?.Dismiss();
return;
}
if (monitorWindow == null || !dirty)
return;
if (gridContent == null)
{
Log("KerbalHealthScenario.gridContent is null.", LogLevel.Error);
monitorWindow.Dismiss();
return;
}
#if DEBUG
updateTimer.Start();
#endif
// Showing list of all kerbals
if (selectedKHS == null)
{
if (crewChanged)
{
Core.KerbalHealthList.RegisterKerbals();
Invalidate();
crewChanged = false;
}
// Fill the Health Monitor's grid with kerbals' health data
for (int i = 0; i < LineCount; i++)
{
KerbalHealthStatus khs = kerbals.Values[FirstLine + i];
bool healthFrozen = khs.IsFrozen;
double change = khs.HPChangeTotal;
string formatTag = "", formatUntag = "", s;
if (healthFrozen || change == 0 || (khs.BalanceHP - khs.NextConditionHP) * change < 0)
if (khs.IsTrainingAtKSC)
s = TimeToString(khs.CurrentTrainingETA, false, 10);
else s = "—";
else
{
s = TimeToString(khs.ETAToNextCondition, false, 100);
if (change < 0)
{
formatTag = khs.HP <= khs.CriticalHP ? "<color=red>" : "<color=orange>";
formatUntag = "</color>";
}
}
gridContent[(i + 1) * colNumMain].SetOptionText(formatTag + khs.FullName + formatUntag);
gridContent[(i + 1) * colNumMain + 1].SetOptionText(formatTag + khs.LocationString + formatUntag);
gridContent[(i + 1) * colNumMain + 2].SetOptionText(formatTag + khs.ConditionString + formatUntag);
gridContent[(i + 1) * colNumMain + 3].SetOptionText($"{formatTag}{100 * khs.Health:F2}% ({khs.HP:F2}){formatUntag}");
gridContent[(i + 1) * colNumMain + 4].SetOptionText(formatTag + (healthFrozen || khs.Health >= 1 ? "—" : change.SignValue("F2")) + formatUntag);
gridContent[(i + 1) * colNumMain + 5].SetOptionText(formatTag + s + formatUntag);
gridContent[((i + 1) * colNumMain) + 6].SetOptionText($"{formatTag}{khs.Dose.PrefixFormat(3)}{(khs.Radiation != 0 ? $" ({Localizer.Format("#KH_HM_perDay", khs.Radiation.PrefixFormat(3, true))})" : "")}{formatUntag}");
}
}
// Showing details for one particular kerbal
else
{
ProtoCrewMember pcm = selectedKHS.ProtoCrewMember;
if (pcm == null)
{
selectedKHS = null;
Invalidate();
}
bool healthFrozen = selectedKHS.IsFrozen;
gridContent[1].SetOptionText($"<color=white>{selectedKHS.Name}</color>");
gridContent[3].SetOptionText($"<color=white>{pcm.experienceLevel} {pcm.trait}</color>");
gridContent[5].SetOptionText($"<color=white>{selectedKHS.ConditionString}</color>");
string s = "";
for (int j = 0; j < selectedKHS.Quirks.Count; j++)
if (selectedKHS.Quirks[j].IsVisible)
s += (s.Length != 0 ? ", " : "") + selectedKHS.Quirks[j].Title;
if (s.Length == 0)
s = Localizer.Format("#KH_HM_DNone");//None
gridContent[7].children[0].SetOptionText($"<color=white>{s}</color>");
gridContent[9].SetOptionText($"<color=white>{selectedKHS.MaxHP:F2}</color>");
gridContent[11].SetOptionText($"<color=white>{selectedKHS.HP:F2} ({selectedKHS.Health:P2})</color>");
gridContent[13].SetOptionText($"<color=white>{(healthFrozen ? "—" : selectedKHS.HPChangeTotal.ToString("F2"))}</color>");
int i = 15;
for (int j = 0; j < Factors.Count; j++)
{
gridContent[i].SetOptionText($"<color=white>{selectedKHS.GetFactorHPChange(Factors[j]):N2}</color>");
i += 2;
}
gridContent[i].children[0].SetOptionText($"<color=white>{(selectedKHS.TrainingVessel != null ? $"{selectedKHS.GetTrainingLevel():P0}{(selectedKHS.IsTrainingAtKSC ? $"/{KSCTrainingCap:P0}" : "")}" : Localizer.Format("#KH_NA"))}</color>");
gridContent[i + 2].SetOptionText($"<color=white>{(healthFrozen ? Localizer.Format("#KH_NA") : $"{selectedKHS.Recuperation:F1}%{(selectedKHS.Decay != 0 ? $"/ {-selectedKHS.Decay:F1}%" : "")} ({selectedKHS.HPChangeMarginal:F2} HP)")}</color>");
gridContent[i + 4].SetOptionText($"<color=white>{selectedKHS.Exposure:P1} / {selectedKHS.ShelterExposure:P1}</color>");
gridContent[i + 6].SetOptionText($"<color=white>{selectedKHS.Radiation:N0}/day</color>");
gridContent[i + 8].children[0].SetOptionText($"<color=white>{selectedKHS.Dose.PrefixFormat(6)}</color>");
gridContent[i + 10].SetOptionText($"<color=white>{1 - selectedKHS.RadiationMaxHPModifier:P2}</color>");
}
dirty = false;
#if DEBUG
updateTimer.Stop();
#endif
}
/// <summary>
/// Shows Health monitor when the AppLauncher/Blizzy's Toolbar button is clicked
/// </summary>
public void ShowWindow()
{
Log("KerbalHealthScenario.DisplayData", LogLevel.Important);
UpdateKerbals(true);
if (selectedKHS == null)
{
Log("No kerbal selected, showing overall list.");
// Preparing a sorted list of kerbals
kerbals = new SortedList<ProtoCrewMember, KerbalHealthStatus>(kerbalComparer);
foreach (KerbalHealthStatus khs in Core.KerbalHealthList.Values)
kerbals.Add(khs.ProtoCrewMember, khs);
DialogGUILayoutBase layout = new DialogGUIVerticalLayout(true, true);
if (page > PageCount)
page = PageCount;
if (ShowPages)
layout.AddChild(new DialogGUIHorizontalLayout(
true,
false,
new DialogGUIButton("<<", FirstPage, () => page > 1, true),
new DialogGUIButton("<", PageUp, () => page > 1, false),
new DialogGUIHorizontalLayout(TextAnchor.LowerCenter, new DialogGUILabel(Localizer.Format("#KH_HM_Page", page, PageCount))),
new DialogGUIButton(">", PageDown, () => page < PageCount, false),
new DialogGUIButton(">>", LastPage, () => page < PageCount, true)));
gridContent = new List<DialogGUIBase>((Core.KerbalHealthList.Count + 1) * colNumMain)
{
// Creating column titles
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Name")}</color></b>", true),//Name
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Location")}</color></b>", true),//Location
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Condition")}</color></b>", true),//Condition
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Health")}</color></b>", true),//Health
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Changeperday")}</color></b>", true),//Change/day
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_TimeLeft")}</color></b>", true),//Time Left
new DialogGUILabel($"<b><color=white>{Localizer.Format("#KH_HM_Radiation")}</color></b>", true),//Radiation
new DialogGUILabel("", true)
};
// Initializing Health Monitor's grid with empty labels, to be filled in Update()
for (int i = 0; i < LineCount; i++)
{
for (int j = 0; j < colNumMain - 1; j++)
gridContent.Add(new DialogGUILabel("", true));
gridContent.Add(new DialogGUIButton<int>(Localizer.Format("#KH_HM_Details"), n =>
{
selectedKHS = kerbals.Values[FirstLine + n];
Invalidate();
}, i));
}
layout.AddChild(new DialogGUIGridLayout(
new RectOffset(0, 0, 0, 0),
new Vector2(colWidth, 30),
new Vector2(colSpacing, 10),
UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
TextAnchor.MiddleCenter,
UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount,
colNumMain,
gridContent.ToArray()));
windowPosition.width = gridWidthList + 10;
monitorWindow = PopupDialog.SpawnPopupDialog(
new Vector2(0.5f, 0.5f),
new Vector2(0.5f, 0.5f),
new MultiOptionDialog("Health Monitor", "", Localizer.Format("#KH_HM_windowtitle"), HighLogic.UISkin, windowPosition, layout), //"Health Monitor"
false,
HighLogic.UISkin,
false);
}
else
{
// Creating the grid for detailed view, which will be filled in Update method
Log($"Showing details for {selectedKHS.Name}.");
gridContent = new List<DialogGUIBase>();
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DName")));//"Name:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DLevel")));//"Level:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DCondition")));//"Condition:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DQuirks")));//"Quirks:"
gridContent.Add(new DialogGUIHorizontalLayout(
new DialogGUILabel(""),
new DialogGUIButton(Localizer.Format("#KH_HM_DQuirkInfo"), OnQuirkInfo, () => selectedKHS.Quirks.Count > 0, 20, 20, false)));//"?"
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DMaxHP")));//"Max HP:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DHp")));//"HP:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DHPChange")));//"HP Change:"
gridContent.Add(new DialogGUILabel(""));
foreach (HealthFactor f in Factors)
{
gridContent.Add(new DialogGUILabel($"{f.Title}:"));
gridContent.Add(new DialogGUILabel(""));
}
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DTraining")));
gridContent.Add(new DialogGUIHorizontalLayout(
new DialogGUILabel(""),
new DialogGUIButton("?", OnTrainingInfo, 20, 20, false)));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DRecuperation")));//"Recuperation:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DExposure")));//"Exposure:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DRadiation")));//"Radiation:"
gridContent.Add(new DialogGUILabel(""));
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DLifetimeDose")));//"Lifetime Dose:"
gridContent.Add(new DialogGUIHorizontalLayout(
new DialogGUILabel(""),
new DialogGUIButton(Localizer.Format("#KH_HM_DDecon"), OnDecontamination, 50, 20, false)));//"Decon"
gridContent.Add(new DialogGUILabel(Localizer.Format("#KH_HM_DRadHPLoss")));//"Rad HP Loss:"
gridContent.Add(new DialogGUILabel(""));
windowPosition.width = gridWidthDetails + 8;
monitorWindow = PopupDialog.SpawnPopupDialog(
new Vector2(0.5f, 0.5f),
new Vector2(0.5f, 0.5f),
new MultiOptionDialog(
"Health Monitor",
"",
Localizer.Format("#KH_HM_Dwindowtitle"),
HighLogic.UISkin,
windowPosition,
new DialogGUIVerticalLayout(
new DialogGUIGridLayout(
new RectOffset(3, 3, 3, 3),
new Vector2(colWidth, 40),
new Vector2(colSpacing, 10),
UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
TextAnchor.MiddleCenter,
UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount,
colNumDetails,
gridContent.ToArray()),
new DialogGUIButton(
Localizer.Format("#KH_HM_backbtn"),
() =>
{
selectedKHS = null;
Invalidate();
},
gridWidthDetails,
20,
false))),
false, HighLogic.UISkin,
false);
}
dirty = true;
}
/// <summary>
/// Hides the Health Monitor window
/// </summary>
public void HideWindow()
{
if (monitorWindow != null)
{
windowPosition.position = new Vector2(monitorWindow.RTrf.anchoredPosition.x / Screen.width + 0.5f, monitorWindow.RTrf.anchoredPosition.y / Screen.height + 0.5f);
monitorWindow.Dismiss();
}
}
public override void OnSave(ConfigNode node)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log("KerbalHealthScenario.OnSave", LogLevel.Important);
#if DEBUG
saveTimer.Start();
#endif
if (!IsInEditor)
UpdateKerbals(true);
node.AddValue("version", version.ToString());
ConfigNode n2;
for (int i = 0; i < Core.KerbalHealthList.Count; i++)
{
Core.KerbalHealthList.List[i].Save(n2 = new ConfigNode(KerbalHealthStatus.ConfigNodeName));
node.AddNode(n2);
}
for (int i = 0; i < radStorms.Count; i++)
if (radStorms[i].Target != RadStormTargetType.None)
{
radStorms[i].Save(n2 = new ConfigNode(RadStorm.ConfigNodeName));
node.AddNode(n2);
}
#if DEBUG
saveTimer.Stop();
#endif
}
public override void OnLoad(ConfigNode node)
{
if (!KerbalHealthGeneralSettings.Instance.modEnabled)
return;
Log("KerbalHealthScenario.OnLoad", LogLevel.Important);
#if DEBUG
loadTimer.Start();
#endif
// If loading scenario for the first time, try to load settings from config
if (!ConfigLoaded)
LoadConfig();
if (!node.HasValue("nextEventTime") && LoadSettingsFromConfig())
ScreenMessages.PostScreenMessage(Localizer.Format("#KH_MSG_CustomSettingsLoaded"), 5);
version = new Version(node.GetString("version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()));
Core.KerbalHealthList.Clear();
foreach (ConfigNode n in node.GetNodes(KerbalHealthStatus.ConfigNodeName))
Core.KerbalHealthList.Add(new KerbalHealthStatus(n));
Log($"{Core.KerbalHealthList.Count} kerbals loaded.", LogLevel.Important);
radStorms = new List<RadStorm>(node.GetNodes(RadStorm.ConfigNodeName).Select(n => new RadStorm(n)));
Log($"{radStorms.Count} radstorms loaded.", LogLevel.Important);
lastUpdated = Planetarium.GetUniversalTime();
#if DEBUG
loadTimer.Stop();
#endif
}
void CheckEVA(Vessel v)
{
if (v == null)
return;
Log($"CheckEVA('{v.vesselName}')");
if (v.isEVA)
Log($"{v.vesselName} is on EVA.");
foreach (KerbalHealthStatus khs in v.GetVesselCrew().Select(pcm => Core.KerbalHealthList[pcm]).Where(khs => khs != null))
khs.IsOnEVA = v.isEVA;
}
void RegisterAppLauncherButton()
{
Log("Registering AppLauncher button...");
Texture2D icon = new Texture2D(38, 38);
icon.LoadImage(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "icon.png")));
appLauncherButton = ApplicationLauncher.Instance.AddModApplication(OnAppLauncherClicked, OnAppLauncherClicked, null, null, null, null, ApplicationLauncher.AppScenes.ALWAYS, icon);
}
void UnregisterAppLauncherButton()
{
if (appLauncherButton != null)
ApplicationLauncher.Instance?.RemoveModApplication(appLauncherButton);
}
bool LoadSettingsFromConfig()
{
Log("LoadSettingsFromConfig", LogLevel.Important);
ConfigNode settingsNode = GameDatabase.Instance.GetMergedConfigNodes("KERBALHEALTH_CONFIG")?.GetNode("SETTINGS");
if (settingsNode == null)
{
Log("KERBALHEALTH_CONFIG/SETTINGS node not found.", LogLevel.Important);
return false;
}
Log($"KERBALHEALTH_CONFIG node: {settingsNode}");
KerbalHealthGeneralSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthFactorsSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthQuirkSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthRadiationSettings.Instance.ApplyConfig(settingsNode);
Log($"Current difficulty preset is {HighLogic.CurrentGame.Parameters.preset}.", LogLevel.Important);
if (HighLogic.CurrentGame.Parameters.preset != GameParameters.Preset.Custom && settingsNode.HasNode(HighLogic.CurrentGame.Parameters.preset.ToString()))
{
settingsNode = settingsNode.GetNode(HighLogic.CurrentGame.Parameters.preset.ToString());
KerbalHealthGeneralSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthFactorsSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthQuirkSettings.Instance.ApplyConfig(settingsNode);
KerbalHealthRadiationSettings.Instance.ApplyConfig(settingsNode);
}
return true;
}
private void SetupDeepFreeze()
{
if (!DFWrapper.InstanceExists)
{
Log("Initializing DFWrapper...");
DFWrapper.InitDFWrapper();
if (DFWrapper.InstanceExists)
Log("DFWrapper initialized.", LogLevel.Important);
else Log("DeepFreeze not found.");
}
if (DFWrapper.InstanceExists)
{
EventData<Part, ProtoCrewMember> dfEvent;
dfEvent = GameEvents.FindEvent<EventData<Part, ProtoCrewMember>>("onKerbalFrozen");
if (dfEvent != null)
dfEvent.Add(OnKerbalFrozen);
else Log("Could not find onKerbalFrozen event!", LogLevel.Error);
dfEvent = GameEvents.FindEvent<EventData<Part, ProtoCrewMember>>("onKerbalThaw");
if (dfEvent != null)
dfEvent.Add(OnKerbalThaw);
else Log("Could not find onKerbalThaw event!", LogLevel.Error);
}
}
void SetupKerbalism()
{
if (KerbalHealthGeneralSettings.Instance.modEnabled && KerbalHealthGeneralSettings.Instance.KerbalismIntegration && Kerbalism.Found && !Kerbalism.IsSetup)
{
Kerbalism.SetRuleProperty("radiation", "degeneration", KerbalHealthRadiationSettings.Instance.RadiationEnabled ? 0 : 1);
Kerbalism.SetRuleProperty("stress", "degeneration", 0);
Kerbalism.FeatureComfort = false;
Kerbalism.FeatureLivingSpace = false;
Log($"Kerbalism radiation degeneration: {Kerbalism.GetRuleProperty("radiation", "degeneration")}");
Log($"Kerbalism stress degeneration: {Kerbalism.GetRuleProperty("stress", "degeneration")}");
Log($"Kerbalism Comfort feature is {(Kerbalism.FeatureComfort ? "enabled" : "disabled")}.");
Log($"Kerbalism Living Space feature is {(Kerbalism.FeatureLivingSpace ? "enabled" : "disabled")}.");
Kerbalism.IsSetup = true;
Log("Kerbalism integration initialized.", LogLevel.Important);
}
}
bool VesselNeedsCheckForUntrainedCrew(Vessel v) =>
KerbalHealthFactorsSettings.Instance.TrainingEnabled
&& HighLogic.LoadedSceneIsFlight
&& v.situation == Vessel.Situations.PRELAUNCH;
/// <summary>
/// Checks the given vessel and displays an alert if any of the crew isn't fully trained
/// </summary>
void CheckUntrainedCrewWarning(Vessel v)
{
if (v == null)
return;
Log($"CheckUntrainedCrewWarning('{v.vesselName}')");
if (!VesselNeedsCheckForUntrainedCrew(v))
{
Log("Disabling untrained crew warning.");
checkUntrainedKerbals = false;
untrainedKerbalsWarningMessage.duration = 0;
return;
}
string msg = "";
int n = 0;
foreach (ProtoCrewMember pcm in v.GetVesselCrew())
{
KerbalHealthStatus khs = Core.KerbalHealthList[pcm];
if (khs == null)
{
Log($"KerbalHealthStatus for {pcm.name} in {v.vesselName} not found!", LogLevel.Error);
continue;
}
Log($"{pcm.name} is trained {khs.GetTrainingLevel():P1} / {KSCTrainingCap:P1}.");
if (khs.GetTrainingLevel() < KSCTrainingCap)
{
msg += (msg.Length == 0 ? "" : ", ") + pcm.name;
n++;
}
}
Log($"{n} kerbals are untrained: {msg}");
if (n == 0)
return;
untrainedKerbalsWarningMessage = new ScreenMessage(
Localizer.Format(n == 1 ? "#KH_TrainingAlert1" : "#KH_TrainingAlertMany", msg),
KerbalHealthGeneralSettings.Instance.UpdateInterval,
ScreenMessageStyle.UPPER_CENTER);
ScreenMessages.PostScreenMessage(untrainedKerbalsWarningMessage);
}
void TrainVessel(Vessel v)
{
if (v == null)
return;
Log($"KerbalHealthScenario.TrainVessel('{v.vesselName}')");
for (int i = 0; i < v.GetVesselCrew().Count; i++)
{
KerbalHealthStatus khs = Core.KerbalHealthList[v.GetVesselCrew()[i]];
if (khs == null)
Core.KerbalHealthList.Add(khs = new KerbalHealthStatus(v.GetVesselCrew()[i]));
khs.StartTraining(v.Parts, khs.IsOnEVA ? Localizer.Format("#KH_Spacesuit") : v.vesselName);
}
}
void SpawnRadStorms(float interval)
{
Log($"SpawnRadStorms({interval:F2})");
Dictionary<int, RadStorm> targets = new Dictionary<int, RadStorm>
{ { Planetarium.fetch.Home.name.GetHashCode(), new RadStorm(Planetarium.fetch.Home) } };
foreach (ProtoCrewMember pcm in HighLogic.fetch.currentGame.CrewRoster.Kerbals(ProtoCrewMember.RosterStatus.Assigned))
{
Vessel v = pcm.GetVessel();
if (v == null)
continue;
CelestialBody body = v.mainBody;
Log($"{pcm.name} is in {v.vesselName} in {body.name}'s SOI.");
int targetKey;
if (body == Planetarium.fetch.Sun)
{
targetKey = (int)v.persistentId;
if (!targets.ContainsKey(targetKey))
targets.Add(targetKey, new RadStorm(v));
}
else
{
body = body.GetPlanet();
targetKey = body.name.GetHashCode();
if (!targets.ContainsKey(targetKey))
targets.Add(targetKey, new RadStorm(body));
}
}
Log($"{targets.Count} potential radstorm targets found.");
Log($"Current solar cycle phase: {SolarCyclePhase:P2} through. Radstorm MTBE: {RadStormMTBE:N0} days.");
foreach (RadStorm t in targets.Values)
if (EventHappens(RadStormMTBE / KerbalHealthRadiationSettings.Instance.RadStormFrequency * KSPUtil.dateTimeFormatter.Day, interval))
{
RadStormType rst = GetRandomRadStormType();
double delay = t.DistanceFromSun / rst.GetRandomVelocity();
t.Magnitutde = rst.GetRandomMagnitude();
Log($"Radstorm will hit {t.Name} travel distance: {t.DistanceFromSun:F0} m; travel time: {delay:N0} s; magnitude {t.Magnitutde:N0}.");
t.Time = Planetarium.GetUniversalTime() + delay;
ShowMessage(Localizer.Format("#KH_RadStorm_Alert", rst.Name, t.Name, KSPUtil.PrintDate(t.Time, true)), true);//A radiation storm of <color=yellow>" + rst.Name + "</color> strength is going to hit <color=yellow>" + t.Name + "</color> on <color=yellow>" + KSPUtil.PrintDate(t.Time, true) + "</color>!
radStorms.Add(t);
}
}
/// <summary>
/// The main method for updating all kerbals' health and processing events
/// </summary>
/// <param name="forced">Whether to process kerbals regardless of the amount of time passed</param>
void UpdateKerbals(bool forced)
{
double time = Planetarium.GetUniversalTime();
float interval = (float)(time - lastUpdated);
if (!forced && (interval < KerbalHealthGeneralSettings.Instance.UpdateInterval || interval < KerbalHealthGeneralSettings.Instance.MinUpdateInterval * TimeWarp.CurrentRate))
return;
#if DEBUG
mainloopTimer.Start();
#endif
Log($"UT is {time}. Updating for {interval} seconds.");
ClearVesselsCache();
if (HighLogic.LoadedSceneIsFlight && vesselChanged)
{
Log("Vessel has changed or just loaded. Ordering kerbals to train for it in-flight, and checking if anyone's on EVA.");
foreach (Vessel v in FlightGlobals.VesselsLoaded)
{
CheckEVA(v);
TrainVessel(v);
}
vesselChanged = false;
}
if (checkUntrainedKerbals)
CheckUntrainedCrewWarning(FlightGlobals.ActiveVessel);
// Processing radiation storms' effects
if (KerbalHealthRadiationSettings.Instance.RadiationEnabled && KerbalHealthRadiationSettings.Instance.RadStormsEnabled && !KerbalHealthRadiationSettings.Instance.UseKerbalismRadiation)
{
for (int i = 0; i < radStorms.Count; i++)
if (time >= radStorms[i].Time)
{
int j = 0;
double m = radStorms[i].Magnitutde * KerbalHealthStatus.GetSolarRadiationProportion(radStorms[i].DistanceFromSun) * KerbalHealthRadiationSettings.Instance.RadStormMagnitude;
Log($"Radstorm {i} hits {radStorms[i].Name} with magnitude of {m} ({radStorms[i].Magnitutde} before modifiers).", LogLevel.Important);
string s = Localizer.Format("#KH_RadStorm_report1", m.PrefixFormat(5), radStorms[i].Name);
foreach (KerbalHealthStatus khs in Core.KerbalHealthList.Values.Where(khs => radStorms[i].Affects(khs.ProtoCrewMember)))
{
double d = m * KerbalHealthStatus.GetCosmicRadiationRate(khs.ProtoCrewMember.GetVessel()) * khs.ShelterExposure;
khs.AddDose(d);
Log($"The radstorm irradiates {khs.Name} by {d:N0} BED.");
s += Localizer.Format("#KH_RadStorm_report2", khs.Name, d.PrefixFormat(5));
j++;
}
if (j > 0)
ShowMessage(s, true);
radStorms.RemoveAt(i--);
}
if (GetYear(time) > GetYear(lastUpdated))
ShowMessage(Localizer.Format("#KH_RadStorm_AnnualReport", (SolarCyclePhase * 100).ToString("N1"), Math.Floor(time / SolarCycleDuration + 1).ToString("N0"), (RadStormMTBE / KerbalHealthRadiationSettings.Instance.RadStormFrequency).ToString("N0")), false); //You are " + + " through solar cycle " + + ". Current mean time between radiation storms is " + + " days.
}
Core.KerbalHealthList.Update(interval);
lastUpdated = time;
// Processing events. It can take several turns of event processing at high time warp
if (KerbalHealthQuirkSettings.Instance.ConditionsEnabled)
{
Log("Processing conditions...");
for (int i = 0; i < Core.KerbalHealthList.Count; i++)
{
KerbalHealthStatus khs = Core.KerbalHealthList.List[i];
ProtoCrewMember pcm = khs.ProtoCrewMember;
if (khs.IsFrozen || !pcm.IsTrackable())
continue;
for (int j = khs.Conditions.Count - 1; j >= 0; j--)
{
HealthCondition hc = khs.Conditions[j];
Log($"Processing {khs.Name}'s {hc.Name} condition.");
for (int k = 0; k < hc.Outcomes.Count; k++)
{
float mtbe = (float)hc.Outcomes[k].GetMTBE(pcm) / KerbalHealthQuirkSettings.Instance.EventFrequency;
Log($"MTBE of outcome #{k}: {mtbe:N1} days.");
if (EventHappens(mtbe * KSPUtil.dateTimeFormatter.Day, interval))
{
Log($"Condition {hc.Name} has outcome: {hc.Outcomes[k]}.");
if (hc.Outcomes[k].Condition.Length != 0)
khs.AddCondition(hc.Outcomes[k].Condition);
if (hc.Outcomes[k].RemoveOldCondition)
{
khs.RemoveCondition(hc);
break;
}
}
}
}
for (int j = 0; j < HealthConditions.Count; j++)
{
HealthCondition hc = HealthConditions.Values.ToList()[j];
if ((hc.Stackable || !khs.HasCondition(hc))
&& hc.IsCompatibleWith(khs.Conditions)
&& hc.Logic.Test(pcm)
&& EventHappens(hc.GetMTBE(pcm) / KerbalHealthQuirkSettings.Instance.EventFrequency * KSPUtil.dateTimeFormatter.Day, interval))
{
Log($"{khs.Name} acquires {hc.Name} condition.");
khs.AddCondition(hc);
}
}
}
if (KerbalHealthRadiationSettings.Instance.RadiationEnabled