/
AIAuxAction.cs
2739 lines (2423 loc) · 114 KB
/
AIAuxAction.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 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/>.
/* AI
*
* Contains code to initialize and control AI trains.
*
*/
using Newtonsoft.Json;
using Orts.Formats.Msts;
using Orts.Formats.OR;
using Orts.Simulation.Physics;
using Orts.Simulation.RollingStocks;
using Orts.Simulation.RollingStocks.SubSystems.Controllers;
using Orts.Simulation.Signalling;
using ORTS.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Event = Orts.Common.Event;
namespace Orts.Simulation.AIs
{
#region AuxActionsContainer
//================================================================================================//
/// <summary>
/// AuxActionsContainer
/// Used to manage all the action ref object.
/// </summary>
public class AuxActionsContainer : ActionContainer
{
public Train.DistanceTravelledActions genRequiredActions = new Train.DistanceTravelledActions(); // distance travelled Generic action list for AITrain
public Train.DistanceTravelledActions specRequiredActions = new Train.DistanceTravelledActions();
Train ThisTrain;
public AuxActionsContainer(Train thisTrain, ORRouteConfig orRouteConfig)
{
if (thisTrain is AITrain && orRouteConfig != null)
{
SetGenAuxActions((AITrain)thisTrain, orRouteConfig);
}
else
{
GenAuxActions = new List<KeyValuePair<string, AuxActionRef>>();
}
ThisTrain = thisTrain;
}
public AuxActionsContainer(Train thisTrain, BinaryReader inf, string routePath)
{
//SpecAuxActions = new List<AuxActionRef>();
////GenAuxActions = new List<AuxActionRef>();
//GenFunctions = new List<KeyValuePair<System.Type, AuxActionRef>>();
//if (thisTrain is AITrain)
//{
// GenAuxActions = SetGenAuxActions((AITrain)thisTrain, null);
//}
ThisTrain = thisTrain;
if (thisTrain is AITrain && thisTrain.Simulator.orRouteConfig != null)
{
SetGenAuxActions((AITrain)thisTrain, thisTrain.Simulator.orRouteConfig);
}
int cntAuxActionSpec = inf.ReadInt32();
for (int idx = 0; idx < cntAuxActionSpec; idx++)
{
int cntAction = inf.ReadInt32();
AuxActionRef action;
string actionRef = inf.ReadString();
AuxActionRef.AUX_ACTION nextAction = (AuxActionRef.AUX_ACTION)Enum.Parse(typeof(AuxActionRef.AUX_ACTION), actionRef);
switch (nextAction)
{
case AuxActionRef.AUX_ACTION.WAITING_POINT:
action = new AIActionWPRef(thisTrain, inf);
SpecAuxActions.Add(action);
break;
case AuxActionRef.AUX_ACTION.SOUND_HORN:
action = new AIActionHornRef(thisTrain, inf);
SpecAuxActions.Add(action);
break;
case AuxActionRef.AUX_ACTION.SIGNAL_DELEGATE:
action = new AIActSigDelegateRef(thisTrain, inf);
var hasWPActionAssociated = inf.ReadBoolean();
if (hasWPActionAssociated && SpecAuxActions.Count > 0)
{
var candidateAssociate = SpecAuxActions[SpecAuxActions.Count - 1];
if (candidateAssociate is AIActionWPRef && (candidateAssociate as AIActionWPRef).TCSectionIndex == (action as AIActSigDelegateRef).TCSectionIndex)
{
(action as AIActSigDelegateRef).AssociatedWPAction = candidateAssociate as AIActionWPRef;
}
}
SpecAuxActions.Add(action);
break;
default:
break;
}
}
}
public void Save(BinaryWriter outf, int currentClock)
{
int cnt = 0;
outf.Write(SpecAuxActions.Count);
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "SaveAuxContainer, count :" + SpecAuxActions.Count +
"Position in file: " + outf.BaseStream.Position + "\n");
#endif
AITrain aiTrain = ThisTrain as AITrain;
if (SpecAuxActions.Count > 0 && SpecAuxActions[0] != null &&
specRequiredActions.First != null && specRequiredActions.First.Value is AuxActSigDelegate)
// SigDelegate WP is running
if (((AuxActSigDelegate)specRequiredActions.First.Value).currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION &&
!(((AuxActSigDelegate)specRequiredActions.First.Value).ActionRef as AIActSigDelegateRef).IsAbsolute)
{
int remainingDelay = ((AuxActSigDelegate)specRequiredActions.First.Value).ActualDepart - currentClock;
AIActSigDelegateRef actionRef = ((AuxActSigDelegate)specRequiredActions.First.Value).ActionRef as AIActSigDelegateRef;
if (actionRef.AssociatedWPAction != null) actionRef.AssociatedWPAction.SetDelay(remainingDelay);
actionRef.Delay = remainingDelay;
}
if (!(ThisTrain == ThisTrain.Simulator.OriginalPlayerTrain && (ThisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERDRIVEN ||
ThisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERHOSTING || ThisTrain.TrainType == Train.TRAINTYPE.PLAYER || ThisTrain.TrainType == Train.TRAINTYPE.AI)))
{
if (ThisTrain is AITrain && ((aiTrain.MovementState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && aiTrain.nextActionInfo != null &&
aiTrain.nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.AUX_ACTION && aiTrain.nextActionInfo is AuxActionWPItem)
|| ( aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 &&
aiTrain.AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt != null &&
(aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt.currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION)))
// WP is running
{
// Do nothing if it is an absolute WP
if (!(aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 && aiTrain.AuxActionsContain.SpecAuxActions[0] is AIActionWPRef &&
(aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay >= 30000 && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay < 40000))
{
int remainingDelay;
if (aiTrain.nextActionInfo != null && aiTrain.nextActionInfo is AuxActionWPItem) remainingDelay = ((AuxActionWPItem)aiTrain.nextActionInfo).ActualDepart - currentClock;
else remainingDelay = ((AIActionWPRef)SpecAuxActions[0]).keepIt.ActualDepart - currentClock;
((AIActionWPRef)SpecAuxActions[0]).SetDelay(remainingDelay);
}
}
}
foreach (var action in SpecAuxActions)
{
((AIAuxActionsRef)action).save(outf, cnt);
cnt++;
}
}
#if false
int cnt = 0;
outf.Write(AuxActions.Count);
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "SaveAIAuxActions, count :" + AuxActions.Count +
"Position in file: " + outf.BaseStream.Position + "\n");
#endif
foreach (var action in AuxActions)
{
action.save(outf, cnt);
cnt++;
}
#endif
protected List<KeyValuePair<string, AuxActionRef>> ConvertActions(Train thisTrain, ActionContainer actionContainer)
{
List<KeyValuePair<string, AuxActionRef>> converted = new List<KeyValuePair<string, AuxActionRef>>();
foreach (var action in actionContainer.GenAuxActions)
{
if (action.Value.GetType() == typeof(AuxActionHorn))
{
AIActionHornRef horn = new AIActionHornRef(thisTrain, (AuxActionHorn)action.Value, 0);
List<KeyValuePair<System.Type, AuxActionRef>> listInfo = horn.GetCallFunction();
foreach (var function in listInfo)
GenFunctions.Add(function);
KeyValuePair<string, AuxActionRef> info = new KeyValuePair<string, AuxActionRef>(action.Key, horn);
converted.Add(info);
}
else if (action.Value.GetType() == typeof(AuxControlStart))
{
AIActionControlStartRef controlStart = new AIActionControlStartRef(thisTrain, (AuxControlStart)action.Value, 0);
List<KeyValuePair<System.Type, AuxActionRef>> listInfo = controlStart.GetCallFunction();
foreach (var function in listInfo)
GenFunctions.Add(function);
KeyValuePair<string, AuxActionRef> info = new KeyValuePair<string, AuxActionRef>(action.Key, controlStart);
converted.Add(info);
// If we use the ControllStart, then we must allow Generic WP to be created.
AIActionWPRef wp = new AIActionWPRef(thisTrain, (AuxControlStart)action.Value, 0);
listInfo = wp.GetCallFunction();
foreach (var function in listInfo)
GenFunctions.Add(function);
info = new KeyValuePair<string, AuxActionRef>(action.Key, controlStart);
converted.Add(info);
}
}
return converted;
}
protected List<KeyValuePair<string, AuxActionRef>> SetGenAuxActions(AITrain thisTrain, ORRouteConfig orRouteConfig) // Add here the new Generic Action
{
List<KeyValuePair<string, AuxActionRef>> loaded = null;
#if WITH_GEN_ACTION
//AIActionSignalRef actionSignal = new AIActionSignalRef(thisTrain, 0f, 0f, 0, 0, 0, 0);
//actionSignal.SetDelay(10);
//actionSignal.IsGeneric = true;
//GenAuxActions.Add(actionSignal);
////GenFunctions.Add(actionSignal.GetCallFunction());
AIActionHornRef actionHorn = new AIActionHornRef(thisTrain, 0f, 0f, 0, 0, 0, 0);
actionHorn.SetDelay(2);
actionHorn.IsGeneric = true;
GenAuxActions.Add(actionHorn);
GenFunctions.Add(actionHorn.GetCallFunction());
AIActionSteamRef actionSteam = new AIActionSteamRef(thisTrain, 0f, 0f, 0, 0, 0, 0);
actionSteam.SetDelay(2);
actionSteam.IsGeneric = true;
GenAuxActions.Add(actionSteam);
GenFunctions.Add(actionSteam.GetCallFunction());
#endif
if (orRouteConfig == null)
{
loaded = new List<KeyValuePair<string, AuxActionRef>>();
return loaded;
}
else
{
loaded = ConvertActions(thisTrain, orRouteConfig.ActionContainer);
}
var activity = thisTrain.Simulator.Activity;
if (activity != null && activity.Tr_Activity.Tr_Activity_File.AIBlowsHornAtLevelCrossings && SpecAuxActions.Count == 0)
{
AuxActionHorn auxActionHorn = new AuxActionHorn(isGeneric: true, hornPattern: activity.Tr_Activity.Tr_Activity_File.AILevelCrossingHornPattern);
AIActionHornRef horn = new AIActionHornRef(thisTrain, auxActionHorn, 0);
List<KeyValuePair<System.Type, AuxActionRef>> listInfo = horn.GetCallFunction();
foreach (var function in listInfo)
GenFunctions.Add(function);
}
//loaded = orRouteConfig.getGenAuxAction();
return loaded;
}
//public bool CheckGenActions(System.Type typeSource, float rearDist, float frontDist, WorldLocation location, uint trackNodeIndex)
public bool CheckGenActions(System.Type typeSource, WorldLocation location, params object[] list)
{
if (ThisTrain is AITrain)
{
AITrain aiTrain = ThisTrain as AITrain;
foreach (var fonction in GenFunctions)
{
if (typeSource == fonction.Key) // Caller object is a LevelCrossing
{
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "GenFunctions registered for train " + ThisTrain.Number + "\n");
#endif
AIAuxActionsRef called = (AIAuxActionsRef)fonction.Value;
if (called.HasAction(ThisTrain.Number, location))
return false;
AIActionItem newAction = called.CheckGenActions(location, aiTrain, list);
if (newAction != null)
{
if (newAction is AuxActionWPItem)
specRequiredActions.InsertAction(newAction);
else
genRequiredActions.InsertAction(newAction);
}
}
}
}
return false;
}
public void RemoveGenActions(System.Type typeSource, WorldLocation location)
{
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "Remove GenAction for train " + ThisTrain.Number + "\n");
#endif
if ((ThisTrain is AITrain))
{
AITrain aiTrain = ThisTrain as AITrain;
foreach (var fonction in GenFunctions)
{
if (typeSource == fonction.Key) // Caller object is a LevelCrossing
{
AIAuxActionsRef called = (AIAuxActionsRef)fonction.Value;
if (called.HasAction(ThisTrain.Number, location))
{
called.RemoveReference(aiTrain.Number, location);
}
}
}
}
}
public void RemoveSpecReqAction(AuxActionItem thisAction)
{
if (thisAction.CanRemove(ThisTrain))
{
Train.DistanceTravelledItem thisItem = thisAction;
specRequiredActions.Remove(thisItem);
}
}
public void ProcessGenAction(AITrain thisTrain, int presentTime, float elapsedClockSeconds, AITrain.AI_MOVEMENT_STATE movementState)
{
if (genRequiredActions.Count <= 0 || !(ThisTrain is AITrain))
return;
AITrain aiTrain = ThisTrain as AITrain;
List<Train.DistanceTravelledItem> itemList = new List<Train.DistanceTravelledItem>();
foreach (var action in genRequiredActions)
{
AIActionItem actionItem = action as AIActionItem;
if (actionItem.RequiredDistance <= ThisTrain.DistanceTravelledM)
{
itemList.Add(actionItem);
}
}
foreach (var action in itemList)
{
AIActionItem actionItem = action as AIActionItem;
actionItem.ProcessAction(aiTrain, presentTime, elapsedClockSeconds, movementState);
}
}
public AITrain.AI_MOVEMENT_STATE ProcessSpecAction(AITrain thisTrain, int presentTime, float elapsedClockSeconds, AITrain.AI_MOVEMENT_STATE movementState)
{
AITrain.AI_MOVEMENT_STATE MvtState = movementState;
if (specRequiredActions.Count <= 0 || !(ThisTrain is AITrain))
return MvtState;
AITrain aiTrain = ThisTrain as AITrain;
List<Train.DistanceTravelledItem> itemList = new List<Train.DistanceTravelledItem>();
foreach (var action in specRequiredActions)
{
AIActionItem actionItem = action as AIActionItem;
if (actionItem.RequiredDistance >= ThisTrain.DistanceTravelledM)
continue;
if (actionItem is AuxActSigDelegate)
{
var actionRef = (actionItem as AuxActSigDelegate).ActionRef;
if ((actionRef as AIActSigDelegateRef).IsAbsolute)
continue;
}
itemList.Add(actionItem);
}
foreach (var action in itemList)
{
AITrain.AI_MOVEMENT_STATE tmpMvt;
AIActionItem actionItem = action as AIActionItem;
tmpMvt = actionItem.ProcessAction(aiTrain, presentTime, elapsedClockSeconds, movementState);
if (tmpMvt != movementState)
MvtState = tmpMvt; // Try to avoid override of changed state of previous action
}
return MvtState;
}
public void Remove(AuxActionItem action)
{
bool ret = false;
bool remove = true;
if (action.ActionRef.IsGeneric)
{
if (genRequiredActions.Count > 0)
ret = genRequiredActions.Remove(action);
if (!ret && specRequiredActions.Count > 0)
{
if (((AIAuxActionsRef)action.ActionRef).CallFreeAction(ThisTrain))
RemoveSpecReqAction(action);
}
}
if (action.ActionRef.ActionType == AuxActionRef.AUX_ACTION.SOUND_HORN)
{
if (specRequiredActions.Contains(action)) RemoveSpecReqAction(action);
else remove = false;
}
if (CountSpec() > 0 && remove == true)
SpecAuxActions.Remove(action.ActionRef);
if (ThisTrain is AITrain)
((AITrain)ThisTrain).ResetActions(true);
}
public void RemoveAt(int posit)
{
SpecAuxActions.RemoveAt(posit);
}
public AuxActionRef this[int key]
{
get
{
if (key >= SpecAuxActions.Count)
return null;
return SpecAuxActions[key];
}
set
{
}
}
public int Count()
{
return CountSpec();
}
public int CountSpec()
{
return SpecAuxActions.Count;
}
//================================================================================================//
// SPA: Added for use with new AIActionItems
/// <summary>
/// Create Specific Auxiliary Action, like WP
/// <\summary>
public void SetAuxAction(Train thisTrain)
{
if (SpecAuxActions.Count <= 0)
return;
AIAuxActionsRef thisAction;
int specAuxActionsIndex = 0;
bool requiredActionsInserted = false;
while (specAuxActionsIndex <= SpecAuxActions.Count-1)
{
while (SpecAuxActions.Count > 0)
{
thisAction = (AIAuxActionsRef)SpecAuxActions[specAuxActionsIndex];
if (thisAction.SubrouteIndex > thisTrain.TCRoute.activeSubpath)
{
return;
}
if (thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath)
break;
else
{
SpecAuxActions.RemoveAt(0);
if (SpecAuxActions.Count <= 0) return;
}
}
thisAction = (AIAuxActionsRef)SpecAuxActions[specAuxActionsIndex];
bool validAction = false;
float[] distancesM;
while (!validAction)
{
if (thisTrain is AITrain && thisTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN)
{
AITrain aiTrain = thisTrain as AITrain;
distancesM = thisAction.CalculateDistancesToNextAction(aiTrain, ((AITrain)aiTrain).TrainMaxSpeedMpS, true);
}
else
{
distancesM = thisAction.CalculateDistancesToNextAction(thisTrain, thisTrain.SpeedMpS, true);
}
//<CSComment> Next block does not seem useful. distancesM[0] includes distanceTravelledM, so it practically can be 0 only at start of game
/* if (distancesM[0]< 0f)
{
SpecAuxActions.RemoveAt(0);
if (SpecAuxActions.Count == 0)
{
return;
}
thisAction = (AIAuxActionsRef)SpecAuxActions[0];
if (thisAction.SubrouteIndex > thisTrain.TCRoute.activeSubpath) return;
}
else */
{
float requiredSpeedMpS = 0;
if (requiredActionsInserted && ((thisAction is AIActSigDelegateRef && !((AIActSigDelegateRef)thisAction).IsAbsolute))) return;
validAction = true;
AIActionItem newAction = ((AIAuxActionsRef)SpecAuxActions[specAuxActionsIndex]).Handler(distancesM[1], requiredSpeedMpS, distancesM[0], thisTrain.DistanceTravelledM);
if (newAction != null)
{
if (thisTrain is AITrain && newAction is AuxActionWPItem) // Put only the WP for AI into the requiredAction, other are on the container
{
bool found = false;
requiredActionsInserted = true;
if ((thisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERDRIVEN || thisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERHOSTING) && thisTrain.requiredActions.Count > 0)
{
// check if action already inserted
foreach (Train.DistanceTravelledItem item in thisTrain.requiredActions)
{
if (item is AuxActionWPItem)
{
found = true;
continue;
}
}
}
if (!found)
{
thisTrain.requiredActions.InsertAction(newAction);
continue;
// ((AITrain)thisTrain).nextActionInfo = newAction; // action must be restored through required actions only
}
}
else
{
specRequiredActions.InsertAction(newAction);
if (newAction is AuxActionWPItem || newAction is AuxActSigDelegate)
return;
}
}
}
}
specAuxActionsIndex++;
}
}
//================================================================================================//
//
/// <summary>
/// Reset WP Aux Action, if any
/// <\summary>
public void ResetAuxAction(Train thisTrain)
{
if (SpecAuxActions.Count <= 0)
return;
AIAuxActionsRef thisAction;
thisAction = (AIAuxActionsRef)SpecAuxActions[0];
if (thisAction.SubrouteIndex != thisTrain.TCRoute.activeSubpath) return;
thisAction.LinkedAuxAction = false;
return;
}
//================================================================================================//
//
/// <summary>
/// Move next Aux Action, if in same section, under train in case of decoupling
/// <\summary>
public void MoveAuxAction(Train thisTrain)
{
AITrain thisAITrain = (AITrain)thisTrain;
if (SpecAuxActions.Count <= 0)
return;
AIAuxActionsRef thisAction;
thisAction = (AIAuxActionsRef)SpecAuxActions[0];
if (thisAction is AIActionWPRef && thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath && thisAction.TCSectionIndex == thisTrain.PresentPosition[0].TCSectionIndex)
// Waiting point is just in the same section where the train is; move it under the train
{
AuxActionWPItem thisWPItem;
if (thisAITrain.nextActionInfo != null && thisAITrain.nextActionInfo is AuxActionWPItem)
{
thisWPItem = (AuxActionWPItem)thisAITrain.nextActionInfo;
if (thisWPItem.ActionRef == thisAction)
{
thisWPItem.ActivateDistanceM = thisTrain.PresentPosition[0].DistanceTravelledM - 5;
thisAction.LinkedAuxAction = true;
}
}
thisAction.RequiredDistance = thisTrain.PresentPosition[0].TCOffset - 5;
}
}
//================================================================================================//
//
/// <summary>
/// Move next Aux Action, if in same section and in next subpath (reversal in between), under train in case of decoupling
/// <\summary>
public void MoveAuxActionAfterReversal(Train thisTrain)
{
if (SpecAuxActions.Count <= 0)
return;
AIAuxActionsRef thisAction;
thisAction = (AIAuxActionsRef)SpecAuxActions[0];
if (thisAction is AIActionWPRef && thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath+1 && thisAction.TCSectionIndex == thisTrain.PresentPosition[1].TCSectionIndex)
// Waiting point is just in the same section where the train is; move it under the train
{
int thisSectionIndex = thisTrain.PresentPosition[1].TCSectionIndex;
TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex];
thisAction.RequiredDistance = thisSection.Length - thisTrain.PresentPosition[1].TCOffset - 5;
}
}
public AuxActionRef GetGenericAuxAction(AuxActionRef.AUX_ACTION typeReq)
{
return GenAuxActions.GetGenericAuxAction(typeReq);
}
public void Add(AuxActionRef action)
{
SpecAuxActions.Add(action);
}
}
public static class AIAuxActionRefList
{
public static AuxActionRef GetGenericAuxAction(this List<KeyValuePair<string, AuxActionRef>> list, AuxActionRef.AUX_ACTION typeReq)
{
foreach (var AuxAction in list)
{
AIAuxActionsRef thisAction = AuxAction.Value as AIAuxActionsRef;
if (thisAction.NextAction == typeReq)
return thisAction;
}
return null;
}
public static List<AuxActionRef> GetValidActions(this List<KeyValuePair<string, AuxActionRef>> list, AITrain thisTrain, float presentSpeedMpS, bool reschedule)
{
List<AuxActionRef> listAction = new List<AuxActionRef>();
if (list == null)
return listAction;
var previousList = list;
bool getFirst = false;
try
{
foreach (var action in previousList)
{
AIAuxActionsRef thisAction = action.Value as AIAuxActionsRef;
float[] distancesM = thisAction.CalculateDistancesToNextAction(thisTrain, presentSpeedMpS, reschedule);
if (!thisAction.IsGeneric && !getFirst)
{
if (distancesM[0] < 0f)
{
previousList.RemoveAt(0);
continue;
}
listAction.Insert(0, thisAction);
getFirst = true;
}
if (distancesM[0] == 0f || distancesM[0] == float.MaxValue)
{
listAction.Add(thisAction);
}
}
}
catch
{
}
return listAction;
}
}
#endregion
#region AuxActionRef
////================================================================================================//
///// <summary>
///// AuxActionRef
///// info used to figure out one auxiliary action along the route. It's a reference data, not a run data.
///// </summary>
public class AIAuxActionsRef : AuxActionRef
{
public int SubrouteIndex;
public int RouteIndex;
public int TCSectionIndex;
public int Direction;
protected int TriggerDistance = 0;
public bool LinkedAuxAction = false;
protected List<KeyValuePair<int, WorldLocation>> AskingTrain;
public SignalObject SignalReferenced = null;
public float RequiredSpeedMpS;
public float RequiredDistance;
public int Delay;
public int OriginalDelay;
public int EndSignalIndex { get; protected set; }
public AUX_ACTION NextAction = AUX_ACTION.NONE;
//================================================================================================//
/// <summary>
/// AIAuxActionsRef: Generic Constructor
/// The specific datas are used to fire the Action.
/// </summary>
public AIAuxActionsRef(float requiredSpeedMps, WorldLocation location)
{
}
public AIAuxActionsRef(Train thisTrain, float distance, float requiredSpeedMpS, int subrouteIdx, int routeIdx, int sectionIdx, int dir, AuxActionRef.AUX_ACTION actionType = AuxActionRef.AUX_ACTION.NONE) :
base(actionType, false) //null, requiredSpeedMpS, , -1, )
{
RequiredDistance = distance;
RequiredSpeedMpS = requiredSpeedMpS;
SubrouteIndex = subrouteIdx;
RouteIndex = routeIdx;
TCSectionIndex = sectionIdx;
Direction = dir;
AskingTrain = new List<KeyValuePair<int, WorldLocation>>();
IsGeneric = false;
EndSignalIndex = -1;
}
public AIAuxActionsRef(Train thisTrain, BinaryReader inf, AuxActionRef.AUX_ACTION actionType = AuxActionRef.AUX_ACTION.NONE)
{
RequiredSpeedMpS = inf.ReadSingle();
RequiredDistance = inf.ReadSingle();
SubrouteIndex = inf.ReadInt32();
RouteIndex = inf.ReadInt32();
TCSectionIndex = inf.ReadInt32();
Direction = inf.ReadInt32();
TriggerDistance = inf.ReadInt32();
IsGeneric = inf.ReadBoolean();
AskingTrain = new List<KeyValuePair<int, WorldLocation>>();
EndSignalIndex = inf.ReadInt32();
if (EndSignalIndex >= 0)
SetSignalObject(thisTrain.signalRef.SignalObjects[EndSignalIndex]);
else
SetSignalObject(null);
ActionType = actionType;
}
public virtual List<KeyValuePair<System.Type, AuxActionRef>> GetCallFunction()
{
return default(List<KeyValuePair<System.Type, AuxActionRef>>);
}
//================================================================================================//
/// <summary>
/// Handler
/// Like a fabric, if other informations are needed, please define specific function that can be called on the new object
/// </summary>
public virtual AIActionItem Handler(params object[] list)
{
AIActionItem info = null;
if (!LinkedAuxAction || IsGeneric)
{
info = new AuxActionItem(this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION);
info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]);
//info = new AuxActionItem(distance, speed, activateDistance, insertedDistance,
// this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION);
}
return info;
}
//================================================================================================//
/// <summary>
/// CalculateDistancesToNextAction
/// PLease, don't use the default function, redefine it.
/// </summary>
public virtual float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule)
{
float[] distancesM = new float[2];
distancesM[1] = 0.0f;
distancesM[0] = thisTrain.PresentPosition[0].DistanceTravelledM;
return (distancesM);
}
public virtual float[] GetActivationDistances(Train thisTrain, WorldLocation location)
{
float[] distancesM = new float[2];
distancesM[1] = float.MaxValue;
distancesM[0] = float.MaxValue;
return (distancesM);
}
//================================================================================================//
//
// Save
//
public virtual void save(BinaryWriter outf, int cnt)
{
outf.Write(cnt);
string info = NextAction.ToString();
outf.Write(NextAction.ToString());
outf.Write(RequiredSpeedMpS);
outf.Write(RequiredDistance);
outf.Write(SubrouteIndex);
outf.Write(RouteIndex);
outf.Write(TCSectionIndex);
outf.Write(Direction);
outf.Write(TriggerDistance);
outf.Write(IsGeneric);
outf.Write(EndSignalIndex);
//if (LinkedAuxAction != null)
// outf.Write(LinkedAuxAction.NextAction.ToString());
//else
// outf.Write(AI_AUX_ACTION.NONE.ToString());
}
//================================================================================================//
//
// Restore
//
public void Register(int trainNumber, WorldLocation location)
{
AskingTrain.Add(new KeyValuePair<int, WorldLocation>(trainNumber, location));
}
//public bool CheckGenActions(System.Type typeSource, float rearDist, float frontDist, WorldLocation location, uint trackNodeIndex)
public virtual AIActionItem CheckGenActions(WorldLocation location, AITrain thisTrain, params object[] list)
{
return null;
}
public bool HasAction(int trainNumber, WorldLocation location)
{
foreach (var info in AskingTrain)
{
int number = (int)info.Key;
if (number == trainNumber)
{
WorldLocation locationRegistered = info.Value;
if (location == locationRegistered)
return true;
}
}
return false;
}
public virtual bool CallFreeAction(Train ThisTrain)
{
return true;
}
public void RemoveReference(int trainNumber, WorldLocation location)
{
//var info = default (KeyValuePair<int, WorldLocation>);
foreach (var info in AskingTrain)
{
int number = (int)info.Key;
if (number == trainNumber)
{
WorldLocation locationRegistered = info.Value;
if (location == locationRegistered)
{
AskingTrain.Remove(info);
break;
}
}
}
}
public void SetSignalObject(SignalObject signal)
{
SignalReferenced = signal;
}
}
//================================================================================================//
/// <summary>
/// AIActionWPRef
/// info used to figure out a Waiting Point along the route.
/// </summary>
public class AIActionWPRef : AIAuxActionsRef
{
public AuxActionWPItem keepIt = null;
public AIActionWPRef(Train thisTrain, float distance, float requiredSpeedMpS, int subrouteIdx, int routeIdx, int sectionIdx, int dir)
: base(thisTrain, distance, requiredSpeedMpS, subrouteIdx, routeIdx, sectionIdx, dir, AuxActionRef.AUX_ACTION.WAITING_POINT)
{
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "New AIAuxActionRef (WP) for train " + thisTrain.Number +
" Required Distance " + distance + ", speed " + requiredSpeedMpS + ", and dir " + dir + "\n");
File.AppendAllText(@"C:\temp\checkpath.txt", "\t\tSection id: " + subrouteIdx + "." + routeIdx + "." + sectionIdx
+ "\n");
#endif
NextAction = AUX_ACTION.WAITING_POINT;
}
public AIActionWPRef(Train thisTrain, BinaryReader inf)
: base (thisTrain, inf)
{
Delay = inf.ReadInt32();
OriginalDelay = inf.ReadInt32();
NextAction = AUX_ACTION.WAITING_POINT;
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "\tRestore one WPAuxAction" +
"Position in file: " + inf.BaseStream.Position +
" type Action: " + NextAction.ToString() +
" Delay: " + Delay + "\n");
#endif
}
public AIActionWPRef(Train thisTrain, AuxControlStart myBase, int nop = 0)
: base(thisTrain, 0f, 0f, 0, 0, 0, 0, myBase.ActionType)
{
Delay = myBase.ActivationDelay; // Generic WP Delay will be the Control Start ActivationDelay
NextAction = AUX_ACTION.WAITING_POINT;
IsGeneric = myBase.IsGeneric;
}
public override void save(BinaryWriter outf, int cnt)
{
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "\tSave one WPAuxAction, count :" + cnt +
"Position in file: " + outf.BaseStream.Position +
" type Action: " + NextAction.ToString() +
" Delay: " + Delay + "\n");
#endif
base.save(outf, cnt);
outf.Write(Delay);
outf.Write(OriginalDelay);
}
public override AIActionItem Handler(params object[] list)
{
AIActionItem info = null;
if (!LinkedAuxAction || IsGeneric)
{
LinkedAuxAction = true;
info = new AuxActionWPItem(this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION);
info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]);
((AuxActionWPItem)info).SetDelay(Delay);
keepIt = (AuxActionWPItem)info;
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "New action item, type WP with distance " + distance + ", speed " + speed + ", activate distance " + activateDistance +
" and inserted distance " + insertedDistance + " (delay " + Delay + ")\n");
#endif
}
else if (LinkedAuxAction)
{
info = keepIt;
}
return (AIActionItem)info;
}
public override AIActionItem CheckGenActions(WorldLocation location, AITrain thisTrain, params object[] list)
{
AIActionItem newAction = null;
int SpeedMps = (int)thisTrain.SpeedMpS;
TrainCar locomotive = thisTrain.FindLeadLocomotive();
if (Math.Abs(SpeedMps) <= Simulator.MaxStoppedMpS) // We call the handler to generate an actionRef
{
newAction = Handler(0f, 0f, thisTrain.DistanceTravelledM, thisTrain.DistanceTravelledM);
Register(thisTrain.Number, location);
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "Caller registered for\n");
#endif
}
return newAction;
}
//================================================================================================//
/// <summary>
/// SetDelay
/// To fullfill the waiting delay.
/// </summary>
public void SetDelay(int delay)
{
#if WITH_PATH_DEBUG
File.AppendAllText(@"C:\temp\checkpath.txt", "\tDelay set to: " + delay + "\n");
#endif
Delay = delay;
}
public override float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule)
{
float[] distancesM = new float[2];
int thisSectionIndex = thisTrain.PresentPosition[0].TCSectionIndex;
TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex];
float leftInSectionM = thisSection.Length - thisTrain.PresentPosition[0].TCOffset;
// get action route index - if not found, return distances < 0
int actionIndex0 = thisTrain.PresentPosition[0].RouteListIndex;
int actionRouteIndex = thisTrain.ValidRoute[0].GetRouteIndex(TCSectionIndex, actionIndex0);
float activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM + thisTrain.ValidRoute[0].GetDistanceAlongRoute(actionIndex0, leftInSectionM, actionRouteIndex, this.RequiredDistance, thisTrain.AITrainDirectionForward, thisTrain.signalRef);
// if reschedule, use actual speed
float triggerDistanceM = TriggerDistance;
if (thisTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN)
{
if (thisTrain is AITrain)
{