-
Notifications
You must be signed in to change notification settings - Fork 79
/
TankContentSwitcher.cs
372 lines (321 loc) · 14.3 KB
/
TankContentSwitcher.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
using KSPAPIExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace ProceduralParts
{
/// <summary>
/// Module that allows switching the contents of a part between different resources.
/// The possible contents are set up in the config file, and the user may switch beween
/// the different possiblities.
///
/// This is a bit of a light-weight version of RealFuels.
///
/// One can set this module up on any existing fuel part (Maybe with module manager if you like)
/// if you set the volume property in the config file.
///
/// The class also accepts the message ChangeVolume(float volume) if attached to a dynamic resizing part
/// such as ProceeduralTanks.
/// </summary>
public class TankContentSwitcher : PartModule, IPartMassModifier, ICostMultiplier
{
private static readonly string ModTag = "[ProceduralParts.TankContentSwitcher]";
#region IPartMassModifier implementation
public float GetModuleMass(float defaultMass, ModifierStagingSituation sit) => mass - defaultMass;
public ModifierChangeWhen GetModuleMassChangeWhen() => ModifierChangeWhen.FIXED;
#endregion
#region Unity Callbacks
public override void OnLoad(ConfigNode node)
{
if (HighLogic.LoadedScene == GameScenes.LOADING)
{
foreach (ConfigNode optNode in node.GetNodes("TANK_TYPE_OPTION"))
{
TankTypeOption option = new TankTypeOption();
option.Load(optNode);
tankTypeOptions.Add(option.name, option);
}
if (string.IsNullOrEmpty(tankType) || !tankTypeOptions.Keys.Contains(tankType))
tankType = tankTypeOptions.Keys.First();
}
bool useV = false;
if (node.TryGetValue("useVolume", ref useV) && useV)
tankVolumeName = PartVolumes.Tankage.ToString();
}
public override void OnStart(StartState state)
{
InitializeTankType();
if (HighLogic.LoadedSceneIsEditor)
{
Fields[nameof(volumeDisplay)].guiActiveEditor = !string.IsNullOrEmpty(tankVolumeName);
Fields[nameof(massDisplay)].guiActiveEditor = !string.IsNullOrEmpty(tankVolumeName);
Fields[nameof(tankType)].guiActiveEditor = tankTypeOptions.Count > 1;
// Don't listen for OnPartVolumeChanged until we have started.
Events[nameof(OnPartVolumeChanged)].active = true;
UI_ChooseOption options = Fields[nameof(tankType)].uiControlEditor as UI_ChooseOption;
options.options = tankTypeOptions.Keys.ToArray();
options.onFieldChanged += OnTankTypeChangedWithSymmetry;
}
tankVolume = PPart?.CurrentShape ? PPart.CurrentShape.Volume : 0;
volumeDisplay = tankVolume.ToStringSI(4, 3, "L");
}
public override void OnStartFinished(StartState state)
{
base.OnStartFinished(state);
if (HighLogic.LoadedSceneIsEditor)
this.OnTankTypeChanged(Fields[nameof(tankType)], null);
else
{
UpdateTankMass();
UpdateMassDisplay();
}
// Done here and done in OnStart in PP to get ordering right
// since these get fired in reverse-add order
if (HighLogic.LoadedSceneIsEditor)
GameEvents.onEditorShipModified.Add(OnShipModified);
}
protected void OnDestroy()
{
GameEvents.onEditorShipModified.Remove(OnShipModified);
}
#endregion
#region Fields Definitions
/// <summary>
/// Volume of part in kilolitres.
/// </summary>
[KSPField(isPersistant = true)]
public float tankVolume;
[KSPField(guiActiveEditor = true, guiName = "Mass", groupName = "TCS", groupDisplayName = "TankContentSwitcher")]
public string massDisplay;
[KSPField(guiActiveEditor = true, guiName = "Volume", groupName = "TCS")]
public string volumeDisplay;
[KSPField(isPersistant = true)]
public float mass;
[KSPField]
public string tankVolumeName;
[KSPField(isPersistant = true, guiActiveEditor = true, guiName = "Tank Type", groupName = "TCS"), UI_ChooseOption(scene = UI_Scene.Editor)]
public string tankType;
private TankTypeOption SelectedTankType => tankTypeOptions.ContainsKey(tankType) ? tankTypeOptions[tankType] : null;
public float GetCurrentCostMult() => SelectedTankType is TankTypeOption ? SelectedTankType.costMultiplier : 0;
private readonly Dictionary<string, TankTypeOption> tankTypeOptions = new Dictionary<string, TankTypeOption>();
#endregion
#region Tank Type
[Serializable]
public class TankTypeOption : IConfigNode
{
[Persistent]
public string name;
[Persistent]
public float dryDensity;
[Persistent]
public float massConstant;
[Persistent]
public bool isStructural = false;
[Persistent]
public float costMultiplier = 1.0f;
[Persistent]
public string techRequired;
public List<TankResource> resources;
public void Load(ConfigNode node)
{
ConfigNode.LoadObjectFromConfig(this, node);
resources = new List<TankResource>();
foreach (ConfigNode resNode in node.GetNodes("RESOURCE"))
{
TankResource resource = new TankResource();
resource.Load(resNode);
resources.Add(resource);
}
resources.Sort();
}
public void Save(ConfigNode node)
{
ConfigNode.CreateConfigFromObject(this, node);
foreach (TankResource resource in resources)
{
ConfigNode resNode = new ConfigNode("RESOURCE");
resource.Save(resNode);
node.AddNode(resNode);
}
}
public bool TechAvailable =>
!(HighLogic.CurrentGame.Mode == Game.Modes.CAREER || HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX) ||
string.IsNullOrEmpty(techRequired) ||
ResearchAndDevelopment.GetTechnologyState(techRequired) == RDTech.State.Available;
}
[Serializable]
public class TankResource : IConfigNode, IComparable<TankResource>
{
[Persistent]
public string name;
[Persistent]
public float unitsPerKL;
[Persistent]
public float unitsPerT;
[Persistent]
public float unitsConst;
[Persistent]
public bool isTweakable = true;
[Persistent]
public bool forceEmpty = false;
[Persistent]
public string flowMode = "Both";
public void Load(ConfigNode node)
{
ConfigNode.LoadObjectFromConfig(this, node);
}
public void Save(ConfigNode node)
{
ConfigNode.CreateConfigFromObject(this, node);
}
int IComparable<TankResource>.CompareTo(TankResource other)
{
return other == null ? 1 :
string.Compare(name, other.name, StringComparison.Ordinal);
}
}
private void InitializeTankType()
{
tankTypeOptions.Clear();
foreach (var kvp in part.partInfo.partPrefab.FindModuleImplementing<TankContentSwitcher>().tankTypeOptions)
{
if (kvp.Value.TechAvailable)
tankTypeOptions.Add(kvp.Key, kvp.Value);
}
if (tankTypeOptions == null || tankTypeOptions.Count == 0)
{
Debug.LogError("*TCS* No part type options available");
return;
}
if (string.IsNullOrEmpty(tankType) || !tankTypeOptions.Keys.Contains(tankType))
tankType = tankTypeOptions.Keys.First();
Fields[nameof(volumeDisplay)].guiActiveEditor = SelectedTankType.isStructural ? false : tankVolumeName != null;
}
#endregion
#region Updaters / Callbacks
/// <summary>
/// Message sent from ProceduralAbstractShape when it updates.
/// </summary>
[KSPEvent(guiActive = false, active = false)]
public void OnPartVolumeChanged(BaseEventDetails data)
{
string volumeName = data.Get<string>("volName");
double volume = data.Get<double>("newTotalVolume");
if (volumeName != tankVolumeName)
{
Debug.LogWarning($"{ModTag} OnPartVolumeChanged for {this}, volumeName {volumeName} vs tankVolumeName {tankVolumeName}");
return;
}
if (volume <= 0f)
throw new ArgumentOutOfRangeException("volume");
tankVolume = Convert.ToSingle(volume);
volumeDisplay = tankVolume.ToStringSI(4, 3, "L");
UpdateTankMass();
UpdateResourceAmounts();
UpdateMassDisplay();
if (HighLogic.LoadedSceneIsEditor)
GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
}
private void OnTankTypeChangedWithSymmetry(BaseField f, object obj)
{
OnTankTypeChanged(f, obj);
foreach (Part p in part.symmetryCounterparts)
p.FindModuleImplementing<TankContentSwitcher>()?.OnTankTypeChanged(f, obj);
MonoUtilities.RefreshPartContextWindow(part);
}
private void OnTankTypeChanged(BaseField f, object obj)
{
UpdateTankMass();
string s = obj as string;
if (!string.IsNullOrEmpty(s) && tankTypeOptions.ContainsKey(s) && tankTypeOptions[s] is TankTypeOption oldTTO)
{
foreach (TankResource tr in oldTTO.resources)
{
if (part.Resources.Get(tr.name) is PartResource pr)
{
part.RemoveResource(pr);
}
}
}
foreach (TankResource tr in SelectedTankType.resources)
{
double maxAmount = CalculateMaxResourceAmount(tr);
// On initialization, old TankTypeOptions is null but there is still a list of PartResources, so apply their value.
double amount = (part.Resources.Get(tr.name) is PartResource pr) ? pr.amount : maxAmount;
ConfigNode node = new ConfigNode("RESOURCE");
node.AddValue("name", tr.name);
node.AddValue("maxAmount", maxAmount);
node.AddValue("amount", amount);
node.AddValue("flowMode", tr.flowMode);
node.AddValue("isTweakable", tr.isTweakable);
part.SetResource(node);
}
Fields[nameof(volumeDisplay)].guiActiveEditor = SelectedTankType.isStructural ? false : tankVolumeName != null;
UpdateMassDisplay();
}
private void UpdateTankMass()
{
if (!string.IsNullOrEmpty(tankVolumeName))
{
mass = SelectedTankType.dryDensity * tankVolume + SelectedTankType.massConstant;
if (PPart != null)
{
mass *= PPart.CurrentShape.massMultiplier;
if (PPart.density > 0f)
mass *= PPart.density * (1f / ProceduralPart.NominalDensity);
}
}
}
private void UpdateMassDisplay()
{
if (!string.IsNullOrEmpty(tankVolumeName))
{
double resourceMass = part.Resources.Cast<PartResource>().Sum(r => r.maxAmount * r.info.density);
float totalMass = mass + Convert.ToSingle(resourceMass);
if (PPart != null)
totalMass += PPart.moduleMass;
massDisplay = (SelectedTankType.isStructural) ?
MathUtils.FormatMass(totalMass) :
$"Dry: {MathUtils.FormatMass(mass)} / Wet: {MathUtils.FormatMass(totalMass)}";
}
}
private void UpdateResourceAmounts()
{
foreach (TankResource tr in SelectedTankType.resources)
{
if (part.Resources.Get(tr.name) is PartResource pr)
{
double maxAmount = CalculateMaxResourceAmount(tr);
pr.amount = Math.Round(pr.amount * maxAmount / pr.maxAmount, 4);
pr.maxAmount = maxAmount;
pr.amount = Math.Min(pr.amount, maxAmount);
if (part.PartActionWindow?.ListItems.FirstOrDefault(x => (x as UIPartActionResourceEditor)?.Resource == pr) is UIPartActionResourceEditor pare)
{
pare.resourceMax.text = KSPUtil.LocalizeNumber(pr.maxAmount, "F1");
pare.UpdateItem();
pare.slider.onValueChanged.Invoke(pare.slider.value);
}
}
else
{
Debug.LogError($"{ModTag} UpdateResourceAmounts for {tr.name} found no matching PartResource!");
}
}
}
private double CalculateMaxResourceAmount(TankResource res)
{
double shapeMultiplier = (PPart is ProceduralPart && PPart.CurrentShape is ProceduralAbstractShape) ?
PPart.CurrentShape.resourceMultiplier : 0;
return Math.Round((res.unitsConst + (tankVolume * res.unitsPerKL) + (mass * res.unitsPerT)) * shapeMultiplier, 2);
}
#endregion
public ProceduralPart PPart => _pPart != null ? _pPart : (_pPart = GetComponent<ProceduralPart>());
private ProceduralPart _pPart;
private void OnShipModified(ShipConstruct _)
{
UpdateTankMass();
UpdateMassDisplay();
}
}
}