/
FuelFlowSimulation.cs
284 lines (229 loc) · 10.5 KB
/
FuelFlowSimulation.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
#nullable enable
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MechJebLib.Simulations.PartModules;
using MechJebLib.Utils;
namespace MechJebLib.Simulations
{
public class FuelFlowSimulation : BackgroundJob<bool>
{
private const int MAXSTEPS = 100;
public readonly List<FuelStats> Segments = new List<FuelStats>();
private FuelStats _currentSegment;
private double _time;
public bool DVLinearThrust = true; // include cos losses
private readonly HashSet<SimPart> _partsWithResourceDrains = new HashSet<SimPart>();
private bool _allocatedFirstSegment;
protected override bool Run(object? o)
{
var vessel = (SimVessel)o!;
_allocatedFirstSegment = false;
_time = 0;
Segments.Clear();
vessel.MainThrottle = 1.0;
vessel.ActivateEngines();
while (vessel.CurrentStage >= 0) // FIXME: should stop mutating vessel.CurrentStage
{
SimulateStage(vessel);
FinishSegment(vessel);
vessel.Stage();
}
Segments.Reverse();
_partsWithResourceDrains.Clear();
return true; // we pull results off the object not off the return value
}
private void SimulateStage(SimVessel vessel)
{
vessel.UpdateMass();
UpdateEngineStats(vessel);
UpdateActiveEngines(vessel);
UpdateResourceDrainsAndResiduals(vessel);
GetNextSegment(vessel);
double currentThrust = vessel.ThrustMagnitude;
for (int steps = MAXSTEPS; steps > 0; steps--)
{
if (AllowedToStage(vessel))
return;
double dt = MinimumTimeStep();
// FIXME: if we have constructed a segment which is > 0 dV, but less than 0.02s, and there's a
// prior > 0dV segment in the same kspStage we should add those together to reduce clutter.
if (Math.Abs(vessel.ThrustMagnitude - currentThrust) > 1e-12)
{
FinishSegment(vessel);
GetNextSegment(vessel);
currentThrust = vessel.ThrustMagnitude;
}
_time += dt;
ApplyResourceDrains(dt);
vessel.UpdateMass();
UpdateEngineStats(vessel);
UpdateActiveEngines(vessel);
UpdateResourceDrainsAndResiduals(vessel);
}
throw new Exception("FuelFlowSimulation hit max steps of " + MAXSTEPS + " steps");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void UpdateEngineStats(SimVessel vessel)
{
vessel.UpdateEngineStats();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyResourceDrains(double dt)
{
foreach (SimPart part in _partsWithResourceDrains)
part.ApplyResourceDrains(dt);
}
private void UpdateResourceDrainsAndResiduals(SimVessel vessel)
{
foreach (SimPart part in _partsWithResourceDrains)
part.ClearResourceDrains();
_partsWithResourceDrains.Clear();
for (int i = 0; i < vessel.ActiveEngines.Count; i++)
{
SimModuleEngines e = vessel.ActiveEngines[i];
foreach (int resourceId in e.PropellantFlowModes.Keys)
switch (e.PropellantFlowModes[resourceId])
{
case SimFlowMode.NO_FLOW:
UpdateResourceDrainsInPart(e.Part, e.ResourceConsumptions[resourceId], resourceId);
e.Part.UpdateResourceResidual(e.ModuleResiduals, resourceId);
break;
case SimFlowMode.ALL_VESSEL:
case SimFlowMode.ALL_VESSEL_BALANCE:
UpdateResourceDrainsInParts(vessel.PartsRemainingInStage[vessel.CurrentStage], e.ResourceConsumptions[resourceId],
resourceId, false);
UpdateResourceResidualsInParts(vessel.PartsRemainingInStage[vessel.CurrentStage], e.ModuleResiduals, resourceId);
break;
case SimFlowMode.STAGE_PRIORITY_FLOW:
case SimFlowMode.STAGE_PRIORITY_FLOW_BALANCE:
UpdateResourceDrainsInParts(vessel.PartsRemainingInStage[vessel.CurrentStage], e.ResourceConsumptions[resourceId],
resourceId, true);
UpdateResourceResidualsInParts(vessel.PartsRemainingInStage[vessel.CurrentStage], e.ModuleResiduals, resourceId);
break;
case SimFlowMode.STAGE_STACK_FLOW:
case SimFlowMode.STAGE_STACK_FLOW_BALANCE:
case SimFlowMode.STACK_PRIORITY_SEARCH:
UpdateResourceDrainsInParts(e.Part.CrossFeedPartSet, e.ResourceConsumptions[resourceId], resourceId, true);
UpdateResourceResidualsInParts(e.Part.CrossFeedPartSet, e.ModuleResiduals, resourceId);
break;
case SimFlowMode.NULL:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private readonly List<SimPart> _sources = new List<SimPart>();
private void UpdateResourceDrainsInParts(IList<SimPart> parts, double resourceConsumption, int resourceId, bool usePriority)
{
int maxPriority = int.MinValue;
_sources.Clear();
for (int i = 0; i < parts.Count; i++)
{
SimPart p = parts[i];
if (!p.TryGetResource(resourceId, out SimResource resource))
continue;
if (resource.Free)
continue;
if (resource.Amount <= p.Resources[resourceId].ResidualThreshold)
continue;
if (usePriority)
{
if (p.ResourcePriority < maxPriority)
continue;
if (p.ResourcePriority > maxPriority)
{
_sources.Clear();
maxPriority = p.ResourcePriority;
}
}
_sources.Add(p);
}
for (int i = 0; i < _sources.Count; i++)
UpdateResourceDrainsInPart(_sources[i], resourceConsumption / _sources.Count, resourceId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void UpdateResourceDrainsInPart(SimPart p, double resourceConsumption, int resourceId)
{
_partsWithResourceDrains.Add(p);
p.AddResourceDrain(resourceId, resourceConsumption);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void UpdateResourceResidualsInParts(IList<SimPart> parts, double residual, int resourceId)
{
for (int i = 0; i < parts.Count; i++)
parts[i].UpdateResourceResidual(residual, resourceId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double MinimumTimeStep()
{
double maxTime = ResourceMaxTime();
return maxTime < double.MaxValue && maxTime >= 0 ? maxTime : 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ResourceMaxTime()
{
double maxTime = double.MaxValue;
foreach (SimPart part in _partsWithResourceDrains)
maxTime = Math.Min(part.ResourceMaxTime(), maxTime);
return maxTime;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void UpdateActiveEngines(SimVessel vessel)
{
vessel.UpdateActiveEngines();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void FinishSegment(SimVessel vessel)
{
if (!_allocatedFirstSegment)
return;
_currentSegment.DeltaTime = _time - _currentSegment.StartTime;
_currentSegment.EndMass = vessel.Mass;
_currentSegment.ComputeStats();
Segments.Add(_currentSegment);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GetNextSegment(SimVessel vessel)
{
double stagedMass = 0;
if (_allocatedFirstSegment)
stagedMass = _currentSegment.EndMass - vessel.Mass;
else
_allocatedFirstSegment = true;
_currentSegment = new FuelStats
{
KSPStage = vessel.CurrentStage,
Thrust = DVLinearThrust ? vessel.ThrustMagnitude : vessel.ThrustNoCosLoss,
StartTime = _time,
StartMass = vessel.Mass,
SpoolUpTime = vessel.SpoolupCurrent,
StagedMass = stagedMass
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AllowedToStage(SimVessel vessel)
{
// always stage if all the engines are burned out
if (vessel.ActiveEngines.Count == 0)
return true;
for (int i = 0; i < vessel.ActiveEngines.Count; i++)
{
SimModuleEngines e = vessel.ActiveEngines[i];
if (e.Part.IsSepratron)
continue;
// never stage an active engine
if (e.Part.DecoupledInStage >= vessel.CurrentStage - 1)
return false;
// never drop fuel that could be used
if (e.WouldDropAccessibleFuelTank(vessel.CurrentStage - 1))
return false;
}
// do not trigger a stage that doesn't decouple anything -- until the engines burn out
if (vessel.PartsRemainingInStage[vessel.CurrentStage - 1].Count == vessel.PartsRemainingInStage[vessel.CurrentStage].Count)
return false;
return vessel.CurrentStage > 0;
}
}
}