/
MSTSLocomotive.cs
6240 lines (5618 loc) · 299 KB
/
MSTSLocomotive.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// COPYRIGHT 2009, 2010, 2011, 2012, 2013 by the Open Rails project.
//
// This file is part of Open Rails.
//
// Open Rails is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Open Rails is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Open Rails. If not, see <http://www.gnu.org/licenses/>.
/* LOCOMOTIVE CLASSES
*
* Used as a base for Steam, Diesel and Electric locomotive classes.
*
* A locomotive is represented by two classes:
* MSTSLocomotive - defines the behaviour, ie physics, motion, power generated etc
* MSTSLocomotiveViewer - defines the appearance in a 3D viewer including animation for wipers etc
*
* Both these classes derive from corresponding classes for a basic TrainCar
* TrainCar - provides for movement, rolling friction, etc
* TrainCarViewer - provides basic animation for running gear, wipers, etc
*
* Locomotives can either be controlled by a player,
* or controlled by the train's MU signals for brake and throttle etc.
* The player controlled loco generates the MU signals which pass along to every
* unit in the train.
* For AI trains, the AI software directly generates the MU signals - there is no
* player controlled train.
*
* The end result of the physics calculations for the the locomotive is
* a TractiveForce and a FrictionForce ( generated by the TrainCar class )
*
*/
//#define ALLOW_ORTS_SPECIFIC_ENG_PARAMETERS
// Debug for Advanced Adhesion Model
// #define DEBUG_ADHESION
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Orts.Common;
using Orts.Formats.Msts;
using Orts.MultiPlayer;
using Orts.Parsers.Msts;
using Orts.Simulation.Physics;
using Orts.Simulation.RollingStocks.SubSystems;
using Orts.Simulation.RollingStocks.SubSystems.Brakes;
using Orts.Simulation.RollingStocks.SubSystems.Brakes.MSTS;
using Orts.Simulation.RollingStocks.SubSystems.Controllers;
using Orts.Simulation.RollingStocks.SubSystems.PowerSupplies;
using Orts.Simulation.RollingStocks.SubSystems.PowerTransmissions;
using ORTS.Common;
using ORTS.Scripting.Api;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Event = Orts.Common.Event;
namespace Orts.Simulation.RollingStocks
{
///////////////////////////////////////////////////
/// SIMULATION BEHAVIOUR
///////////////////////////////////////////////////
public enum CabViewType
{
Front = 0,
Rear = 1,
Void = 2
}
/// <summary>
/// Adds Throttle, Direction, Horn, Sander and Wiper control
/// to the basic TrainCar.
/// Use as a base for Electric, Diesel or Steam locomotives.
/// </summary>
public partial class MSTSLocomotive : MSTSWagon
{
public enum CombinedControl
{
None,
ThrottleDynamic,
ThrottleAir,
ThrottleDynamicAir,
DynamicAir,
}
public enum SoundState
{
Stopped,
Sound,
ContinuousSound
}
// simulation parameters
public bool ManualHorn = false;
public bool TCSHorn = false;
public bool Horn = false;
protected bool PreviousHorn = false;
protected float HornTimerS = 30.0f;
protected float? HornStartTime;
public bool HornRecent { get; private set; }
public bool ManualBell = false;
public SoundState BellState = SoundState.Stopped;
public bool Bell = false;
protected bool PreviousBell = false;
protected float BellTimerS;
protected float? BellStartTime;
public bool BellRecent { get; private set; }
public bool VacuumExhausterPressed = false;
public bool FastVacuumExhausterFitted = false;
public bool AlerterSnd;
public bool VigilanceMonitor;
public bool Sander;
public bool Wiper;
public bool BailOff;
public bool DynamicBrake;
public float MaxPowerW;
public float MaxForceN;
public float AbsTractionSpeedMpS;
public float MaxCurrentA = 0;
public float MaxSpeedMpS = 1e3f;
public float UnloadingSpeedMpS;
public float MainResPressurePSI = 130;
public float BrakePipeFlowM3pS;
public float MaximumMainReservoirPipePressurePSI;
public bool CompressorIsOn;
public bool CompressorIsMechanical = false;
public float AverageForceN;
public float PowerOnDelayS;
public bool CabLightOn;
public bool ShowCab = true;
public bool MilepostUnitsMetric;
public int DPUnitID;
public float DrvWheelWeightKg; // current weight on locomotive drive wheels, includes drag factor (changes as mass changes)
public float InitialDrvWheelWeightKg; // initialising weight on locomotive drive wheels, includes drag factor
public bool CabRadioOn;
public bool OnLineCabRadio;
public string OnLineCabRadioURL;
public float ZeroSpeedAdhesionBase;
public float FilteredBrakePipeFlowM3pS;
public IIRFilter AFMFilter;
// Water trough filling
public bool HasWaterScoop = false; // indicates whether loco + tender have a water scoop or not
public float ScoopMaxPickupSpeedMpS = 200.0f; // Maximum scoop pickup speed - used in steam locomotive viewer
public bool ScoopIsBroken = false; // becomes broken if activated where there is no trough
public bool RefillingFromTrough = false; // refilling from through is ongoing
public float WaterScoopFillElevationM; // height water has to be raised to fill tender
public float WaterScoopDepthM; // depth that water scoop goes into trough (pan)
public float WaterScoopWidthM; // width of water scoop
public float WaterScoopVelocityMpS; // Velocity of water entering water scoop
public float WaterScoopDragForceN; // drag force due to scoop being in water trough
public float WaterScoopedQuantityLpS; // Amount of water scooped up by water scoop per second
public float WaterScoopInputAmountL; // Water scooped in elapsed time
public float WaterScoopMinSpeedMpS; // Minimum speed for water pickup
public bool IsWaterScoopDown = false;
public bool WaterScoopDown;
public const float GravitationalAccelerationFtpSpS = 32.26f;
public float TenderWaterLevelFraction;
public float WaterScoopTotalWaterL;
bool WaterScoopOverTroughFlag = false;
bool WaterScoopNotFittedFlag = false;
bool WaterScoopSlowSpeedFlag = false;
bool WaterScoopDirectionFlag = false;
public bool IsWaterScoopPlayerLocomotive = false;
bool WaterScoopSoundOn = false;
public float MaxTotalCombinedWaterVolumeUKG;
public MSTSNotchController WaterController = new MSTSNotchController(0, 1, 0.01f);
public float CombinedTenderWaterVolumeUKG // Decreased by running injectors and increased by refilling
{
get { return WaterController.CurrentValue * MaxTotalCombinedWaterVolumeUKG; }
set { WaterController.CurrentValue = value / MaxTotalCombinedWaterVolumeUKG; }
}
public float CurrentLocomotiveSteamHeatBoilerWaterCapacityL
{
get {
if (IsSteamHeatFitted)
{
return WaterController.CurrentValue * MaximumSteamHeatBoilerWaterTankCapacityL;
}
else
{
return 0;
}
}
set { WaterController.CurrentValue = value / MaximumSteamHeatBoilerWaterTankCapacityL; }
}
public float IsTenderRequired = 1.0f; // Flag indicates that a tender is required for operation of the locomotive. Typically tank locomotives do not require a tender. Assume by default that tender is required.
public float BoilerPressurePSI; // Steam Gauge pressure - what the engineer sees.
public float MaxBoilerPressurePSI = 180f; // maximum boiler pressure, safety valve setting
public float SandingSteamUsageLBpS; // Sanding Steam Usage
// Vacuum Reservoir and Exhauster Settings
// Steam heating Flags
public bool IsSteamInitial = true; // To initialise steam heat
public bool IsSteamHeatFirstTime = true; // Flag for first pass at steam heating.
public bool IsSteamHeatFitted = false; // Is steam heating fitted to locomotive
public float CurrentSteamHeatPressurePSI = 0.0f; // Current pressure in steam heat system
public string LocomotiveName; // Name of locomotive from ENG file
// Carriage Steam Heating Parameters
public float MaxSteamHeatPressurePSI; // Maximum Steam heating pressure
public Interpolator SteamHeatPressureToTemperaturePSItoF;
public Interpolator SteamDensityPSItoLBpFT3; // saturated steam density given pressure
public Interpolator SteamHeatPSItoBTUpLB; // total heat in saturated steam given pressure
public bool IsSteamHeatingBoilerFitted = false; // Flag to indicate when steam heat boiler van is fitted
public float CalculatedCarHeaterSteamUsageLBpS;
// Adhesion Debug
// Commented out as never used
//bool DebugSpeedReached;
//float DebugSpeedIncrement = 5.0f; // Speed increment for debug display - in mph
//float DebugSpeed = 5.0f; // Initialise at 5 mph
//float DebugTimer = 0.0f;
// Adhesion parameters
public enum SlipControlType
{
None,
Full
}
public SlipControlType SlipControlSystem;
float BaseFrictionCoefficientFactor; // Factor used to adjust Curtius formula depending upon weather conditions
float SlipFrictionCoefficientFactor;
public float SteamStaticWheelForce;
public float SteamTangentialWheelForce;
public float SteamDrvWheelWeightLbs; // Weight on each drive axle
public float PreviousThrottleSetting = 0.0f; // Holds the value of the previous throttle setting for calculating the correct antislip speed
float DebugTimer; // Used for debugging adhesion coefficient
bool DebugSpeedReached = false; // Used for debugging adhesion coefficient
float DebugSpeedIncrement = 1; // Used for debugging adhesion coefficient
float DebugSpeed = 1; // Used for debugging adhesion coefficient
// parameters for Track Sander based upon compressor air and abrasive table for 1/2" sand blasting nozzle @ 50psi
public float MaxTrackSandBoxCapacityM3; // Capacity of sandbox
public float MaxTrackSanderAirComsumptionForwardM3pS;
public float MaxTrackSanderAirComsumptionReverseM3pS = 0;
public float MaxTrackSanderSandConsumptionForwardM3pS;
public float CurrentTrackSanderAirConsumptionM3pS;
public float CurrentTrackSanderSandConsumptionM3pS;
public float CurrentTrackSandBoxCapacityM3;
public float MaxTrackSanderSandConsumptionReverseM3pS = 0;
public float SandWeightKgpM3 = 1600; // One cubic metre of sand weighs about 1.54-1.78 tonnes.
public float MaxTrackSanderSteamConsumptionForwardLbpS;
public float MaxTrackSanderSteamConsumptionReverseLbpS = 0;
// Vacuum Braking parameters
readonly static float OneAtmospherePSI = Bar.ToPSI(1);
public bool SmallSteamEjectorIsOn = false;
public bool LargeSteamEjectorIsOn = false;
public bool VacuumPumpOperating = false;
public float SteamEjectorSmallPressurePSI = 0.0f;
public float SteamEjectorLargePressurePSI = 0.0f;
public bool VacuumPumpFitted;
public bool SmallEjectorControllerFitted = false;
public float VacuumPumpResistanceN;
public float EjectorSmallSteamConsumptionLbpS;
public float EjectorLargeSteamConsumptionLbpS;
public float SteamEjectorSmallSetting = 0.0f;
public float SteamEjectorLargeSetting = 0.0f;
public float MaxVaccuumMaxPressurePSI = 110.0f; // Value for the boiler pressure when maximum vacuum will be produced for the steam ejector
public float SmallEjectorFeedFraction = 0.35f;
public float LargeEjectorFeedFraction = 1.0f;
public bool LargeEjectorControllerFitted = false;
public float VacuumPumpChargingRateInHgpS = 0.0f;
public bool VacuumBrakeEQFitted = false; // Flag to indicate that equalising resevoir fitted to vacuum brakes
public float HUDNetBPLossGainPSI;
public float SmallEjectorBrakePipeChargingRatePSIorInHgpS;
public float LargeEjectorBrakePipeChargingRatePSIorInHgpS;
public float ExhausterHighSBPChargingRatePSIorInHgpS; // Rate for Exhauster in high speed mode
public float ExhausterLowSBPChargingRatePSIorInHgpS; // Rate for Exhauster in high speed mode
public bool VacuumBrakeCutoffActivated = false;
public bool BrakeFlagDecrease = false;
public bool BrakeFlagIncrease = false;
private bool _SmallEjectorSoundOn = false;
public bool SmallEjectorSoundOn
{
get => _SmallEjectorSoundOn;
set
{
if (value != _SmallEjectorSoundOn)
{
SignalEvent(value? Event.SmallEjectorOn : Event.SmallEjectorOff);
_SmallEjectorSoundOn = value;
}
}
}
private bool _LargeEjectorSoundOn = false;
public bool LargeEjectorSoundOn
{
get => _LargeEjectorSoundOn;
set
{
if (value != _LargeEjectorSoundOn)
{
SignalEvent(value? Event.LargeEjectorOn : Event.LargeEjectorOff);
_LargeEjectorSoundOn = value;
}
}
}
public bool DriveWheelOnlyBrakes = false;
public bool SteamEngineBrakeFitted = false;
public bool TrainBrakeFitted = false;
public bool EngineBrakeFitted = false;
public bool BrakemanBrakeFitted = false;
public bool VacuumExhausterIsOn = false;
public float VacuumBrakesMainResVolumeM3 = Me3.FromFt3(200.0f); // Main vacuum reservoir volume
public float VacuumBrakesMainResMaxVacuumPSIAorInHg = Vac.ToPress(23);
public float VacuumBrakesExhausterRestartVacuumPSIAorInHg = Vac.ToPress(21);
public float VacuumBrakesMainResChargingRatePSIAorInHgpS = Bar.ToPSI(Bar.FromInHg(0.2f));
public float VacuumMainResVacuumPSIAorInHg = Vac.ToPress(23); // Vacuum currently in Main Reservoir
// Set values for display in HUD
public float WagonCoefficientFrictionHUD;
public float LocomotiveCoefficientFrictionHUD;
public float HuDGearMaximumTractiveForce;
public PressureUnit MainPressureUnit = PressureUnit.None;
public Dictionary<BrakeSystemComponent, PressureUnit> BrakeSystemPressureUnits = new Dictionary<BrakeSystemComponent, PressureUnit>
{
{ BrakeSystemComponent.MainReservoir, PressureUnit.None },
{ BrakeSystemComponent.EqualizingReservoir, PressureUnit.None },
{ BrakeSystemComponent.AuxiliaryReservoir, PressureUnit.None },
{ BrakeSystemComponent.EmergencyReservoir, PressureUnit.None },
{ BrakeSystemComponent.MainPipe, PressureUnit.None },
{ BrakeSystemComponent.BrakePipe, PressureUnit.None },
{ BrakeSystemComponent.BrakeCylinder, PressureUnit.None }
};
protected float OdometerResetPositionM = 0;
protected bool OdometerCountingUp = true;
protected bool OdometerCountingForwards = true;
public bool OdometerResetButtonPressed = false;
public bool OdometerVisible { get; private set; }
public float OdometerM
{
get
{
if (Train == null)
return 0;
return OdometerCountingForwards ? Train.DistanceTravelledM - OdometerResetPositionM : OdometerResetPositionM - Train.DistanceTravelledM;
}
}
// ENG file data
public string CabSoundFileName;
public string CVFFileName;
public float MaxMainResPressurePSI;
public float MainResVolumeM3;
public float TrainBrakePipeLeakPSIorInHgpS = 0.0f; // Air leakage from train brake pipe - should normally be no more then 5psi/min - default off
public float CompressorRestartPressurePSI = 110;
public float CompressorChargingRateM3pS = 0.075f;
public bool CompressorIsMUControlled = false;
public float MainResChargingRatePSIpS = 0.4f;
public float EngineBrakeReleaseRatePSIpS = 12.5f;
public float EngineBrakeApplyRatePSIpS = 12.5f;
public float BrakePipeTimeFactorS = 0.0015f;
public float BrakePipeDischargeTimeFactor;
public float BrakeServiceTimeFactorPSIpS;
public float BrakeEmergencyTimeFactorPSIpS;
public float BrakePipeChargingRatePSIorInHgpS;
public float BrakePipeQuickChargingRatePSIpS;
public InterpolatorDiesel2D TractiveForceCurves;
public InterpolatorDiesel2D DynamicBrakeForceCurves;
public float DynamicBrakeSpeed1MpS = MpS.FromKpH(5);
public float DynamicBrakeSpeed2MpS = MpS.FromKpH(30);
public float DynamicBrakeSpeed3MpS = MpS.FromKpH(999);
public float DynamicBrakeSpeed4MpS = MpS.FromKpH(999);
public float DynamicBrakeRatioAtSpeed4 = 0;
public float MaxDynamicBrakeForceN;
public float DynamicBrakeMaxCurrentA;
public float DynamicBrakeDelayS;
public bool DynamicBrakeAutoBailOff;
public bool DynamicBrakePartialBailOff;
public bool UsingRearCab;
public bool BrakeOverchargeSoundOn = false;
protected bool DynamicBrakeBlendingEnabled; // dynamic brake blending is configured
public bool DynamicBrakeAvailable; // dynamic brake is available
AirSinglePipe airPipeSystem;
public double? DynamicBrakeCommandStartTime;
protected bool DynamicBrakeBlendingOverride; // true when DB lever >0% should always override the blending. When false, the bigger command is applied.
protected bool DynamicBrakeBlendingForceMatch = true; // if true, dynamic brake blending tries to achieve the same braking force as the airbrake would have.
protected bool DynamicBrakeControllerSetupLock; // if true if dynamic brake lever will lock until dynamic brake is available
public float DynamicBrakeBlendingPercent { get; protected set; } = -1;
public CombinedControl CombinedControlType;
public float CombinedControlSplitPosition;
public bool HasSmoothStruc;
bool controlTrailerBrakeSystemSet = false;
public float MaxContinuousForceN;
public float SpeedOfMaxContinuousForceMpS; // Speed where maximum tractive effort occurs
public float MSTSSpeedOfMaxContinuousForceMpS; // Speed where maximum tractive effort occurs - MSTS parameter if used
public float ContinuousForceTimeFactor = 1800;
public bool AntiSlip;
public bool AdvancedAdhesionModel = false; // flag set depending upon adhesion model used.
public float SanderSpeedEffectUpToMpS;
public float SanderSpeedOfMpS = 30.0f;
public string EngineOperatingProcedures;
public bool EmergencyButtonPressed { get; set; }
public bool EmergencyCausesPowerDown { get; private set; }
public bool EmergencyCausesThrottleDown { get; private set; }
public bool EmergencyEngagesHorn { get; private set; }
public bool WheelslipCausesThrottleDown { get; private set; }
public float BrakeRestoresPowerAtBrakePipePressurePSI;
public float BrakeCutsPowerAtBrakePipePressurePSI;
public bool DoesVacuumBrakeCutPower { get; private set; }
public bool DoesBrakeCutPower { get; private set; }
public float BrakeCutsPowerAtBrakeCylinderPressurePSI { get; private set; }
public bool DoesHornTriggerBell { get; private set; }
public bool DPSyncTrainApplication { get; private set; }
public bool DPSyncTrainRelease { get; private set; }
public bool DPSyncEmergency { get; private set; }
public bool DPSyncIndependent { get; private set; } = true;
protected const float DefaultCompressorRestartToMaxSysPressureDiff = 35; // Used to check if difference between these two .eng parameters is correct, and to correct it
protected const float DefaultMaxMainResToCompressorRestartPressureDiff = 10; // Used to check if difference between these two .eng parameters is correct, and to correct it
protected const float DefaultMaxCompressorRestartPressure = 135; // Max value to be inserted if .eng parameters are corrected
protected const float DefaultMainResVolume = 0.78f; // Value to be inserted if .eng parameters are corrected
protected const float DefaultMaxMainResPressure = 140; // Max value to be inserted if .eng parameters are corrected
public List<CabView> CabViewList = new List<CabView>();
public CabView3D CabView3D;
public MSTSNotchController SteamHeatController = new MSTSNotchController(0, 1, 0.1f);
public MSTSNotchController ThrottleController;
public ScriptedBrakeController TrainBrakeController;
public ScriptedBrakeController EngineBrakeController;
public ScriptedBrakeController BrakemanBrakeController;
public AirSinglePipe.ValveState EngineBrakeState = AirSinglePipe.ValveState.Lap;
public MSTSNotchController DynamicBrakeController;
public MSTSNotchController GearBoxController;
public MSTSNotchController DPThrottleController;
public MSTSNotchController DPDynamicBrakeController;
private int PreviousGearBoxNotch;
private int previousChangedGearBoxNotch;
public float EngineBrakeIntervention = -1;
public float TrainBrakeIntervention = -1;
public float ThrottleIntervention = -1;
public float DynamicBrakeIntervention = -1;
public enum TractionMotorTypes
{
DC,
AC,
}
public TractionMotorTypes TractionMotorType = TractionMotorTypes.DC;
public List<ElectricMotor> TractionMotors = new List<ElectricMotor>();
public ILocomotivePowerSupply LocomotivePowerSupply => PowerSupply as ILocomotivePowerSupply;
public ScriptedTrainControlSystem TrainControlSystem;
public IIRFilter CurrentFilter;
public IIRFilter AdhesionFilter;
public float SaveAdhesionFilter;
public float AdhesionConditions;
public float FilteredMotiveForceN;
public double CommandStartTime;
public double LastBrakeSoundTime = 0;
public float PowerReduction = 0;
// Cruise Control
public CruiseControl CruiseControl;
// public MultiPositionController MultiPositionController;
public List<MultiPositionController> MultiPositionControllers;
public MSTSLocomotive(Simulator simulator, string wagPath)
: base(simulator, wagPath)
{
// BrakePipeChargingRatePSIpS = Simulator.Settings.BrakePipeChargingRate;
MilepostUnitsMetric = Simulator.TRK.Tr_RouteFile.MilepostUnitsMetric;
BrakeCutsPowerAtBrakeCylinderPressurePSI = 4.0f;
LocomotiveAxles.Add(new Axle());
CurrentFilter = new IIRFilter(IIRFilter.FilterTypes.Butterworth, 1, IIRFilter.HzToRad(0.5f), 0.001f);
AdhesionFilter = new IIRFilter(IIRFilter.FilterTypes.Butterworth, 1, IIRFilter.HzToRad(1f), 0.001f);
AFMFilter = new IIRFilter(IIRFilter.FilterTypes.Butterworth, 1, IIRFilter.HzToRad(0.1f), 1.0f);
TrainBrakeController = new ScriptedBrakeController(this);
EngineBrakeController = new ScriptedBrakeController(this);
BrakemanBrakeController = new ScriptedBrakeController(this);
MultiPositionControllers = new List<MultiPositionController>();
ThrottleController = new MSTSNotchController();
DynamicBrakeController = new MSTSNotchController();
TrainControlSystem = new ScriptedTrainControlSystem(this);
}
/// <summary>
/// This initializer is called when we haven't loaded this type of car before
/// and must read it new from the wag file.
/// </summary>
public override void LoadFromWagFile(string wagFilePath)
{
base.LoadFromWagFile(wagFilePath);
// Assumes that CabViewList[0] is the front cab
// and that CabViewList[1] is the rear cab, if present.
// Could be extended to more than 2 cabs.
if (CVFFileName != null)
{
var cabView = BuildCabView(WagFilePath, CVFFileName);
if (cabView != null)
{
CabViewList.Add(cabView);
var reverseCVFFileName = Path.Combine(
Path.GetDirectoryName(CVFFileName), // Some CVF paths begin with "..\..\", so Path.GetDirectoryName() is needed.
Path.GetFileNameWithoutExtension(CVFFileName) + "_rv.cvf"
);
{
cabView = BuildCabView(WagFilePath, reverseCVFFileName);
if (cabView != null)
CabViewList.Add(cabView);
}
// practically never happens, but never say never
if (CabViewList.Count == 2 && CabViewList[1].CabViewType == CabViewType.Front && CabViewList[0].CabViewType == CabViewType.Rear)
{
cabView = CabViewList[1];
CabViewList.Insert(0, cabView);
CabViewList.RemoveAt(2);
}
// only one cabview, and it looks rear; insert a void one at first place to maintain fast indexing
else if (CabViewList.Count == 1 && CabViewList[0].CabViewType == CabViewType.Rear)
{
UsingRearCab = true;
CabViewList.Add(CabViewList[0]);
CabViewList[0].CabViewType = CabViewType.Void;
}
}
CabView3D = BuildCab3DView();
if (CabViewList.Count == 0 & CabView3D == null)
Trace.TraceWarning("{0} locomotive's CabView references non-existent {1}", wagFilePath, CVFFileName);
}
DrvWheelWeightKg = InitialDrvWheelWeightKg;
// If DrvWheelWeight is not in ENG file, then set drivewheel weight the same as locomotive mass
if (DrvWheelWeightKg == 0) // if DrvWheelWeightKg not in ENG file.
{
DrvWheelWeightKg = MassKG; // set Drive wheel weight to total wagon mass if not in ENG file
InitialDrvWheelWeightKg = MassKG; // // set Initial Drive wheel weight as well, as it is used as a reference
}
CorrectBrakingParams();
CheckCoherence();
GetPressureUnit();
IsDriveable = true;
MoveParamsToAxle();
}
protected void CheckCoherence()
{
if (!TrainBrakeController.IsValid())
TrainBrakeController = new ScriptedBrakeController(this); //create a blank one
if (!EngineBrakeController.IsValid())
EngineBrakeController = null;
if (!BrakemanBrakeController.IsValid())
BrakemanBrakeController = null;
if (ThrottleController == null)
{
//If no controller so far, we create a default one
ThrottleController = new MSTSNotchController();
ThrottleController.StepSize = 0.1f;
}
DPThrottleController = (MSTSNotchController)ThrottleController.Clone();
// need to test for Dynamic brake problem on 3DTS and SLI
if (DynamicBrakeController.IsValid())
{
if (DynamicBrakeController.NotchCount() <= 3)
{
HasSmoothStruc = true;
}
if (DynamicBrakeController.NotchCount() > 3)
DPDynamicBrakeController = (MSTSNotchController)DynamicBrakeController.Clone();
else
DPDynamicBrakeController = BuildDPDynamicBrakeController();
}
else
{
DynamicBrakeController = null;
DPDynamicBrakeController = null;
}
if (DynamicBrakeForceCurves == null && MaxDynamicBrakeForceN > 0)
{
DynamicBrakeForceCurves = new InterpolatorDiesel2D(2);
Interpolator interp = new Interpolator(2);
interp[0] = 0;
interp[100] = 0;
DynamicBrakeForceCurves[0] = interp;
interp = new Interpolator(7);
interp[0] = 0;
interp[DynamicBrakeSpeed1MpS] = 0;
interp[DynamicBrakeSpeed2MpS] = MaxDynamicBrakeForceN;
interp[DynamicBrakeSpeed3MpS] = MaxDynamicBrakeForceN;
interp[DynamicBrakeSpeed4MpS] = DynamicBrakeRatioAtSpeed4 * MaxDynamicBrakeForceN;
interp[DynamicBrakeSpeed4MpS + 0.5f] = 0;
interp[100] = 0;
DynamicBrakeForceCurves[1] = interp;
}
}
protected MSTSNotchController BuildDPDynamicBrakeController()
{
var dpDynController = new MSTSNotchController();
CabView cabView = null;
CVCMultiStateDisplay msDisplay = null;
if (CabView3D != null)
cabView = CabView3D;
else if (CabViewList.Count > 0)
{
if (CabViewList[0].CabViewType == CabViewType.Front)
cabView = CabViewList[0];
else
cabView = CabViewList[1];
}
if (cabView != null)
{
try
{
msDisplay = (CVCMultiStateDisplay) cabView.CVFFile.CabViewControls.Where(
control => control is CVCMultiStateDisplay &&
(((CVCMultiStateDisplay) control).ControlType.Type == CABViewControlTypes.DYNAMIC_BRAKE_DISPLAY ||
((CVCMultiStateDisplay) control).ControlType.Type == CABViewControlTypes.CPH_DISPLAY)).First();
}
catch
{
}
if (msDisplay != null)
{
if (msDisplay.ControlType.Type == CABViewControlTypes.DYNAMIC_BRAKE_DISPLAY)
{
foreach (var switchval in msDisplay.Values)
dpDynController.AddNotch((float) switchval);
}
else
{
foreach (var switchval in msDisplay.Values)
{
if (switchval<CombinedControlSplitPosition)
continue;
dpDynController.AddNotch((float)(switchval - CombinedControlSplitPosition) / (1 - CombinedControlSplitPosition));
}
}
}
}
if (cabView == null || msDisplay == null)
// Use default Dash9 arrangement if no display is found
{
var switchval = 0f;
while (switchval <= 1)
{
if (switchval == 0.99f)
switchval = 1;
dpDynController.AddNotch(switchval);
switchval += 0.11f;
}
}
return dpDynController;
}
protected void GetPressureUnit()
{
switch (Simulator.Settings.PressureUnit)
{
default:
case "Automatic":
if (CabViewList.Count > 0)
{
Dictionary<CABViewControlTypes, BrakeSystemComponent> brakeSystemComponents = new Dictionary<CABViewControlTypes, BrakeSystemComponent>
{
{ CABViewControlTypes.MAIN_RES, BrakeSystemComponent.MainReservoir },
{ CABViewControlTypes.EQ_RES, BrakeSystemComponent.EqualizingReservoir },
{ CABViewControlTypes.BRAKE_CYL, BrakeSystemComponent.BrakeCylinder },
{ CABViewControlTypes.BRAKE_PIPE, BrakeSystemComponent.BrakePipe }
};
Dictionary<CABViewControlUnits, PressureUnit> pressureUnits = new Dictionary<CABViewControlUnits, PressureUnit>
{
{ CABViewControlUnits.KILOPASCALS, PressureUnit.KPa },
{ CABViewControlUnits.BAR, PressureUnit.Bar },
{ CABViewControlUnits.PSI, PressureUnit.PSI },
{ CABViewControlUnits.INCHES_OF_MERCURY, PressureUnit.InHg },
{ CABViewControlUnits.KGS_PER_SQUARE_CM, PressureUnit.KgfpCm2 }
};
CabViewControls cvcList = CabViewList[0].CVFFile.CabViewControls;
foreach (CabViewControl cvc in cvcList)
{
if (brakeSystemComponents.TryGetValue(cvc.ControlType.Type, out var component) && pressureUnits.TryGetValue(cvc.Units, out var unit))
{
BrakeSystemPressureUnits[component] = unit;
}
}
}
// Manual rules :
BrakeSystemPressureUnits[BrakeSystemComponent.MainPipe] = BrakeSystemPressureUnits[BrakeSystemComponent.MainReservoir]; // Main Pipe is supplied by Main Reservoir
BrakeSystemPressureUnits[BrakeSystemComponent.AuxiliaryReservoir] = BrakeSystemPressureUnits[BrakeSystemComponent.BrakePipe]; // Auxiliary Reservoir is supplied by Brake Pipe (in single pipe brakes)
BrakeSystemPressureUnits[BrakeSystemComponent.EmergencyReservoir] = BrakeSystemPressureUnits[BrakeSystemComponent.BrakePipe]; // Emergency Reservoir is supplied by Brake Pipe
foreach (BrakeSystemComponent component in BrakeSystemPressureUnits.Keys.ToList())
{
if (BrakeSystemPressureUnits[component] == PressureUnit.None)
{
BrakeSystemPressureUnits[component] = (MilepostUnitsMetric ? PressureUnit.Bar : PressureUnit.PSI);
}
}
break;
case "bar":
foreach (BrakeSystemComponent component in BrakeSystemPressureUnits.Keys.ToList())
{
BrakeSystemPressureUnits[component] = PressureUnit.Bar;
}
break;
case "PSI":
foreach (BrakeSystemComponent component in BrakeSystemPressureUnits.Keys.ToList())
{
BrakeSystemPressureUnits[component] = PressureUnit.PSI;
}
break;
case "inHg":
foreach (BrakeSystemComponent component in BrakeSystemPressureUnits.Keys.ToList())
{
BrakeSystemPressureUnits[component] = PressureUnit.InHg;
}
break;
case "kgf/cm^2":
foreach (BrakeSystemComponent component in BrakeSystemPressureUnits.Keys.ToList())
{
BrakeSystemPressureUnits[component] = PressureUnit.KgfpCm2;
}
break;
}
// The main pressure unit is the one that is the most present in the brake system
MainPressureUnit = BrakeSystemPressureUnits.Values.ToList()
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.First().Key;
}
protected CabView BuildCabView(string wagFilePath, string cvfFileName)
{
var viewPointList = new List<ViewPoint>();
var extendedCVF = new ExtendedCVF();
bool noseAhead = false;
var cvfBasePath = Path.Combine(Path.GetDirectoryName(wagFilePath), "CABVIEW");
var cvfFilePath = Path.Combine(cvfBasePath, cvfFileName);
if (!File.Exists(cvfFilePath))
return null;
var cvfFile = new CabViewFile(cvfFilePath, cvfBasePath);
var viewPoint = new ViewPoint();
if (cvfFile.Locations.Count <= 0) return null; //check for Protrain's dummy cab
// Set up camera locations for the cab views
for (int i = 0; i < cvfFile.Locations.Count; ++i)
{
if (i >= cvfFile.Locations.Count || i >= cvfFile.Directions.Count)
{
Trace.TraceWarning("Skipped cab view camera {1} missing Position and Direction in {0}", cvfFilePath, i);
break;
}
viewPoint = new ViewPoint();
viewPoint.Location = cvfFile.Locations[i];
viewPoint.StartDirection = cvfFile.Directions[i];
viewPoint.RotationLimit = new Vector3(0, 0, 0); // cab views have a fixed head position
viewPointList.Add(viewPoint);
}
var cabViewType = new CabViewType();
cabViewType = ((viewPointList[0].StartDirection.Y >= 90 && viewPointList[0].StartDirection.Y <= 270)
|| (viewPointList[0].StartDirection.Y <= -90 && viewPointList[0].StartDirection.Y >= -270)) ? CabViewType.Rear : CabViewType.Front;
var wag = this as MSTSWagon;
var wagFolderSlash = Path.GetDirectoryName(wag.WagFilePath) + @"\";
string shapeFilePath;
bool boundingLimitsFound = false;
ShapeDescriptorFile shapeFile = new ShapeDescriptorFile();
if (wag.FreightShapeFileName != null)
{
shapeFilePath = wagFolderSlash + wag.FreightShapeFileName;
if (shapeFilePath != null && File.Exists(shapeFilePath + "d"))
{
shapeFile = new ShapeDescriptorFile(shapeFilePath + "d");
if (shapeFile.shape.ESD_Bounding_Box != null) boundingLimitsFound = true;
}
}
if (!boundingLimitsFound)
{
shapeFilePath = wagFolderSlash + wag.MainShapeFileName;
if (shapeFilePath != null && File.Exists(shapeFilePath + "d"))
{
shapeFile = new ShapeDescriptorFile(shapeFilePath + "d");
if (shapeFile.shape.ESD_Bounding_Box != null) boundingLimitsFound = true;
}
}
if (boundingLimitsFound)
{
if (cabViewType == CabViewType.Front)
noseAhead = (viewPointList[0].Location.Z + 0.5f < shapeFile.shape.ESD_Bounding_Box.Max.Z) ? true : false;
else if (cabViewType == CabViewType.Rear)
noseAhead = (viewPointList[0].Location.Z - 0.5f > shapeFile.shape.ESD_Bounding_Box.Min.Z) ? true : false;
}
if (!(this is MSTSSteamLocomotive))
{
InitializeFromORTSSpecific(cvfFilePath, extendedCVF);
}
return new CabView(cvfFile, viewPointList, extendedCVF, cabViewType, noseAhead);
}
protected CabView3D BuildCab3DView()
{
if (Cab3DShapeFileName == null)
return null;
var extendedCVF = new ExtendedCVF();
bool noseAhead = false;
var cab3dBasePath = Path.Combine(Path.GetDirectoryName(WagFilePath), "CABVIEW3D");
var shapeFilePath = Path.Combine(cab3dBasePath, Cab3DShapeFileName);
if (!File.Exists(shapeFilePath))
return null;
var cvfBasePath = cab3dBasePath;
var cvfFilePath = Path.Combine(cvfBasePath, Path.ChangeExtension(Cab3DShapeFileName, "cvf"));
if (!File.Exists(cvfFilePath))
{
cvfFilePath = Path.Combine(cvfBasePath, CVFFileName);
if (!File.Exists(cvfFilePath))
{
cvfBasePath = Path.Combine(Path.GetDirectoryName(WagFilePath), "CABVIEW");
cvfFilePath = Path.Combine(cvfBasePath, CVFFileName);
if (!File.Exists(cvfFilePath))
return null;
}
}
var cvfFile = new CabViewFile(cvfFilePath, cvfBasePath);
if (!(this is MSTSSteamLocomotive))
InitializeFromORTSSpecific(cvfFilePath, extendedCVF);
var cabViewAngle = CabViewpoints[0].StartDirection.Y;
var cabViewType = (cabViewAngle >= 90 && cabViewAngle <= 270) || (cabViewAngle <= -90 && cabViewAngle >= -270) ? CabViewType.Rear : CabViewType.Front;
// only one cabview, and it looks rear; insert a void one at first place to maintain fast indexing
if (CabViewpoints.Count == 1 && cabViewType == CabViewType.Rear)
CabViewpoints.Insert(0, new PassengerViewPoint());
return new CabView3D(cvfFile, CabViewpoints, extendedCVF, cabViewType, noseAhead, shapeFilePath);
}
/// <summary>
/// Parse the wag file parameters required for the simulator and viewer classes
/// </summary>
public override void Parse(string lowercasetoken, STFReader stf)
{
switch (lowercasetoken)
{
case "engine(sound": CabSoundFileName = stf.ReadStringBlock(null); break;
case "engine(cabview": CVFFileName = stf.ReadStringBlock(null); break;
case "engine(maxpower": MaxPowerW = stf.ReadFloatBlock(STFReader.UNITS.Power, null); break;
case "engine(maxforce": MaxForceN = stf.ReadFloatBlock(STFReader.UNITS.Force, null); break;
case "engine(maxcurrent": MaxCurrentA = stf.ReadFloatBlock(STFReader.UNITS.Current, null); break;
case "engine(maxcontinuousforce": MaxContinuousForceN = stf.ReadFloatBlock(STFReader.UNITS.Force, null); break;
case "engine(ortsspeedofmaxcontinuousforce": SpeedOfMaxContinuousForceMpS = stf.ReadFloatBlock(STFReader.UNITS.Speed, null); break;
case "engine(dieselenginespeedofmaxtractiveeffort": MSTSSpeedOfMaxContinuousForceMpS = stf.ReadFloatBlock(STFReader.UNITS.Speed, null); break;
case "engine(maxvelocity": MaxSpeedMpS = stf.ReadFloatBlock(STFReader.UNITS.Speed, null); break;
case "engine(ortsunloadingspeed": UnloadingSpeedMpS = stf.ReadFloatBlock(STFReader.UNITS.Speed, null); break;
case "engine(ortsslipcontrolsystem":
stf.MustMatch("(");
string slipControlType = stf.ReadString().ToLowerInvariant();
try
{
SlipControlSystem = (SlipControlType)Enum.Parse(typeof(SlipControlType), slipControlType.First().ToString().ToUpper() + slipControlType.Substring(1));
}
catch
{
STFException.TraceWarning(stf, "Skipped unknown slip control system " + slipControlType);
}
break;
case "engine(type":
stf.MustMatch("(");
var engineType = stf.ReadString();
try
{
EngineType = (EngineTypes)Enum.Parse(typeof(EngineTypes), engineType.First().ToString().ToUpper() + engineType.Substring(1));
}
catch
{
STFException.TraceWarning(stf, "Skipped unknown engine type " + engineType);
}
break;
case "engine(sandingsystemtype":
stf.MustMatch("(");
var sandingType = stf.ReadString();
try
{
SandingSystemType = (SandingSystemTypes)Enum.Parse(typeof(SandingSystemTypes), sandingType.First().ToString().ToUpper() + sandingType.Substring(1));
}
catch
{
STFException.TraceWarning(stf, "Skipped unknown engine type " + sandingType);
}
break;
case "engine(ortstractionmotortype":
stf.MustMatch("(");
string tractionMotorType = stf.ReadString().ToUpper();
try
{
TractionMotorType = (TractionMotorTypes)Enum.Parse(typeof(TractionMotorTypes), tractionMotorType);
}
catch
{
STFException.TraceWarning(stf, "Skipped unknown traction motor type " + tractionMotorType);
}
break;
case "engine(enginecontrollers(throttle": ThrottleController = new MSTSNotchController(stf); break;
case "engine(enginecontrollers(regulator": ThrottleController = new MSTSNotchController(stf); break;
case "engine(enginecontrollers(brake_dynamic": DynamicBrakeController.Parse(stf); break;
case "engine(ortslocomotivedrivewheelonlybraking":
var wheelbraking = stf.ReadIntBlock(null);
if (wheelbraking == 1)
{
DriveWheelOnlyBrakes = true;
}
break;
case "engine(trainbrakescontrollermaxsystempressure":
case "engine(ortstrainbrakescontrollermaxoverchargepressure":
case "engine(trainbrakescontrollermaxreleaserate":
case "engine(trainbrakescontrollermaxquickreleaserate":
case "engine(ortstrainbrakescontrolleroverchargeeliminationrate":
case "engine(trainbrakescontrollermaxapplicationrate":
case "engine(trainbrakescontrolleremergencyapplicationrate":
case "engine(trainbrakescontrollerfullservicepressuredrop":
case "engine(trainbrakescontrollerminpressurereduction":
case "engine(ortstrainbrakescontrollerslowapplicationrate":
case "engine(ortstrainbrakecontroller":
case "engine(enginecontrollers(brake_train":
case "engine(ortstraindynamicblendingtable":
TrainBrakeController.Parse(lowercasetoken, stf);
TrainBrakeFitted = true;