-
Notifications
You must be signed in to change notification settings - Fork 47
/
LifeSupportMonitor.cs
557 lines (498 loc) · 22.2 KB
/
LifeSupportMonitor.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
using KSP.UI.Screens;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace LifeSupport
{
[KSPAddon(KSPAddon.Startup.Flight, false)]
public class LifeSupportMonitor_Flight : LifeSupportMonitor
{
protected override bool IsActive()
{
return HighLogic.LoadedSceneIsFlight;
}
}
[KSPAddon(KSPAddon.Startup.TrackingStation, false)]
public class LifeSupportMonitor_TStation : LifeSupportMonitor
{
protected override bool IsActive()
{
return HighLogic.LoadedScene == GameScenes.TRACKSTATION;
}
}
public class LifeSupportMonitor : MonoBehaviour
{
private ApplicationLauncherButton _lifeSupportMonitorButton;
private Rect _windowPosition = new Rect(300, 60, 970, 400);
private GUIStyle _windowStyle;
private GUIStyle _labelStyle;
private GUIStyle _scrollStyle;
private Vector2 _scrollPos = Vector2.zero;
private bool _hasInitStyles = false;
internal static string EcGraceTimeDisplay;
internal static string SuppliesGraceTimeDisplay;
public static bool _renderDisplay = false;
void Awake()
{
var texture = new Texture2D(36, 36, TextureFormat.RGBA32, false);
var textureFile = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Assets",
"Supplies.png");
print("Loading " + textureFile);
texture.LoadImage(File.ReadAllBytes(textureFile));
_lifeSupportMonitorButton = ApplicationLauncher.Instance.AddModApplication(GuiOn, GuiOff, null, null, null, null,
ApplicationLauncher.AppScenes.ALWAYS, texture);
}
private void GuiOn()
{
_renderDisplay = true;
}
public void Start()
{
if (!_hasInitStyles)
InitStyles();
}
private void GuiOff()
{
_renderDisplay = false;
}
private void OnGUI()
{
if (!_renderDisplay)
return;
if (!IsActive())
return;
if (Event.current.type == EventType.Repaint || Event.current.isMouse)
{
//preDrawQueue
}
Ondraw();
}
protected virtual bool IsActive()
{
return false;
}
private void Ondraw()
{
_windowPosition = GUILayout.Window(10, _windowPosition, OnWindow, "Life Support Status", _windowStyle);
}
private void OnWindow(int windowId)
{
GenerateWindow();
}
private double _lastGUIUpdate;
private double _guiCheckInterval = 1d;
private LifeSupportVesselDisplayStat GetEvaKerbalStats(Vessel kerbal)
{
var lblColor = "FFD966";
var vstat = new LifeSupportVesselDisplayStat();
vstat.VesselName = String.Format("<color=#{0}>{1}</color>", lblColor, kerbal.vesselName);
vstat.LastUpdate = kerbal.missionTime;
var sitString = "(EVA)";
var remEVATime = LifeSupportScenario.Instance.settings.GetSettings().EVATime - kerbal.missionTime;
var timeString = LifeSupportUtilities.SmartDurationDisplay(Math.Max(0, remEVATime));
if (remEVATime > 0)
{
vstat.SummaryLabel = String.Format(
"<color=#3DB1FF>{0}/{1} - </color><color=#9EE4FF>{2}</color><color=#3DB1FF> time remaining</color>"
, kerbal.mainBody.bodyName
, sitString
, timeString.Substring(timeString.IndexOf(':') + 1));
}
else
{
vstat.SummaryLabel = "<color=#FF8585>EVA Time Expired</color>";
}
vstat.crew = new List<LifeSupportCrewDisplayStat>();
return vstat;
}
private LifeSupportVesselDisplayStat GetVesselStats(VesselSupplyStatus vsl)
{
var secondsPerDay = LifeSupportUtilities.SecondsPerDay();
var useHabPenalties = (LifeSupportScenario.Instance.settings.GetSettings().NoHomeEffectVets +
LifeSupportScenario.Instance.settings.GetSettings().NoHomeEffect > 0);
Vessel thisVessel = FlightGlobals.Vessels.Find(v => v.id.ToString() == vsl.VesselId);
var vstat = new LifeSupportVesselDisplayStat();
bool isOldData = Planetarium.GetUniversalTime() - vsl.LastUpdate > 2;
var lblColor = isOldData ? "C4C4C4" : "ACFF40";
vstat.VesselName = String.Format("<color=#{0}>{1}</color>", lblColor, vsl.VesselName);
vstat.VesselId = vsl.VesselId;
vstat.LastUpdate = vsl.LastUpdate;
var situationString = GetSituationString(thisVessel);
double suppliesPerSecond = LifeSupportScenario.Instance.settings.GetSettings().SupplyAmount * Convert.ToDouble(vsl.NumCrew) * vsl.RecyclerMultiplier;
var suppliesPerDay = secondsPerDay * suppliesPerSecond;
var supAmount = GetResourceInVessel(thisVessel, "Supplies");
var suppliesTimeLeft = (suppliesPerSecond > ResourceUtilities.FLOAT_TOLERANCE) ? (supAmount / suppliesPerSecond) : 0;
if (supAmount == 0)
{
var suppliesConsumedSinceLastCheck = suppliesPerSecond * (Planetarium.GetUniversalTime() - vsl.LastFeeding);
supAmount = Math.Max(0, (vsl.SuppliesLeft * suppliesPerSecond) - suppliesConsumedSinceLastCheck);
suppliesTimeLeft = (vsl.SuppliesLeft - (Planetarium.GetUniversalTime() - vsl.LastFeeding));
}
double ecPerSecond = LifeSupportScenario.Instance.settings.GetSettings().ECAmount * Convert.ToDouble(vsl.NumCrew);
var ecAmount = GetResourceInVessel(thisVessel, "ElectricCharge");
var ecTimeLeft = (ecPerSecond > ResourceUtilities.FLOAT_TOLERANCE) ? (ecAmount / ecPerSecond) : 0;
if (ecAmount == 0)
{
var ecConsumedSinceLastCheck = ecPerSecond * (Planetarium.GetUniversalTime () - vsl.LastECCheck);
ecAmount = Math.Max (0, (vsl.ECLeft * ecPerSecond) - ecConsumedSinceLastCheck);
ecTimeLeft = (vsl.ECLeft - (Planetarium.GetUniversalTime() - vsl.LastECCheck));
}
int numSharedHabVessels = 0;
var habTime = LifeSupportManager.GetTotalHabTime(vsl, thisVessel, out numSharedHabVessels);
var habString = "indefinite";
if (useHabPenalties)
{
habString = LifeSupportUtilities.DurationDisplay(habTime, LifeSupportUtilities.TimeFormatLength.Short);
}
vstat.SummaryLabel = String.Format(
"<color=#3DB1FF>{0}/{1} - </color><color=#9EE4FF>{2:0}</color><color=#3DB1FF> supplies (</color><color=#9EE4FF>{3:0.0}</color><color=#3DB1FF>/day) hab for </color><color=#9EE4FF>{4}</color>"
, thisVessel.mainBody.bodyName
, situationString
, supAmount
, suppliesPerDay
, habString);
vstat.crew = new List<LifeSupportCrewDisplayStat>();
if (useHabPenalties)
{
vstat.SummaryLabel += String.Format(
"<color=#3DB1FF> (</color><color=#9EE4FF>{0}</color><color=#3DB1FF> {1} shared within </color><color=#9EE4FF>{2}</color><color=#3DB1FF>m)</color>",
isOldData ? "?" : numSharedHabVessels.ToString(),
numSharedHabVessels == 1 ? "vessel" : "vessels",
LifeSupportScenario.Instance.settings.GetSettings().HabRange);
}
foreach (var c in thisVessel.GetVesselCrew())
{
var crewStat = GetCrewStat(c, thisVessel, suppliesTimeLeft, ecTimeLeft, ecAmount, habTime);
vstat.crew.Add(crewStat);
}
vstat.crew = vstat.crew.OrderBy(crewStat => crewStat.EarliestExpiration).ToList();
if (vstat.crew.Any())
{
vstat.EarliestExpiration = vstat.crew.First().EarliestExpiration;
}
return vstat;
}
private IEnumerable<LifeSupportVesselDisplayStat> UpdateGUIStats()
{
LifeSupportManager.Instance.UpdateVesselStats();
var statList = new List<LifeSupportVesselDisplayStat>();
foreach (var vessel in FlightGlobals.Vessels)
{
if (vessel.isEVA)
{
statList.Add(GetEvaKerbalStats(vessel));
}
}
foreach(var trackedVessel in LifeSupportManager.Instance.VesselSupplyInfo)
{
statList.Add(GetVesselStats(trackedVessel));
}
var activeVesselId = FlightGlobals.ActiveVessel ? FlightGlobals.ActiveVessel.id.ToString() : "";
return statList.OrderByDescending(s => s.VesselId == activeVesselId).ThenBy(s => (int)(s.EarliestExpiration));
}
private IEnumerable<LifeSupportVesselDisplayStat> _guiStats;
private void GenerateWindow()
{
if (Planetarium.GetUniversalTime() > _lastGUIUpdate + _guiCheckInterval)
{
_lastGUIUpdate = Planetarium.GetUniversalTime();
EcGraceTimeDisplay = LifeSupportUtilities.CompactDurationDisplay(LifeSupportScenario.Instance.settings.GetSettings().ECTime);
SuppliesGraceTimeDisplay = LifeSupportUtilities.CompactDurationDisplay(LifeSupportScenario.Instance.settings.GetSettings().SupplyTime);
_guiStats = UpdateGUIStats();
}
GUILayout.BeginVertical();
_scrollPos = GUILayout.BeginScrollView(_scrollPos, _scrollStyle, GUILayout.Width(950), GUILayout.Height(350));
GUILayout.BeginVertical();
try
{
foreach (var v in _guiStats)
{
DisplayVesselStats(v);
}
}
catch (Exception ex)
{
Debug.Log(ex.StackTrace);
}
finally
{
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUI.DragWindow();
}
}
private void DisplayVesselStats(LifeSupportVesselDisplayStat v)
{
GUILayout.BeginHorizontal();
GUILayout.Label("", _labelStyle, GUILayout.Width(10));
GUILayout.Label(v.VesselName, _labelStyle, GUILayout.Width(155));
GUILayout.Label(v.SummaryLabel, _labelStyle, GUILayout.Width(570));
GUILayout.EndHorizontal();
foreach (var c in v.crew)
{
DisplayCrewStats(c);
}
}
private void DisplayCrewStats(LifeSupportCrewDisplayStat c)
{
GUILayout.BeginHorizontal();
GUILayout.Label("", _labelStyle, GUILayout.Width(30));
GUILayout.Label(c.CrewName, _labelStyle, GUILayout.Width(135));
GUILayout.Label("<color=#EDEDED>sup:</color>", _labelStyle, GUILayout.Width(35));
GUILayout.Label(c.SupplyLabel, _labelStyle, GUILayout.Width(145));
GUILayout.Label("<color=#EDEDED>EC:</color>", _labelStyle, GUILayout.Width(35));
GUILayout.Label(c.ECLabel, _labelStyle, GUILayout.Width(145));
GUILayout.Label("<color=#EDEDED>hab:</color>", _labelStyle, GUILayout.Width(40));
GUILayout.Label(c.HabLabel, _labelStyle, GUILayout.Width(145));
GUILayout.Label("<color=#EDEDED>home:</color>", _labelStyle, GUILayout.Width(40));
GUILayout.Label(c.HomeLabel, _labelStyle, GUILayout.Width(145));
GUILayout.EndHorizontal();
}
private double GetResourceInVessel(Vessel vessel, string resName)
{
if (vessel == null)
return 0d;
var amount = 0d;
var count = vessel.parts.Count;
for (int i = 0; i < count; ++i)
{
var p = vessel.parts[i];
if (!p.Resources.Contains(resName))
continue;
var res = p.Resources[resName];
if(res.flowState)
amount += res.amount;
}
return amount;
}
private string GetSituationString(Vessel vessel)
{
var sitString = "Orbiting";
vessel.checkSplashed();
if (vessel.Splashed)
sitString = "Splashed";
vessel.checkLanded();
if (vessel.Landed)
sitString = "Landed";
return sitString;
}
private LifeSupportCrewDisplayStat GetCrewStat(ProtoCrewMember c, Vessel vessel, double vesselSuppliesTimeLeft, double vesselEcTimeLeft, double vesselEcAmount, double vesselHabTime)
{
var cls = LifeSupportManager.Instance.FetchKerbal(c);
//Guard clause in case we just changed vessels
if (cls.CurrentVesselId != vessel.id.ToString()
&& cls.PreviousVesselId != vessel.id.ToString())
{
cls.PreviousVesselId = cls.CurrentVesselId;
cls.CurrentVesselId = vessel.id.ToString();
cls.TimeEnteredVessel = Planetarium.GetUniversalTime();
LifeSupportManager.Instance.TrackKerbal(cls);
}
// not sure this is correct or needed
var ecTimeLeft = vesselEcTimeLeft;
if (vesselEcAmount <= LifeSupportScenario.Instance.settings.GetSettings().ECAmount && !LifeSupportManager.IsOnKerbin(vessel))
{
ecTimeLeft = cls.LastEC - Planetarium.GetUniversalTime ();
}
var cStat = new LifeSupportCrewDisplayStat();
cStat.CrewName = GetCrewNameLabel(c, cls);
cStat.ComputeEc(ecTimeLeft, c);
cStat.ComputeSupply(vesselSuppliesTimeLeft, c);
cStat.ComputeHab(vesselHabTime, c, cls);
cStat.ComputeHome(c, cls);
LifeSupportManager.Instance.TrackKerbal(cls);
return cStat;
}
private string GetCrewNameLabel(ProtoCrewMember c, LifeSupportStatus cls)
{
var traitColor = cls.IsGrouchy ? "#FF0000" : "#FFFFFF";
var traitLabel = c.experienceTrait.Title.Substring (0, 1); // Could choose to display OldTrait instead
return String.Format("<color=#FFFFFF>{0}</color> <color={1}>({2})</color>", c.name, traitColor, traitLabel);
}
internal void OnDestroy()
{
if (_lifeSupportMonitorButton == null)
return;
ApplicationLauncher.Instance.RemoveModApplication(_lifeSupportMonitorButton);
_lifeSupportMonitorButton = null;
}
private void InitStyles()
{
_windowStyle = new GUIStyle(HighLogic.Skin.window);
_windowStyle.fixedWidth = 970f;
_windowStyle.fixedHeight = 400f;
_labelStyle = new GUIStyle(HighLogic.Skin.label);
_scrollStyle = new GUIStyle(HighLogic.Skin.scrollView);
_hasInitStyles = true;
}
}
public class LifeSupportVesselDisplayStat
{
public string VesselName { get; set; }
public string VesselId { get; set; }
public string SummaryLabel { get; set; }
public double LastUpdate { get; set; }
public double EarliestExpiration { get; set; }
public List<LifeSupportCrewDisplayStat> crew { get; set; }
public LifeSupportVesselDisplayStat()
{
EarliestExpiration = double.PositiveInfinity;
}
}
public class LifeSupportCrewDisplayStat
{
public string CrewName { get; set; }
public string ECLabel { get; set; }
public string SupplyLabel { get; set; }
public string HabLabel { get; set; }
public string HomeLabel { get; set; }
public double EarliestExpiration { get; set; }
public LifeSupportCrewDisplayStat()
{
EarliestExpiration = double.PositiveInfinity;
}
private void UpdateEarliestExpiration(double expirationIn)
{
var expiration = Planetarium.GetUniversalTime() + expirationIn;
if (expiration < EarliestExpiration)
{
EarliestExpiration = expiration;
}
}
internal void ComputeHab(double vesselHabTime, ProtoCrewMember c, LifeSupportStatus cls)
{
var crewHabString = "indefinite";
var lblHab = "6FFF00";
var useHabPenalties = LifeSupportManager.GetNoHomeEffect(c.name) > 0;
if (useHabPenalties)
{
UpdateEarliestExpiration(vesselHabTime);
var habTimeLeft = vesselHabTime - (Planetarium.GetUniversalTime() - cls.TimeEnteredVessel);
var isScout = c.HasEffect("ExplorerSkill") && habTimeLeft >= LifeSupportScenario.Instance.settings.GetSettings().ScoutHabTime;
var isPermaHab = habTimeLeft >= LifeSupportScenario.Instance.settings.GetSettings().PermaHabTime;
if(isScout || isPermaHab)
{
crewHabString = "indefinite";
}
else if (habTimeLeft < 0)
{
lblHab = "FF5E5E";
crewHabString = "expired";
}
else
{
crewHabString = LifeSupportUtilities.SmartDurationDisplay(habTimeLeft);
var secondsPerDay = LifeSupportUtilities.SecondsPerDay();
if (habTimeLeft < secondsPerDay * 30)
{
lblHab = "FFE100";
}
if (habTimeLeft < secondsPerDay * 15)
{
lblHab = "FFAE00";
}
}
}
HabLabel = String.Format("<color=#{0}>{1}</color>", lblHab, crewHabString);
}
internal void ComputeHome(ProtoCrewMember c, LifeSupportStatus cls)
{
var crewHomeString = "indefinite";
var lblHome = "6FFF00";
var useHabPenalties = LifeSupportManager.GetNoHomeEffect(c.name) > 0;
if (useHabPenalties)
{
var homeTimeLeft = cls.MaxOffKerbinTime - Planetarium.GetUniversalTime();
UpdateEarliestExpiration(homeTimeLeft);
var isScout = c.HasEffect("ExplorerSkill") && homeTimeLeft >= LifeSupportScenario.Instance.settings.GetSettings().ScoutHabTime;
var isPermaHab = homeTimeLeft >= LifeSupportScenario.Instance.settings.GetSettings().PermaHabTime;
if (isScout || isPermaHab)
{
crewHomeString = "indefinite";
}
else if (homeTimeLeft < 0)
{
lblHome = "FF5E5E";
crewHomeString = "expired";
}
else
{
crewHomeString = LifeSupportUtilities.SmartDurationDisplay(homeTimeLeft);
var secondsPerDay = LifeSupportUtilities.SecondsPerDay();
if (homeTimeLeft < secondsPerDay * 30) //15 days
{
lblHome = "FFE100";
}
if (homeTimeLeft < secondsPerDay * 15)
{
lblHome = "FFAE00";
}
}
}
HomeLabel = String.Format("<color=#{0}>{1}</color>", lblHome, crewHomeString);
}
private string GetRemainingTimeWithGraceLabel(double timeLeft, double graceTime, string graceTimeDisplay, string inGraceTimeMessage, int effectWhenExpires)
{
if (effectWhenExpires == 0)
{
return "<color=#6FFF00>indefinite</color>";
}
if (timeLeft > 0)
{
return String.Format("<color=#6FFF00>{0} (+{1})</color>",
LifeSupportUtilities.SmartDurationDisplay(timeLeft),
graceTimeDisplay);
}
else
{
var exceededTime = - timeLeft;
if (exceededTime < graceTime / 2)
{
return String.Format("<color=#FFE100>{0} ({1})</color>",
LifeSupportUtilities.SmartDurationDisplay(graceTime - exceededTime),
inGraceTimeMessage);
}
else if (exceededTime < graceTime)
{
return String.Format("<color=#FFAE00>{0} ({1})</color>",
LifeSupportUtilities.SmartDurationDisplay(graceTime - exceededTime),
inGraceTimeMessage);
}
else // exceededTime > graceTime
{
return "<color=#FF5E5E>expired</color>";
}
}
}
internal void ComputeEc(double ecTimeLeft, ProtoCrewMember c)
{
var noEcEffect = LifeSupportManager.GetNoECEffect(c.name);
ECLabel = GetRemainingTimeWithGraceLabel(
ecTimeLeft,
LifeSupportScenario.Instance.settings.GetSettings().ECTime,
LifeSupportMonitor.EcGraceTimeDisplay,
"out of EC",
noEcEffect);
}
internal void ComputeSupply(double vesselSuppliesTimeLeft, ProtoCrewMember c)
{
var noSupplyEffect = LifeSupportManager.GetNoSupplyEffect(c.name);
if (noSupplyEffect > 0)
{
UpdateEarliestExpiration(vesselSuppliesTimeLeft);
}
SupplyLabel = GetRemainingTimeWithGraceLabel(
vesselSuppliesTimeLeft,
LifeSupportScenario.Instance.settings.GetSettings().SupplyTime,
LifeSupportMonitor.SuppliesGraceTimeDisplay,
"starving",
noSupplyEffect);
}
}
}