forked from RemoteTechnologiesGroup/RemoteTech
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleRTAntenna.cs
More file actions
478 lines (415 loc) · 18 KB
/
Copy pathModuleRTAntenna.cs
File metadata and controls
478 lines (415 loc) · 18 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace RemoteTech
{
[KSPModule("Antenna")]
public class ModuleRTAntenna : PartModule, IAntenna
{
public String Name { get { return part.partInfo.title; } }
public Guid Guid { get { return mRegisteredId; } }
public bool Powered { get { return IsRTPowered; } }
public bool Activated { get { return IsRTActive; } set { SetState(value); } }
public bool Animating { get { return mDeployFxModules.Any(fx => fx.GetScalar > 0.1f && fx.GetScalar < 0.9f); } }
public bool CanTarget { get { return Mode1DishRange != -1.0f; } }
public Guid Target
{
get { return RTAntennaTarget; }
set
{
RTAntennaTarget = value;
Events["EventTarget"].guiName = RTUtil.TargetName(Target);
foreach (UIPartActionWindow w in GameObject.FindObjectsOfType(typeof(UIPartActionWindow)).Where(w => ((UIPartActionWindow) w).part == part))
{
w.displayDirty = true;
}
}
}
public float Dish { get { return IsRTBroken ? 0.0f : ((IsRTActive && IsRTPowered) ? Mode1DishRange : Mode0DishRange) * RangeMultiplier; } }
public double Radians { get { return RTDishRadians; } }
public float Omni { get { return IsRTBroken ? 0.0f : ((IsRTActive && IsRTPowered) ? Mode1OmniRange : Mode0OmniRange) * RangeMultiplier; } }
public float Consumption { get { return IsRTBroken ? 0.0f : IsRTActive ? EnergyCost * ConsumptionMultiplier : 0.0f; } }
public Vector3d Position { get { return vessel.GetWorldPos3D(); } }
private float RangeMultiplier { get { return RTSettings.Instance.RangeMultiplier; } }
private float ConsumptionMultiplier { get { return RTSettings.Instance.ConsumptionMultiplier; } }
[KSPField]
public bool
ShowGUI_DishRange = true,
ShowGUI_OmniRange = true,
ShowGUI_EnergyReq = true,
ShowGUI_Status = true,
ShowEditor_OmniRange = true,
ShowEditor_DishRange = true,
ShowEditor_EnergyReq = true,
ShowEditor_DishAngle = true;
[KSPField(guiName = "Dish range")]
public String GUI_DishRange;
[KSPField(guiName = "Energy")]
public String GUI_EnergyReq;
[KSPField(guiName = "Omni range")]
public String GUI_OmniRange;
[KSPField(guiName = "Status")]
public String GUI_Status;
[KSPField]
public String
Mode0Name = "Off",
Mode1Name = "Operational",
ActionMode0Name = "Deactivate",
ActionMode1Name = "Activate",
ActionToggleName = "Toggle";
[KSPField]
public float
Mode0DishRange = -1.0f,
Mode1DishRange = -1.0f,
Mode0OmniRange = 0.0f,
Mode1OmniRange = 0.0f,
EnergyCost = 0.0f,
DishAngle = 0.0f,
MaxQ = -1;
[KSPField(isPersistant = true)]
public bool
IsRTAntenna = true,
IsRTActive = false,
IsRTPowered = false,
IsRTBroken = false;
[KSPField(isPersistant = true)]
public double RTDishRadians = 1.0f;
[KSPField(isPersistant = true)]
public float
RTOmniRange = 0.0f,
RTDishRange = 0.0f;
[KSPField] // Persistence handled by Save()
public Guid RTAntennaTarget = Guid.Empty;
public int[] mDeployFxModuleIndices, mProgressFxModuleIndices;
private List<IScalarModule> mDeployFxModules = new List<IScalarModule>();
private List<IScalarModule> mProgressFxModules = new List<IScalarModule>();
public ConfigNode mTransmitterConfig;
private IScienceDataTransmitter mTransmitter;
private enum State
{
Off,
Operational,
NoResources,
Malfunction,
}
private Guid mRegisteredId;
public override string GetInfo()
{
var info = new StringBuilder();
if (ShowEditor_OmniRange && Mode1OmniRange > 0)
{
info.AppendFormat("Omni range: {0} / {1}", RTUtil.FormatSI(Mode0OmniRange * RangeMultiplier, "m"), RTUtil.FormatSI(Mode1OmniRange * RangeMultiplier, "m")).AppendLine();
}
if (ShowEditor_DishRange && Mode1DishRange > 0)
{
info.AppendFormat("Dish range: {0} / {1}", RTUtil.FormatSI(Mode0DishRange * RangeMultiplier, "m"), RTUtil.FormatSI(Mode1DishRange * RangeMultiplier, "m")).AppendLine();
}
if (ShowEditor_EnergyReq && EnergyCost > 0)
{
info.AppendFormat("Energy req.: {0}", RTUtil.FormatConsumption(EnergyCost * ConsumptionMultiplier)).AppendLine();
}
if (ShowEditor_DishAngle && CanTarget)
{
info.AppendFormat("Cone angle: {0} degrees", DishAngle.ToString("F2")).AppendLine();
}
if (IsRTActive)
{
info.AppendLine("Activated by default");
}
if (MaxQ > 0)
{
info.AppendLine("Snaps under high dynamic pressure");
}
return info.ToString().TrimEnd(Environment.NewLine.ToCharArray());
}
public virtual void SetState(bool state)
{
bool prev_state = IsRTActive;
IsRTActive = state && !IsRTBroken;
Events["EventOpen"].guiActive = Events["EventOpen"].active =
Events["EventEditorOpen"].guiActiveEditor =
Events["OverrideOpen"].guiActiveUnfocused = !IsRTActive && !IsRTBroken;
Events["EventClose"].guiActive = Events["EventClose"].active =
Events["EventEditorClose"].guiActiveEditor =
Events["OverrideClose"].guiActiveUnfocused = IsRTActive && !IsRTBroken;
UpdateContext();
StartCoroutine(SetFXModules_Coroutine(mDeployFxModules, IsRTActive ? 1.0f : 0.0f));
if (RTCore.Instance != null)
{
var satellite = RTCore.Instance.Network[Guid];
bool route_home = RTCore.Instance.Network[satellite].Any(r => r.Links[0].Interfaces.Contains(this) && RTCore.Instance.Network.GroundStations.ContainsKey(r.Goal.Guid));
if (mTransmitter == null && route_home)
{
AddTransmitter();
}
else if (!route_home && mTransmitter != null)
{
RemoveTransmitter();
}
}
}
[KSPEvent(name = "EventToggle", guiActive = false)]
public void EventToggle() { if (Animating) return; if (IsRTActive) { EventClose(); } else { EventOpen(); } }
[KSPEvent(name = "EventTarget", guiActive = false, guiName = "Target", category = "skip_delay")]
public void EventTarget() { (new AntennaWindow(this)).Show(); }
[KSPEvent(name = "EventEditorOpen", guiActive = false, guiName = "Start deployed")]
public void EventEditorOpen() { SetState(true); }
[KSPEvent(name = "EventEditorClose", guiActive = false, guiName = "Start retracted")]
public void EventEditorClose() { SetState(false); }
[KSPEvent(name = "EventOpen", guiActive = false)]
public void EventOpen() { if (!Animating) { SetState(true); } }
[KSPEvent(name = "EventClose", guiActive = false)]
public void EventClose() { if (!Animating) { SetState(false); } }
[KSPAction("ActionToggle", KSPActionGroup.None)]
public void ActionToggle(KSPActionParam param) { EventToggle(); }
[KSPAction("ActionOpen", KSPActionGroup.None)]
public void ActionOpen(KSPActionParam param) { EventOpen(); }
[KSPAction("ActionClose", KSPActionGroup.None)]
public void ActionClose(KSPActionParam param) { EventClose(); }
[KSPEvent(name = "OverrideTarget", active = true, guiActiveUnfocused = true, unfocusedRange = 5, externalToEVAOnly = true, guiName = "[EVA] Set Target", category = "skip_delay;skip_control")]
public void OverrideTarget() { (new AntennaWindow(this)).Show(); }
[KSPEvent(name = "OverrideOpen", active = true, guiActiveUnfocused = true, unfocusedRange = 5, externalToEVAOnly = true, guiName = "[EVA] Force Open", category = "skip_delay;skip_control")]
public void OverrideOpen() { EventOpen(); }
[KSPEvent(name = "OverrideClose", active = true, guiActiveUnfocused = true, unfocusedRange = 5, externalToEVAOnly = true, guiName = "[EVA] Force Close", category = "skip_delay;skip_control")]
public void OverrideClose() { EventClose(); }
public void OnConnectionRefresh()
{
SetState(IsRTActive);
}
public override void OnLoad(ConfigNode node)
{
base.OnLoad(node);
if (node.HasValue("RTAntennaTarget"))
{
try
{
Target = new Guid(node.GetValue("RTAntennaTarget"));
}
catch (FormatException)
{
Target = Guid.Empty;
}
}
if (node.HasValue("DishAngle"))
{
RTDishRadians = Math.Cos(DishAngle / 2 * Math.PI / 180);
}
if (node.HasValue("DeployFxModules"))
{
mDeployFxModuleIndices = KSPUtil.ParseArray<Int32>(node.GetValue("DeployFxModules"), new ParserMethod<Int32>(Int32.Parse));
}
if (node.HasValue("ProgressFxModules"))
{
mProgressFxModuleIndices = KSPUtil.ParseArray<Int32>(node.GetValue("ProgressFxModules"), new ParserMethod<Int32>(Int32.Parse));
}
if (node.HasNode("TRANSMITTER"))
{
RTLog.Notify("ModuleRTAntenna: Found TRANSMITTER block.");
mTransmitterConfig = node.GetNode("TRANSMITTER");
mTransmitterConfig.AddValue("name", "ModuleRTDataTransmitter");
}
}
public override void OnSave(ConfigNode node)
{
base.OnSave(node);
if (node.HasValue("RTAntennaTarget"))
{
node.SetValue("RTAntennaTarget", RTAntennaTarget.ToString());
}
else
{
node.AddValue("RTAntennaTarget", RTAntennaTarget.ToString());
}
}
public override void OnStart(StartState state)
{
Actions["ActionOpen"].guiName = ActionMode1Name;
Actions["ActionOpen"].active = !IsRTBroken;
Actions["ActionClose"].guiName = ActionMode0Name;
Actions["ActionClose"].active = !IsRTBroken;
Actions["ActionToggle"].guiName = ActionToggleName;
Actions["ActionToggle"].active = !IsRTBroken;
Events["EventOpen"].guiName = ActionMode1Name;
Events["EventClose"].guiName = ActionMode0Name;
Events["EventToggle"].guiName = ActionToggleName;
Events["EventTarget"].guiActive = (Mode1DishRange > 0);
Events["EventTarget"].active = Events["EventTarget"].guiActive;
Fields["GUI_OmniRange"].guiActive = (Mode1OmniRange > 0) && ShowGUI_OmniRange;
Fields["GUI_DishRange"].guiActive = (Mode1DishRange > 0) && ShowGUI_DishRange;
Fields["GUI_EnergyReq"].guiActive = (EnergyCost > 0) && ShowGUI_EnergyReq;
Fields["GUI_Status"].guiActive = ShowGUI_Status;
if (RTCore.Instance != null)
{
GameEvents.onVesselWasModified.Add(OnVesselModified);
GameEvents.onPartUndock.Add(OnPartUndock);
mRegisteredId = vessel.id;
RTCore.Instance.Antennas.Register(vessel.id, this);
}
LoadAnimations();
SetState(IsRTActive);
}
private void LoadAnimations()
{
mDeployFxModules = FindFxModules(this.mDeployFxModuleIndices, true);
mProgressFxModules = FindFxModules(this.mProgressFxModuleIndices, false);
mDeployFxModules.ForEach(fx => { fx.SetUIRead(false); fx.SetUIWrite(false); });
mProgressFxModules.ForEach(fx => { fx.SetUIRead(false); fx.SetUIWrite(false); });
}
private void AddTransmitter()
{
if (mTransmitterConfig == null || !mTransmitterConfig.HasValue("name")) return;
var transmitters = part.FindModulesImplementing<IScienceDataTransmitter>();
if (transmitters.Count > 0)
{
RTLog.Notify("ModuleRTAntenna: Find TRANSMITTER success.");
mTransmitter = transmitters.First();
}
else
{
var copy = new ConfigNode();
mTransmitterConfig.CopyTo(copy);
part.AddModule(copy);
AddTransmitter();
RTLog.Notify("ModuleRTAntenna: Add TRANSMITTER success.");
}
}
private void RemoveTransmitter()
{
RTLog.Notify("ModuleRTAntenna: Remove TRANSMITTER success.");
if (mTransmitter == null) return;
part.RemoveModule((PartModule) mTransmitter);
mTransmitter = null;
}
private State UpdateControlState()
{
if (RTCore.Instance == null) return State.Operational;
if (IsRTBroken) return State.Malfunction;
if (!IsRTActive) return State.Off;
ModuleResource request = new ModuleResource();
float resourceRequest = Consumption * (TimeWarp.fixedDeltaTime / TimeWarp.CurrentRate);
float resourceAmount = part.RequestResource("ElectricCharge", resourceRequest);
if (resourceAmount < resourceRequest * 0.9) return State.NoResources;
return State.Operational;
}
private void FixedUpdate()
{
switch (UpdateControlState())
{
case State.Off:
GUI_Status = Mode0Name;
IsRTPowered = false;
break;
case State.Operational:
GUI_Status = Mode1Name;
IsRTPowered = true;
break;
case State.NoResources:
GUI_Status = "Out of power";
IsRTPowered = false;
break;
case State.Malfunction:
GUI_Status = "Malfunction";
IsRTPowered = false;
break;
}
RTDishRange = Dish;
RTOmniRange = Omni;
HandleDynamicPressure();
UpdateContext();
}
private void UpdateContext()
{
GUI_OmniRange = RTUtil.FormatSI(Omni, "m");
GUI_DishRange = RTUtil.FormatSI(Dish, "m");
GUI_EnergyReq = RTUtil.FormatConsumption(Consumption);
Events["EventTarget"].guiName = RTUtil.TargetName(Target);
}
private void HandleDynamicPressure()
{
if (vessel == null) return;
if (!vessel.HoldPhysics && vessel.atmDensity > 0 && MaxQ > 0 && mDeployFxModules.Any(a => a.GetScalar > 0.9f))
{
if (vessel.srf_velocity.sqrMagnitude * vessel.atmDensity / 2 > MaxQ)
{
MaxQ = -1.0f;
part.decouple(0.0f);
}
}
}
private List<IScalarModule> FindFxModules(int[] indices, bool showUI)
{
var modules = new List<IScalarModule>();
if (indices == null) return modules;
foreach (int i in indices)
{
var item = base.part.Modules[i] as IScalarModule;
if (item != null)
{
item.SetUIWrite(showUI);
item.SetUIRead(showUI);
modules.Add(item);
}
else
{
RTLog.Notify("ModuleRTAntenna: Part Module {0} doesn't implement IScalarModule", part.Modules[i].name);
}
}
return modules;
}
private IEnumerator SetFXModules_Coroutine(List<IScalarModule> modules, float tgtValue)
{
bool done = false;
while (!done)
{
done = true;
foreach (var module in modules)
{
if (Mathf.Abs(module.GetScalar - tgtValue) > 0.01f)
{
module.SetScalar(tgtValue);
done = false;
}
}
yield return true;
}
}
private void OnDestroy()
{
RTLog.Notify("ModuleRTAntenna: OnDestroy");
GameEvents.onVesselWasModified.Remove(OnVesselModified);
GameEvents.onPartUndock.Remove(OnPartUndock);
if (RTCore.Instance != null && mRegisteredId != Guid.Empty)
{
RTCore.Instance.Antennas.Unregister(mRegisteredId, this);
mRegisteredId = Guid.Empty;
}
}
private void OnPartUndock(Part p)
{
if (p.vessel == vessel)
{
OnVesselModified(p.vessel);
}
}
private void OnVesselModified(Vessel v)
{
if ((mRegisteredId != vessel.id))
{
RTCore.Instance.Antennas.Unregister(mRegisteredId, this);
mRegisteredId = vessel.id;
RTCore.Instance.Antennas.Register(vessel.id, this);
}
}
public int CompareTo(IAntenna antenna)
{
return Consumption.CompareTo(antenna.Consumption);
}
public override string ToString()
{
return String.Format("ModuleRTAntenna(Name: {0}, Guid: {1}, Dish: {2}, Omni: {3}, Target: {4}, Radians: {5})", Name, mRegisteredId, Dish, Omni, Target, Radians);
}
}
}