-
Notifications
You must be signed in to change notification settings - Fork 81
/
TTTurntable.cs
2604 lines (2208 loc) · 122 KB
/
TTTurntable.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 2014 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/>.
// This code processes the Timetable definition and converts it into playable train information
//
// #define DEBUG_POOLINFO
// #define DEBUG_TURNTABLEINFO
//
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Orts.Simulation.AIs;
using Orts.Simulation.Physics;
using Orts.Simulation.RollingStocks;
using Orts.Simulation.Signalling;
using Orts.Parsers.OR;
using ORTS.Common;
namespace Orts.Simulation.Timetables
{
//================================================================================================//
//================================================================================================//
/// <summary>
/// Class TimetableTurntablePool
/// Class holding all details for turntables in timetable mode
/// Child of TimetablePool
/// </summary>
public class TimetableTurntablePool : TimetablePool
{
public struct AccessPathDetails
{
public Train.TCSubpathRoute AccessPath; // actual access path
public Traveller AccessTraveller; // traveler based on access path
public string AccessPathName; // access path name
public int TableVectorIndex; // index in VectorList of tracknode which is the table
public int TableExitIndex; // index in table exit list for this exit
public float TableApproachOffset; // offset of holding point in front of turntable (in Inward direction)
public float TableMiddleEntry; // offset of middle of table when approaching table
public float TableMiddleExit; // offset of middle of table when exiting
}
public struct TurntableDetails
{
public List<AccessPathDetails> AccessPaths; // access paths details defined for turntable location
public int TurntableIndex; // index for turntable in list of moving tables
public float TurntableApproachClearanceM; // required clearance from front of turntable on approach
public float TurntableReleaseClearanceM; // required clearance from front of turntabe for release
public float? TurntableSpeedMpS; // set speed for turntable access
public int? FrameRate; // frame rate for turntable movement
}
public TurntableDetails AdditionalTurntableDetails;
static float defaultTurntableApproachClearanceM = 10.0f; // default approach clearance
static float defaultTurntableReleaseClearanceM = 5.0f; // default release clearance
public Simulator Simulatorref { get; protected set; }
//================================================================================================//
/// <summary>
/// constructor for new TimetableTurntablePool
/// creates TimetableTurntablePool from files .turntable-or
/// </summary>
/// <param name="fileContents"></param>
/// <param name="lineindex"></param>
/// <param name="simulatorref"></param>
public TimetableTurntablePool(TimetableReader fileContents, ref int lineindex, Simulator simulatorref)
{
bool validpool = true;
bool newName = false;
bool firstName = false;
Turntable thisTurntable = null;
string Worldfile = string.Empty;
int UiD = -1;
Simulatorref = simulatorref;
ForceCreation = Simulatorref.Settings.TTCreateTrainOnPoolUnderflow;
AdditionalTurntableDetails.TurntableApproachClearanceM = defaultTurntableApproachClearanceM;
AdditionalTurntableDetails.TurntableReleaseClearanceM = defaultTurntableReleaseClearanceM;
AdditionalTurntableDetails.TurntableSpeedMpS = null;
AdditionalTurntableDetails.FrameRate = null;
// loop through definitions
while (lineindex < fileContents.Strings.Count && !newName)
{
string[] inputLine = fileContents.Strings[lineindex];
// switch through definitions
switch (inputLine[0].ToLower().Trim())
{
// comment : do not process
case "#comment":
lineindex++;
break;
// name : set as name
case "#name":
newName = firstName;
if (!firstName)
{
lineindex++;
firstName = true;
PoolName = String.Copy(inputLine[1].ToLower().Trim());
}
break;
// worldfile : read worldfile details
case "#worldfile":
if (String.IsNullOrEmpty(PoolName))
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : missing pool name \n");
validpool = false;
lineindex++;
}
else
{
Worldfile = String.Copy(inputLine[1].ToLower().Trim());
lineindex++;
}
break;
// UiD reference
case "#uid":
if (String.IsNullOrEmpty(PoolName))
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : missing pool name \n");
validpool = false;
lineindex++;
}
else
{
try
{
UiD = Convert.ToInt32(inputLine[1].Trim());
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for UiD \n");
}
lineindex++;
}
break;
// access path
case "#access":
if (String.IsNullOrEmpty(PoolName))
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : missing pool name \n");
validpool = false;
lineindex++;
}
else
{
string accessPath = inputLine[1].ToLower().Trim();
bool pathValid = true;
TimetableInfo TTInfo = new TimetableInfo(Simulatorref);
AIPath newPath = TTInfo.LoadPath(accessPath, out pathValid);
if (pathValid)
{
Train.TCRoutePath fullRoute = new Train.TCRoutePath(newPath, -2, 1, Simulatorref.Signals, -1, Simulatorref.Settings);
// if first element is end of track, remove it from path (path is defined outbound)
Train.TCSubpathRoute usedRoute = fullRoute.TCRouteSubpaths[0];
if (Simulatorref.Signals.TrackCircuitList[usedRoute.First().TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.EndOfTrack)
{
usedRoute.RemoveAt(0);
}
// if last element is send of track, remove it from path (if path has no junction it may be in reverse direction)
if (Simulatorref.Signals.TrackCircuitList[usedRoute.Last().TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.EndOfTrack)
{
usedRoute.RemoveAt(usedRoute.Count - 1);
}
// create path list if required
if (AdditionalTurntableDetails.AccessPaths == null)
{
AdditionalTurntableDetails.AccessPaths = new List<AccessPathDetails>();
}
AccessPathDetails thisAccess = new AccessPathDetails();
thisAccess.AccessPath = new Train.TCSubpathRoute(usedRoute);
thisAccess.AccessTraveller = new Traveller(Simulatorref.TSectionDat, Simulatorref.TDB.TrackDB.TrackNodes, newPath);
thisAccess.AccessPathName = String.Copy(accessPath);
AdditionalTurntableDetails.AccessPaths.Add(thisAccess);
}
else
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : access path not found : " + accessPath);
validpool = false;
}
lineindex++;
}
break;
// case approach clearance : read clearance value
case "#approachclearance":
try
{
AdditionalTurntableDetails.TurntableApproachClearanceM = Convert.ToSingle(inputLine[1].Trim());
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for approach clearance : " + inputLine[1].Trim());
}
lineindex++;
break;
// case release clearance : read clearance value
case "#releaseclearance":
try
{
AdditionalTurntableDetails.TurntableReleaseClearanceM = Convert.ToSingle(inputLine[1].Trim());
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for release clearance : " + inputLine[1].Trim());
}
lineindex++;
break;
// case turntable speed : read speed (either speedmph or speedkph)
case "#speedmph":
try
{
AdditionalTurntableDetails.TurntableSpeedMpS = MpS.FromMpH(Convert.ToSingle(inputLine[1].Trim()));
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for speed (mph) : " + inputLine[1].Trim());
}
lineindex++;
break;
case "#speedkph":
try
{
AdditionalTurntableDetails.TurntableSpeedMpS = MpS.FromKpH(Convert.ToSingle(inputLine[1].Trim()));
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for speed (kph) : " + inputLine[1].Trim());
}
lineindex++;
break;
// table frame rate
case "#framerate":
try
{
AdditionalTurntableDetails.FrameRate = Convert.ToInt32(inputLine[1].Trim());
}
catch
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : invalid value for frame rate : " + inputLine[1].Trim());
}
lineindex++;
break;
// storage : read path, add to path list
case "#storage":
if (String.IsNullOrEmpty(PoolName))
{
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : missing pool name \n");
validpool = false;
lineindex++;
}
else
{
bool validStorage = true;
PoolDetails thisPool = ExtractStorage(fileContents, Simulatorref, ref lineindex, out validStorage, false);
if (validStorage)
{
StoragePool.Add(thisPool);
}
else
{
validpool = false;
}
}
break;
default:
Trace.TraceInformation("Pool : " + fileContents.FilePath + " : line : " + (lineindex - 1) + " : unexpected line defitinion : " + inputLine[0] + "\n");
lineindex++;
break;
}
}
// find turntable reference
AdditionalTurntableDetails.TurntableIndex = FindTurntable(Worldfile, UiD);
if (AdditionalTurntableDetails.TurntableIndex < 0)
{
validpool = false;
Trace.TraceInformation("Pool : " + fileContents.FilePath + " not included due to errors in pool definition");
}
// check validity of access and storage paths
// paths must start at turntable
if (validpool)
{
thisTurntable = Simulatorref.MovingTables[AdditionalTurntableDetails.TurntableIndex] as Turntable;
// check validity for all access paths
for (int iPath = 0; iPath < AdditionalTurntableDetails.AccessPaths.Count; iPath++)
{
int vectorIndex = CheckTurntablePath(AdditionalTurntableDetails.AccessPaths[iPath].AccessPath, thisTurntable.TrackShapeIndex);
if (vectorIndex < 0)
{
Trace.TraceInformation("Pool : " + PoolName + " : access path " + AdditionalTurntableDetails.AccessPaths[iPath].AccessPathName + " does not link to turntable");
validpool = false;
}
else
{
AccessPathDetails thisPath = AdditionalTurntableDetails.AccessPaths[iPath];
thisPath.TableVectorIndex = vectorIndex;
AdditionalTurntableDetails.AccessPaths[iPath] = thisPath;
}
}
// check validity for all storage paths
for (int iPath = 0; iPath < StoragePool.Count; iPath++)
{
int vectorIndex = CheckTurntablePath(StoragePool[iPath].StoragePath, thisTurntable.TrackShapeIndex);
if (vectorIndex < 0)
{
Trace.TraceInformation("Pool : " + PoolName + " : storage path " + StoragePool[iPath].StorageName + " does not link to turntable");
validpool = false;
}
else
{
PoolDetails thisPool = StoragePool[iPath];
thisPool.TableVectorIndex = vectorIndex;
StoragePool[iPath] = thisPool;
}
}
}
// calculate offsets for paths
if (validpool)
{
// access path : hold offset, offset for start of turntable, offset for middle of turntable
for (int ipath = 0; ipath < AdditionalTurntableDetails.AccessPaths.Count; ipath++)
{
CalculateAccessOffsets(ipath, thisTurntable);
}
// storage path : actual length, offset for start of turntable, offset for middle of turntable
for (int ipath = 0; ipath < StoragePool.Count; ipath++)
{
CalculateStorageOffsets(ipath, thisTurntable);
}
}
// reset poolname if not valid
if (!validpool)
{
PoolName = String.Empty;
}
}
//================================================================================================//
/// <summary>
/// constructor for restore
/// </summary>
/// <param name="inf"></param>
/// <param name="simulatorref"></param>
public TimetableTurntablePool(BinaryReader inf, Simulator simulatorref)
{
Simulatorref = simulatorref;
PoolName = inf.ReadString();
ForceCreation = inf.ReadBoolean();
AdditionalTurntableDetails.AccessPaths = new List<AccessPathDetails>();
int noAccessPaths = inf.ReadInt32();
for (int iAccessPath = 0; iAccessPath < noAccessPaths; iAccessPath++)
{
AccessPathDetails thisAccess = new AccessPathDetails();
thisAccess.AccessPath = new Train.TCSubpathRoute(inf);
thisAccess.AccessTraveller = new Traveller(Simulatorref.TSectionDat, Simulatorref.TDB.TrackDB.TrackNodes, inf);
thisAccess.AccessPathName = inf.ReadString();
thisAccess.TableExitIndex = inf.ReadInt32();
thisAccess.TableVectorIndex = inf.ReadInt32();
thisAccess.TableApproachOffset = inf.ReadSingle();
thisAccess.TableMiddleEntry = inf.ReadSingle();
thisAccess.TableMiddleExit = inf.ReadSingle();
AdditionalTurntableDetails.AccessPaths.Add(thisAccess);
}
AdditionalTurntableDetails.TurntableIndex = inf.ReadInt32();
AdditionalTurntableDetails.TurntableApproachClearanceM = inf.ReadSingle();
AdditionalTurntableDetails.TurntableReleaseClearanceM = inf.ReadSingle();
AdditionalTurntableDetails.TurntableSpeedMpS = null;
if (inf.ReadBoolean())
{
AdditionalTurntableDetails.TurntableSpeedMpS = inf.ReadSingle();
}
AdditionalTurntableDetails.FrameRate = null;
if (inf.ReadBoolean())
{
AdditionalTurntableDetails.FrameRate = inf.ReadInt32();
}
int noPools = inf.ReadInt32();
for (int iPool = 0; iPool < noPools; iPool++)
{
int maxStorage = 0;
PoolDetails newPool = new PoolDetails();
newPool.StoragePath = new Train.TCSubpathRoute(inf);
newPool.StoragePathTraveller = new Traveller(Simulatorref.TSectionDat, Simulatorref.TDB.TrackDB.TrackNodes, inf);
newPool.StorageName = inf.ReadString();
newPool.AccessPaths = null;
newPool.StoredUnits = new List<int>();
int noStoredUnits = inf.ReadInt32();
for (int iUnits = 0; iUnits < noStoredUnits; iUnits++)
{
newPool.StoredUnits.Add(inf.ReadInt32());
}
newPool.ClaimUnits = new List<int>();
int noClaimUnits = inf.ReadInt32();
for (int iUnits = 0; iUnits < noClaimUnits; iUnits++)
{
newPool.ClaimUnits.Add(inf.ReadInt32());
}
newPool.StorageLength = inf.ReadSingle();
newPool.StorageCorrection = inf.ReadSingle();
newPool.TableExitIndex = inf.ReadInt32();
newPool.TableVectorIndex = inf.ReadInt32();
newPool.TableMiddleEntry = inf.ReadSingle();
newPool.TableMiddleExit = inf.ReadSingle();
newPool.RemLength = inf.ReadSingle();
maxStorage = inf.ReadInt32();
if (maxStorage <= 0)
{
newPool.maxStoredUnits = null;
}
else
{
newPool.maxStoredUnits = maxStorage;
}
StoragePool.Add(newPool);
}
}
//================================================================================================//
/// <summary>
/// Method to save pool
/// </summary>
/// <param name="outf"></param>
override public void Save(BinaryWriter outf)
{
outf.Write(PoolName);
outf.Write(ForceCreation);
// save access path information
outf.Write(AdditionalTurntableDetails.AccessPaths.Count);
foreach (AccessPathDetails thisPath in AdditionalTurntableDetails.AccessPaths)
{
thisPath.AccessPath.Save(outf);
thisPath.AccessTraveller.Save(outf);
outf.Write(thisPath.AccessPathName);
outf.Write(thisPath.TableExitIndex);
outf.Write(thisPath.TableVectorIndex);
outf.Write(thisPath.TableApproachOffset);
outf.Write(thisPath.TableMiddleEntry);
outf.Write(thisPath.TableMiddleExit);
}
outf.Write(AdditionalTurntableDetails.TurntableIndex);
outf.Write(AdditionalTurntableDetails.TurntableApproachClearanceM);
outf.Write(AdditionalTurntableDetails.TurntableReleaseClearanceM);
outf.Write(AdditionalTurntableDetails.TurntableSpeedMpS.HasValue);
if (AdditionalTurntableDetails.TurntableSpeedMpS.HasValue)
{
outf.Write(AdditionalTurntableDetails.TurntableSpeedMpS.Value);
}
outf.Write(AdditionalTurntableDetails.FrameRate.HasValue);
if (AdditionalTurntableDetails.FrameRate.HasValue)
{
outf.Write(AdditionalTurntableDetails.FrameRate.Value);
}
// save storage path information
outf.Write(StoragePool.Count);
foreach (PoolDetails thisStorage in StoragePool)
{
thisStorage.StoragePath.Save(outf);
thisStorage.StoragePathTraveller.Save(outf);
outf.Write(thisStorage.StorageName);
outf.Write(thisStorage.StoredUnits.Count);
foreach (int storedUnit in thisStorage.StoredUnits)
{
outf.Write(storedUnit);
}
outf.Write(thisStorage.ClaimUnits.Count);
foreach (int claimUnit in thisStorage.ClaimUnits)
{
outf.Write(claimUnit);
}
outf.Write(thisStorage.StorageLength);
outf.Write(thisStorage.StorageCorrection);
outf.Write(thisStorage.TableExitIndex);
outf.Write(thisStorage.TableVectorIndex);
outf.Write(thisStorage.TableMiddleEntry);
outf.Write(thisStorage.TableMiddleExit);
outf.Write(thisStorage.RemLength);
if (thisStorage.maxStoredUnits.HasValue)
{
outf.Write(thisStorage.maxStoredUnits.Value);
}
else
{
outf.Write(-1);
}
}
}
//================================================================================================//
/// <summary>
/// Check if path starts at turntable
/// </summary>
private int CheckTurntablePath(Train.TCSubpathRoute thisPath, int turntableTrackShape)
{
// check if turntable track section is in path - must be in first element (path must start at turntable end)
int vectorIndex = -1;
TrackCircuitSection thisSection = Simulatorref.Signals.TrackCircuitList[thisPath[0].TCSectionIndex];
Formats.Msts.TrackNode thisTDBsection = Simulatorref.Signals.trackDB.TrackNodes[thisSection.OriginalIndex];
for (int iVector = 0; iVector < thisTDBsection.TrVectorNode.TrVectorSections.Length; iVector++)
{
Formats.Msts.TrVectorSection thisVector = thisTDBsection.TrVectorNode.TrVectorSections[iVector];
if (thisVector.ShapeIndex == turntableTrackShape)
{
vectorIndex = iVector;
break;
}
}
return (vectorIndex);
}
//================================================================================================//
/// <summary>
/// FindTurntable : find reference to turntable as defined in turntable.dat using worldfile and uid references
/// </summary>
private int FindTurntable(string worldfile, int uid)
{
int foundIndex = -1;
// search through all moving tables
for (int iMT = 0; iMT < Simulatorref.MovingTables.Count && foundIndex == -1; iMT++)
{
MovingTable thisMT = Simulatorref.MovingTables[iMT];
if (thisMT.WFile == worldfile && thisMT.UID == uid)
{
foundIndex = iMT;
}
}
return (foundIndex);
}
//================================================================================================//
/// <summary>
/// Calculate offset of timetable position in access path
/// </summary>
private void CalculateAccessOffsets(int ipath, Turntable thisTurntable)
{
AccessPathDetails thisPath = AdditionalTurntableDetails.AccessPaths[ipath];
// calculate total length of track sections in first section backward upto turntable section
TrackCircuitSection thisSection = Simulatorref.Signals.TrackCircuitList[thisPath.AccessPath[0].TCSectionIndex];
int trackNodeIndex = thisSection.OriginalIndex;
Formats.Msts.TrVectorSection[] trackVectors = Simulatorref.Signals.trackDB.TrackNodes[trackNodeIndex].TrVectorNode.TrVectorSections;
// check if path is in front or behind turntable
int lastVectorIndex = 0;
float entrySectionLength = 0.0f;
float exitSectionLength = 0.0f;
if (thisPath.TableVectorIndex < thisPath.AccessTraveller.TrackVectorSectionIndex)
{
// path is behind turntable - calculate length from turntable to end
// also set direction forward (path is outbound)
lastVectorIndex = thisPath.TableVectorIndex + 1;
entrySectionLength = CalculateVectorLength(lastVectorIndex, trackVectors.Length - 1, lastVectorIndex, trackVectors);
exitSectionLength = CalculateVectorLength(0, lastVectorIndex - 2, lastVectorIndex, trackVectors);
thisPath.AccessPath[0].Direction = 1;
thisPath.AccessTraveller.Direction = Traveller.TravellerDirection.Forward;
}
else
{
// path is in front of turntable - calculate length from start to turntable
// also set direction backward (path is outbound)
lastVectorIndex = thisPath.TableVectorIndex - 1;
entrySectionLength = CalculateVectorLength(0, lastVectorIndex, lastVectorIndex, trackVectors);
exitSectionLength = CalculateVectorLength(lastVectorIndex + 2, trackVectors.Length - 1, lastVectorIndex, trackVectors);
thisPath.AccessPath[0].Direction = 0;
thisPath.AccessTraveller.Direction = Traveller.TravellerDirection.Backward;
}
// deduct clearance for turntable
// if no explicit clearance defined, use length of last vector before turntable
thisPath.TableApproachOffset = entrySectionLength - AdditionalTurntableDetails.TurntableApproachClearanceM;
thisPath.TableMiddleEntry = entrySectionLength + (thisTurntable.Length / 2.0f);
thisPath.TableMiddleExit = exitSectionLength + (thisTurntable.Length / 2.0f);
#if DEBUG_TURNTABLEINFO
Trace.TraceInformation("Pool : {0} , calculate access positions for path : {1} :", PoolName, thisPath.AccessPathName);
Trace.TraceInformation("\n start offset {0}\n middle offset [exit] : {1}\n middle offset [entry] : {2}\n turntable length : {3}\n section length : {4}",
thisPath.TableApproachOffset, thisPath.TableMiddleEntry, thisPath.TableMiddleExit, thisTurntable.Length, thisSection.Length);
#endif
// get turntable exit index
int exitIndex = -1;
for (int iExit = 0; iExit < thisTurntable.MyTrackNodesIndex.Length && exitIndex < 0; iExit++)
{
if (thisTurntable.MyTrackNodesIndex[iExit] == trackNodeIndex)
{
exitIndex = iExit;
}
}
thisPath.TableExitIndex = exitIndex;
// store updated path
AdditionalTurntableDetails.AccessPaths[ipath] = thisPath;
}
//================================================================================================//
/// <summary>
/// Calculate length and turntable offset for storage paths
/// </summary>
private void CalculateStorageOffsets(int ipath, Turntable thisTurntable)
{
PoolDetails thisPath = StoragePool[ipath];
float baseLength = 0;
// calculate total length of path sections except first section
for (int isection = 1; isection < thisPath.StoragePath.Count; isection++)
{
baseLength += Simulatorref.Signals.TrackCircuitList[thisPath.StoragePath[isection].TCSectionIndex].Length;
}
// calculate total length of track sections in first section backward upto turntable section
TrackCircuitSection thisSection = Simulatorref.Signals.TrackCircuitList[thisPath.StoragePath[0].TCSectionIndex];
int trackNodeIndex = thisSection.OriginalIndex;
Formats.Msts.TrVectorSection[] trackVectors = Simulatorref.Signals.trackDB.TrackNodes[trackNodeIndex].TrVectorNode.TrVectorSections;
// check if path is in front or behind turntable
int lastVectorIndex = 0;
float entrySectionLength = 0.0f;
float exitSectionLength = 0.0f;
if (thisPath.TableVectorIndex < thisPath.StoragePathTraveller.TrackVectorSectionIndex)
{
// path is behind turntable - calculate length from turntable to end
// also set direction forward (path is outbound)
lastVectorIndex = thisPath.TableVectorIndex + 1;
entrySectionLength = CalculateVectorLength(lastVectorIndex, trackVectors.Length - 1, lastVectorIndex, trackVectors);
exitSectionLength = CalculateVectorLength(0, lastVectorIndex - 2, lastVectorIndex, trackVectors);
thisPath.StoragePath[0].Direction = 1;
thisPath.StoragePathTraveller.Direction = Traveller.TravellerDirection.Forward;
}
else
{
// path is in front of turntable - calculate length from start to turntable
// also set direction backward (path is outbound)
lastVectorIndex = thisPath.TableVectorIndex - 1;
entrySectionLength = CalculateVectorLength(0, lastVectorIndex, lastVectorIndex, trackVectors);
exitSectionLength = CalculateVectorLength(lastVectorIndex + 2, trackVectors.Length - 1, lastVectorIndex, trackVectors);
thisPath.StoragePath[0].Direction = 0;
thisPath.StoragePathTraveller.Direction = Traveller.TravellerDirection.Backward;
}
float totalLength = baseLength + entrySectionLength;
// deduct clearance for turntable
thisPath.TableMiddleEntry = totalLength + (thisTurntable.Length / 2.0f);
thisPath.TableMiddleExit = exitSectionLength + (thisTurntable.Length / 2.0f);
#if DEBUG_TURNTABLEINFO
Trace.TraceInformation("Pool : {0} , calculate access positions for path {1}:", PoolName, thisPath.StorageName);
Trace.TraceInformation("\n middle offset [exit] : {0}\n middle offset [entry] : {1}\n turntable length : {2}\n section length : {3}",
thisPath.TableMiddleEntry, thisPath.TableMiddleExit, thisTurntable.Length, thisSection.Length);
#endif
// get turntable exit index
int exitIndex = -1;
for (int iExit = 0; iExit < thisTurntable.MyTrackNodesIndex.Length && exitIndex < 0; iExit++)
{
if (thisTurntable.MyTrackNodesIndex[iExit] == trackNodeIndex)
{
exitIndex = iExit;
}
}
thisPath.TableExitIndex = exitIndex;
// store updated path
StoragePool[ipath] = thisPath;
}
//================================================================================================//
/// <summary>
/// Calculate length of section connected to turntable
/// </summary>
private float CalculateVectorLength(int firstIndex, int LastIndex, int connectIndex, Formats.Msts.TrVectorSection[] vectors)
{
float returnLength = 0.0f;
for (int iVector = firstIndex; iVector <= LastIndex; iVector++)
{
float thisLength = 0.0f;
Formats.Msts.TrVectorSection thisVector = vectors[iVector];
if (Simulatorref.TSectionDat.TrackSections.ContainsKey(thisVector.SectionIndex))
{
Orts.Formats.Msts.TrackSection TS = Simulatorref.TSectionDat.TrackSections[thisVector.SectionIndex];
if (TS.SectionCurve != null)
{
thisLength =
MathHelper.ToRadians(Math.Abs(TS.SectionCurve.Angle)) *
TS.SectionCurve.Radius;
}
else
{
thisLength = TS.SectionSize.Length;
}
}
returnLength += thisLength;
}
return (returnLength);
}
//================================================================================================//
/// <summary>
/// Create in pool : create train in pool, for this type of pool train is created directly on storage path
/// </summary>
public override Train.TCSubpathRoute CreateInPool(TTTrain train, out int poolStorageIndex, bool checkAccessPath)
{
Train.TCSubpathRoute newRoute = null;
int storageIndex = -1;
// check if train fits on turntable - if not, reject
Turntable thisTurntable = Simulatorref.MovingTables[AdditionalTurntableDetails.TurntableIndex] as Turntable;
if (train.Length > thisTurntable.Length)
{
Trace.TraceWarning("Train : {0} too long ({1}) for turntable (length {2}) in pool {3}\n",
train.Name, train.Length.ToString(), thisTurntable.Length.ToString(), PoolName);
}
else
{
storageIndex = GetPoolExitIndex(train);
if (storageIndex < 0)
{
Trace.TraceWarning("Pool : " + PoolName + " : overflow : cannot place train : " + train.Name + "\n");
}
else
{
newRoute = new Train.TCSubpathRoute(StoragePool[storageIndex].StoragePath);
}
}
poolStorageIndex = storageIndex;
return (newRoute);
}
//================================================================================================//
/// <summary>
/// TestPoolExit : find access path linked to trains path
/// </summary>
public override bool TestPoolExit(TTTrain train)
{
int testAccess;
bool validPath = TestPoolAccess(train, out testAccess);
return (validPath);
}
public bool TestPoolAccess(TTTrain train, out int accessIndex)
{
bool validPool = false;
int reqPath = -1;
int reqPathIndex = -1;
// set dispose states
train.FormsStatic = true;
train.Closeup = true;
// find relevant access path
int lastValidSectionIndex = train.TCRoute.TCRouteSubpaths.Last().Count - 1;
for (int iSection = train.TCRoute.TCRouteSubpaths.Last().Count - 1; iSection >= 0 && reqPath == -1; iSection--)
{
int lastSectionIndex = train.TCRoute.TCRouteSubpaths.Last()[iSection].TCSectionIndex;
int lastSectionDirection = train.TCRoute.TCRouteSubpaths.Last()[iSection].Direction;
if (train.signalRef.TrackCircuitList[lastSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Normal)
{
for (int iPath = 0; iPath < AdditionalTurntableDetails.AccessPaths.Count && reqPath < 0; iPath++)
{
Train.TCSubpathRoute accessPath = AdditionalTurntableDetails.AccessPaths[iPath].AccessPath;
reqPathIndex = accessPath.GetRouteIndex(lastSectionIndex, 0);
// path is defined outbound, so directions must be opposite
if (reqPathIndex >= 0 && accessPath[reqPathIndex].Direction != lastSectionDirection)
{
reqPath = iPath;
lastValidSectionIndex = iSection;
}
}
}
}
// remove sections from train route if required
if (reqPath >= 0 && lastValidSectionIndex < train.TCRoute.TCRouteSubpaths.Last().Count - 1)
{
for (int iSection = train.TCRoute.TCRouteSubpaths.Last().Count - 1; iSection > lastValidSectionIndex; iSection--)
{
train.TCRoute.TCRouteSubpaths.Last().RemoveAt(iSection);
}
}
// none found
if (reqPath < 0)
{
Trace.TraceWarning("Train : " + train.Name + " : no valid path found to access pool storage " + PoolName + "\n");
train.FormsStatic = false;
train.Closeup = false;
}
// path found
else
{
validPool = true;
}
accessIndex = reqPath;
return (validPool);
}
//================================================================================================//
/// <summary>
/// Extract train from pool
/// </summary>
override public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime)
{
#if DEBUG_POOLINFO
var sob = new StringBuilder();
sob.AppendFormat("Pool {0} : request for train {1} ({2})", PoolName, train.Number, train.Name);
File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n");
#endif
// check if any engines available
int selectedTrainNumber = -1;
int selectedStorage = -1;
bool claimActive = false;
for (int iStorage = 0; iStorage < StoragePool.Count; iStorage++)
{
PoolDetails thisStorage = StoragePool[iStorage];
// engine has claimed access - this storage cannot be used for exit right now
if (thisStorage.ClaimUnits.Count > 0)
{
claimActive = true;
}
else if (thisStorage.StoredUnits.Count > 0)
{
selectedTrainNumber = thisStorage.StoredUnits.Last();
selectedStorage = iStorage;
break;
}
}
// pool underflow : create engine from scratch
if (selectedTrainNumber < 0)
{
// no train found but claim is active - create engine is delayed
if (claimActive)
{
#if DEBUG_TRACEINFO
Trace.TraceInformation("Pool {0} : train {1} : delayed through claimed access\n", PoolName, train.Name);
#endif
return (TrainFromPool.Delayed);
}
DateTime baseDTA = new DateTime();
DateTime moveTimeA = baseDTA.AddSeconds(train.AI.clockTime);
if (ForceCreation)
{
Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName +
" : no engines available in pool, engine is created, at " + moveTimeA.ToString("HH:mm:ss") + "\n");
#if DEBUG_POOLINFO
sob = new StringBuilder();
sob.AppendFormat("Pool {0} : train {1} ({2}) : no units available, engine force created", PoolName, train.Number, train.Name);
File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n");
#endif
return (TrainFromPool.ForceCreated);
}
else
{
Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName +
" : no engines available in pool, engine is not created , at " + moveTimeA.ToString("HH:mm:ss") + "\n");
#if DEBUG_POOLINFO
sob = new StringBuilder();
sob.AppendFormat("Pool {0} : train {1} ({2}) : no units available, enigne not created", PoolName, train.Number, train.Name);
File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n");
#endif
return (TrainFromPool.NotCreated);
}
}
// find required access path
int firstSectionIndex = train.TCRoute.TCRouteSubpaths[0][0].TCSectionIndex;
int reqAccessPath = -1;
for (int iPath = 0; iPath < AdditionalTurntableDetails.AccessPaths.Count; iPath++)
{
Train.TCSubpathRoute thisPath = AdditionalTurntableDetails.AccessPaths[iPath].AccessPath;
int pathSectionIndex = thisPath.GetRouteIndex(firstSectionIndex, 0);
if (pathSectionIndex >= 0 && AdditionalTurntableDetails.AccessPaths[iPath].AccessPath[pathSectionIndex].Direction == train.TCRoute.TCRouteSubpaths[0][0].Direction)
{
reqAccessPath = iPath;
break;
}
}
// no valid path found
if (reqAccessPath < 0)
{
Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + " : no valid access path found \n");
return (TrainFromPool.Failed);
}
// valid train found - start train