Updated simulation logic.
[VesselSimulator.git] / KerbalEngineer / Simulation.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
// Kerbal Engineer Redux
// Author:  CYBUTEK
// License: Attribution-NonCommercial-ShareAlike 3.0 Unported
//
// This class has taken a lot of inspiration from r4m0n's MuMech FuelFlowSimulator.  Although extremely
// similar to the code used within MechJeb, it is a clean re-write.  The similarities are a testiment
// to how well the MuMech code works and the robustness of the simulation algorithem used.
 
using System;
using System.Collections.Generic;
 
using UnityEngine;
 
namespace KerbalEngineer.Simulation
{
    public class Simulation
    {
        private List<Part> partList;
 
        private List<PartSim> allParts;
        private List<PartSim> allFuelLines;
        private HashSet<PartSim> drainingParts;
        private List<EngineSim> allEngines;
        private List<EngineSim> activeEngines;
        private HashSet<int> drainingResources;
 
        private int lastStage = 0;
        private int currentStage = 0;
 
        private double gravity = 0;
        private double atmosphere = 0;
#if LOG || TIMERS
        private Stopwatch _timer = new Stopwatch();
#endif
        private const double STD_GRAVITY = 9.81d;
        private const double SECONDS_PER_DAY = 86400;
        
        public Simulation()
        {
#if LOG
            MonoBehaviour.print("Simulation created");
#endif
        }
 
        // This function prepares the simulation by creating all the necessary data structures it will 
        // need during the simulation.  All required data is copied from the core game data structures 
        // so that the simulation itself can be run in a background thread without having issues with 
        // the core game changing the data while the simulation is running.
        public bool PrepareSimulation(List<Part> parts, double theGravity, double theAtmosphere = 0)
        {
#if LOG
            MonoBehaviour.print("PrepareSimulation started");
#endif
#if LOG || TIMERS
            _timer.Start();
#endif
            // Store the parameters in members for ease of access in other functions
            this.partList = parts;
            this.gravity = theGravity;
            this.atmosphere = theAtmosphere;
            this.lastStage = Staging.lastStage;
            //MonoBehaviour.print("lastStage = " + lastStage);
 
            // Create the lists for our simulation parts
            this.allParts = new List<PartSim>();
            this.allFuelLines = new List<PartSim>();
            this.drainingParts = new HashSet<PartSim>();
            this.allEngines = new List<EngineSim>();
            this.activeEngines = new List<EngineSim>();
            this.drainingResources = new HashSet<int>();
 
            // A dictionary for fast lookup of Part->PartSim during the preparation phase
            Dictionary<Part, PartSim> partSimLookup = new Dictionary<Part, PartSim>();
 
            // First we create a PartSim for each Part (giving each a unique id)
            int partId = 1;
            foreach (Part part in this.partList)
            {
                // If the part is already in the lookup dictionary then log it and skip to the next part
                if (partSimLookup.ContainsKey(part))
                {
                    MonoBehaviour.print("Part " + part.name + " appears in vessel list more than once");
                    continue;
                }
 
                // Create the PartSim
                PartSim partSim = new PartSim(part, partId, this.atmosphere);
 
                // Add it to the Part lookup dictionary and the necessary lists
                partSimLookup.Add(part, partSim);
                this.allParts.Add(partSim);
                if (partSim.isFuelLine)
                    this.allFuelLines.Add(partSim);
                if (partSim.isEngine)
                    partSim.CreateEngineSims(this.allEngines, this.atmosphere);
 
                partId++;
            }
 
            // Now that all the PartSims have been created we can do any set up that needs access to other parts
            //MonoBehaviour.print("SetupAttachNodes and count stages");
            foreach (PartSim partSim in this.allParts)
            {
                partSim.SetupAttachNodes(partSimLookup);
                if (partSim.decoupledInStage >= this.lastStage)
                    this.lastStage = partSim.decoupledInStage + 1;
            }
 
            // And finally release the Part references from all the PartSims
            //MonoBehaviour.print("ReleaseParts");
            foreach (PartSim partSim in this.allParts)
                partSim.ReleasePart();
 
            // And dereference the core's part list
            this.partList = null;
 
#if LOG || TIMERS
            _timer.Stop();
            MonoBehaviour.print("PrepareSimulation: " + _timer.ElapsedMilliseconds + "ms");
#endif
#if LOG
            Dump();
#endif
            return true;
        }
 
        
        // This function runs the simulation and returns a newly created array of Stage objects
        public Stage[] RunSimulation()
        {
#if LOG
            MonoBehaviour.print("RunSimulation started");
#endif
#if LOG || TIMERS
            _timer.Start();
#endif
            // Start with the last stage to simulate
            // (this is in a member variable so it can be accessed by AllowedToStage and ActiveStage)
            this.currentStage = this.lastStage;
 
            // Create the array of stages that will be returned
            Stage[] stages = new Stage[this.currentStage + 1];
 
            // Loop through the stages
            while (this.currentStage >= 0)
            {
#if LOG
                MonoBehaviour.print("Simulating stage " + currentStage);
                MonoBehaviour.print("ShipMass = " + ShipMass);
                _timer.Reset();
                _timer.Start();
#endif
                // Update active engines and resource drains
                this.UpdateResourceDrains();
 
                // Create the Stage object for this stage
                Stage stage = new Stage();
 
                double stageTime = 0d;
                double stageDeltaV = 0d;            
                double totalStageThrust = 0d;
                double totalStageActualThrust = 0d;
 
                double totalStageFlowRate = 0d;
                double totalStageIspFlowRate = 0d;
                double currentisp = 0;
                double stageStartMass = this.ShipMass;
                double stepStartMass = stageStartMass;
                double stepEndMass = 0;
 
                // Loop through all the active engines totalling the thrust, actual thrust and mass flow rates
                foreach (EngineSim engine in this.activeEngines)
                {
                    totalStageActualThrust += engine.actualThrust;
                    totalStageThrust += engine.thrust;
 
                    totalStageFlowRate += engine.ResourceConsumptions.Mass;
                    totalStageIspFlowRate += engine.ResourceConsumptions.Mass * engine.isp;
                }
 
                // Calculate the effective isp at this point
                if (totalStageFlowRate > 0d && totalStageIspFlowRate > 0d)
                    currentisp = totalStageIspFlowRate / totalStageFlowRate;
                else
                    currentisp = 0;
 
                // Store various things in the Stage object
                stage.thrust = totalStageThrust;
                //MonoBehaviour.print("stage.thrust = " + stage.thrust);
                stage.thrustToWeight = totalStageThrust / (stageStartMass * this.gravity);
                stage.maxThrustToWeight = stage.thrustToWeight;
                //MonoBehaviour.print("StageMass = " + stageStartMass);
                //MonoBehaviour.print("Initial maxTWR = " + stage.maxThrustToWeight);
                stage.actualThrust = totalStageActualThrust;
                stage.actualThrustToWeight = totalStageActualThrust / (stageStartMass * this.gravity);
 
                // Calculate the cost and mass of this stage
                foreach (PartSim partSim in this.allParts)
                {
                    if (partSim.decoupledInStage == this.currentStage - 1)
                    {
                        stage.cost += partSim.cost;
                        stage.mass += partSim.GetStartMass();
                    }
                }
#if LOG
                MonoBehaviour.print("Stage setup took " + _timer.ElapsedMilliseconds + "ms");
#endif
                // Now we will loop until we are allowed to stage
                int loopCounter = 0;
                while (!this.AllowedToStage())
                {
                    loopCounter++;
                    //MonoBehaviour.print("loop = " + loopCounter);
 
                    // Calculate how long each draining tank will take to drain and run for the minimum time
                    double resourceDrainTime = double.MaxValue;
                    PartSim partMinDrain = null;
                    foreach (PartSim partSim in this.drainingParts)
                    {
                        double time = partSim.TimeToDrainResource();
                        if (time < resourceDrainTime)
                        {
                            resourceDrainTime = time;
                            partMinDrain = partSim;
                        }
                    }
#if LOG
                    MonoBehaviour.print("Drain time = " + resourceDrainTime + " (" + partMinDrain.name + ":" + partMinDrain.partId + ")");
#endif
                    foreach (PartSim partSim in this.drainingParts)
                        partSim.DrainResources(resourceDrainTime);
 
                    // Get the mass after draining
                    stepEndMass = this.ShipMass;
                    stageTime += resourceDrainTime;
 
                    double stepEndTWR = totalStageThrust / (stepEndMass * this.gravity);
                    //MonoBehaviour.print("After drain mass = " + stepEndMass);
                    //MonoBehaviour.print("currentThrust = " + totalStageThrust);
                    //MonoBehaviour.print("currentTWR = " + stepEndTWR);
                    if (stepEndTWR > stage.maxThrustToWeight)
                        stage.maxThrustToWeight = stepEndTWR;
 
                    //MonoBehaviour.print("newMaxTWR = " + stage.maxThrustToWeight);
 
                    // If we have drained anything and the masses make sense then add this step's deltaV to the stage total
                    if (resourceDrainTime > 0d && stepStartMass > stepEndMass && stepStartMass > 0d && stepEndMass > 0d)
                        stageDeltaV += (currentisp * STD_GRAVITY) * Math.Log(stepStartMass / stepEndMass);
 
                    // Update the active engines and resource drains for the next step
                    this.UpdateResourceDrains();
 
                    // Recalculate the current thrust and isp for the next step
                    totalStageThrust = 0d;
                    totalStageActualThrust = 0d;
                    totalStageFlowRate = 0d;
                    totalStageIspFlowRate = 0d;
                    foreach (EngineSim engine in this.activeEngines)
                    {
                        totalStageActualThrust += engine.actualThrust;
                        totalStageThrust += engine.thrust;
 
                        totalStageFlowRate += engine.ResourceConsumptions.Mass;
                        totalStageIspFlowRate += engine.ResourceConsumptions.Mass * engine.isp;
                    }
 
                    //MonoBehaviour.print("next step thrust = " + totalStageThrust);
 
                    if (totalStageFlowRate > 0d && totalStageIspFlowRate > 0d)
                        currentisp = totalStageIspFlowRate / totalStageFlowRate;
                    else
                        currentisp = 0;
 
                    // Check if we actually changed anything
                    if (stepStartMass == stepEndMass)
                    {
                        MonoBehaviour.print("No change in mass");
                        break;
                    }
 
                    // Check to stop rampant looping
                    if (loopCounter == 1000)
                    {
                        MonoBehaviour.print("exceeded loop count");
                        MonoBehaviour.print("stageStartMass = " + stageStartMass);
                        MonoBehaviour.print("stepStartMass = " + stepStartMass);
                        MonoBehaviour.print("StepEndMass   = " + stepEndMass);
                        break;
                    }
 
                    // The next step starts at the mass this one ended at
                    stepStartMass = stepEndMass;
                }
 
                // Store more values in the Stage object and stick it in the array
                // Recalculate effective stage isp from the stageDeltaV (flip the standard deltaV calculation around)
                // Note: If the mass doesn't change then this is a divide by zero
                if (stageStartMass != stepStartMass)
                    stage.isp = stageDeltaV / (STD_GRAVITY * Math.Log(stageStartMass / stepStartMass));
                else
                    stage.isp = 0;
                stage.deltaV = stageDeltaV;
                // Zero stage time if more than a day (this should be moved into the window code)
                stage.time = (stageTime < SECONDS_PER_DAY) ? stageTime : 0d;
                stage.number = this.currentStage;
                stages[this.currentStage] = stage;
 
                // Now activate the next stage
                this.currentStage--;
#if LOG
                // Log how long the stage took
                _timer.Stop();
                MonoBehaviour.print("Simulating stage took " + _timer.ElapsedMilliseconds + "ms");
                stage.Dump();
                _timer.Reset();
                _timer.Start();
#endif
                // Activate the next stage
                this.ActivateStage();
#if LOG
                // Log home long it took to activate
                _timer.Stop();
                MonoBehaviour.print("ActivateStage took " + _timer.ElapsedMilliseconds + "ms");
#endif
            }
 
            // Now we add up the various total fields in the stages
            for (int i = 0; i < stages.Length; i++)
            {
                // For each stage we total up the cost, mass, deltaV and time for this stage and all the stages above
                for (int j = i; j >= 0; j--)
                {
                    stages[i].totalCost += stages[j].cost;
                    stages[i].totalMass += stages[j].mass;
                    stages[i].totalDeltaV += stages[j].deltaV;
                    stages[i].totalTime += stages[j].time;
                }
                // We also total up the deltaV for stage and all stages below
                for (int j = i; j < stages.Length; j++)
                {
                    stages[i].inverseTotalDeltaV += stages[j].deltaV;
                }
 
                // Zero the total time if the value will be huge (24 hours?) to avoid the display going weird
                // (this should be moved into the window code)
                if (stages[i].totalTime > SECONDS_PER_DAY)
                    stages[i].totalTime = 0d;
            }
#if LOG || TIMERS
            _timer.Stop();
            MonoBehaviour.print("RunSimulation: " + _timer.ElapsedMilliseconds + "ms");
#endif
            return stages;
        }
 
 
        // This function does all the hard work of working out which engines are burning, which tanks are being drained 
        // and setting the drain rates
        private void UpdateResourceDrains()
        {
            // Empty the active engines list and the draining resources set
            this.activeEngines.Clear();
            this.drainingResources.Clear();
 
            // Reset the resource drains of all draining parts
            foreach (PartSim partSim in this.drainingParts)
                partSim.ResourceDrains.Reset();
 
            // Empty the draining parts set
            this.drainingParts.Clear();
 
            // Loop through all the engine modules in the ship
            foreach (EngineSim engine in this.allEngines)
            {
                // If the engine is active in the current stage
                if (engine.partSim.inverseStage >= this.currentStage)
                {
                    // Set the resource drains for this engine and add it to the active list if it is active
                    if (engine.SetResourceDrains(this.allParts, this.allFuelLines, this.drainingParts))
                    {
                        this.activeEngines.Add(engine);
                        foreach (int type in engine.ResourceConsumptions.Types)
                            this.drainingResources.Add(type);
                    }
                }
            }
#if LOG
            StringBuilder buffer = new StringBuilder(1024);
            buffer.AppendFormat("Active engines = {0:d}\n", activeEngines.Count);
            int i = 0;
            foreach (EngineSim engine in activeEngines)
                engine.DumpEngineToBuffer(buffer, "Engine " + (i++) + ":");
            MonoBehaviour.print(buffer);
#endif
        }
 
        // This function works out if it is time to stage
        private bool AllowedToStage()
        {
#if LOG
            StringBuilder buffer = new StringBuilder(1024);
            buffer.AppendLine("AllowedToStage");
            buffer.AppendFormat("currentStage = {0:d}\n", currentStage);
#endif
            if (this.activeEngines.Count == 0)
            {
#if LOG
                buffer.AppendLine("No active engines => true");
                MonoBehaviour.print(buffer);
#endif
                return true;
            }
 
            foreach (PartSim partSim in this.allParts)
            {
                //partSim.DumpPartToBuffer(buffer, "Testing: ", allParts);
                //buffer.AppendFormat("isSepratron = {0}\n", partSim.isSepratron ? "true" : "false");
                if (partSim.decoupledInStage == (this.currentStage - 1) && (!partSim.isSepratron || partSim.decoupledInStage < partSim.inverseStage))
                {
                    if (!partSim.Resources.EmptyOf(this.drainingResources))
                    {
#if LOG
                        partSim.DumpPartToBuffer(buffer, "Decoupled part not empty => false: ");
                        MonoBehaviour.print(buffer);
#endif
                        return false;
                    }
                    foreach (EngineSim engine in this.activeEngines)
                    {
                        if (engine.partSim == partSim)
                        {
#if LOG
                            partSim.DumpPartToBuffer(buffer, "Decoupled part is active engine => false: ");
                            MonoBehaviour.print(buffer);
#endif
                            return false;
                        }
                    }
                }
            }
 
            if (this.currentStage > 0)
            {
#if LOG
                buffer.AppendLine("Current stage > 0 => true");
                MonoBehaviour.print(buffer);
#endif
                return true;
            }
 
#if LOG
            buffer.AppendLine("Returning false");
            MonoBehaviour.print(buffer);
#endif
            return false;
        }
 
        // This function activates the next stage
        // currentStage must be updated before calling this function
        private void ActivateStage()
        {
            // Build a set of all the parts that will be decoupled
            HashSet<PartSim> decoupledParts = new HashSet<PartSim>();
            foreach (PartSim partSim in this.allParts)
            {
                if (partSim.decoupledInStage >= this.currentStage)
                    decoupledParts.Add(partSim);
            }
 
            foreach (PartSim partSim in decoupledParts)
            {
                // Remove it from the all parts list
                this.allParts.Remove(partSim);
                if (partSim.isEngine)
                {
                    // If it is an engine then loop through all the engine modules and remove all the ones from this engine part
                    for (int i = this.allEngines.Count - 1; i >= 0; i--)
                    {
                        if (this.allEngines[i].partSim == partSim)
                            this.allEngines.RemoveAt(i);
                    }
                }
                // If it is a fuel line then remove it from the list of all fuel lines
                if (partSim.isFuelLine)
                    this.allFuelLines.Remove(partSim);
            }
 
            // Loop through all the (remaining) parts
            foreach (PartSim partSim in this.allParts)
            {
                // Ask the part to remove all the parts that are decoupled
                partSim.RemoveAttachedParts(decoupledParts);
            }
        }
 
        private double ShipStartMass
        {
            get
            {
                double mass = 0d;
 
                foreach (PartSim partSim in this.allParts)
                {
                    mass += partSim.GetStartMass();
                }
 
                return mass;
            }
        }
 
        private double ShipMass
        {
            get
            {
                double mass = 0d;
 
                foreach (PartSim partSim in this.allParts)
                {
                    mass += partSim.GetMass();
                }
 
                return mass;
            }
        }
#if LOG
        public void Dump()
        {
            StringBuilder buffer = new StringBuilder(1024);
            buffer.AppendFormat("Part count = {0:d}\n", allParts.Count);
 
            // Output a nice tree view of the rocket
            if (allParts.Count > 0)
            {
                PartSim root = allParts[0];
                while (root.parent != null)
                    root = root.parent;
 
                root.DumpPartToBuffer(buffer, "", allParts);
            }
 
            MonoBehaviour.print(buffer);
        }
#endif
    }
}