forked from WheteThunger/AutomatedWorkcarts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutomatedWorkcarts.cs
5299 lines (4337 loc) · 208 KB
/
AutomatedWorkcarts.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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Rust;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;
using static BaseEntity;
using static TrainCar;
using static TrainEngine;
using static TrainTrackSpline;
namespace Oxide.Plugins
{
[Info("Automated Workcarts", "WhiteThunder", "0.33.1")]
[Description("Automates workcarts with NPC conductors.")]
internal class AutomatedWorkcarts : CovalencePlugin
{
#region Fields
[PluginReference]
private Plugin CargoTrainEvent;
private static AutomatedWorkcarts _pluginInstance;
private const string PermissionToggle = "automatedworkcarts.toggle";
private const string PermissionManageTriggers = "automatedworkcarts.managetriggers";
private const string ShopkeeperPrefab = "assets/prefabs/npc/bandit/shopkeepers/bandit_shopkeeper.prefab";
private const string GenericMapMarkerPrefab = "assets/prefabs/tools/map/genericradiusmarker.prefab";
private const string VendingMapMarkerPrefab = "assets/prefabs/deployable/vendingmachine/vending_mapmarker.prefab";
private const string BradleyExplosionEffectPrefab = "assets/prefabs/npc/m2bradley/effects/bradley_explosion.prefab";
private const string IdPlaceholder = "$id";
private static readonly FieldInfo TrainCouplingIsValidField = typeof(TrainCoupling).GetField("isValid", BindingFlags.NonPublic | BindingFlags.Instance)
?? typeof(TrainCoupling).GetField("isValid", BindingFlags.Public | BindingFlags.Instance);
private static readonly object False = false;
private static readonly Regex IdRegex = new Regex("\\$id", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly BasePlayer[] _playerQueryResults = new BasePlayer[64];
private Configuration _pluginConfig;
private StoredPluginData _pluginData;
private StoredTunnelData _tunnelData;
private StoredMapData _mapData;
private readonly SpawnedTrainCarTracker _spawnedTrainCarTracker = new SpawnedTrainCarTracker();
private TriggerManager _triggerManager;
private TrainManager _trainManager;
private Coroutine _startupCoroutine;
#endregion
#region Hooks
private void Init()
{
_pluginInstance = this;
_pluginData = StoredPluginData.Load();
_tunnelData = StoredTunnelData.Load();
_trainManager = new TrainManager(_pluginConfig, _pluginData, _spawnedTrainCarTracker);
_triggerManager = new TriggerManager(_pluginConfig, _trainManager, _tunnelData);
permission.RegisterPermission(PermissionToggle, this);
permission.RegisterPermission(PermissionManageTriggers, this);
Unsubscribe(nameof(OnEntitySpawned));
if (!_pluginConfig.GenericMapMarker.Enabled)
{
Unsubscribe(nameof(OnPlayerConnected));
}
}
private void OnServerInitialized()
{
if (!_pluginConfig.EnableTerrainCollision)
{
foreach (var entity in BaseNetworkable.serverEntities)
{
var trainCar = entity as TrainCar;
if (trainCar != null)
{
EnableTerrainCollision(trainCar, false);
}
}
Subscribe(nameof(OnEntitySpawned));
}
_tunnelData.MigrateTriggers();
_mapData = StoredMapData.Load();
_triggerManager.SetMapData(_mapData);
_startupCoroutine = ServerMgr.Instance.StartCoroutine(DoStartupRoutine());
}
private void Unload()
{
if (!_pluginConfig.EnableTerrainCollision)
{
foreach (var entity in BaseNetworkable.serverEntities)
{
var trainCar = entity as TrainCar;
if (trainCar != null)
{
EnableTerrainCollision(trainCar, true);
}
}
}
if (_startupCoroutine != null)
ServerMgr.Instance.StopCoroutine(_startupCoroutine);
OnServerSave();
_triggerManager.DestroyAll();
_trainManager.Unload();
_pluginInstance = null;
}
private void OnServerSave()
{
if (_trainManager.UpdateTrainEngineData())
{
_pluginData.Save();
}
else
{
_pluginData.SaveIfDirty();
}
}
private void OnNewSave()
{
_pluginData = StoredPluginData.Clear();
}
private void OnPlayerConnected(BasePlayer player)
{
if (player.IsReceivingSnapshot)
{
timer.Once(1f, () => OnPlayerConnected(player));
return;
}
_trainManager.ResendAllGenericMarkers();
}
private void OnEntitySpawned(TrainCar trainCar)
{
EnableTerrainCollision(trainCar, false);
}
private object OnTrainCarUncouple(TrainCar trainCar, BasePlayer player)
{
// Disallow uncoupling train cars from automated trains.
return _trainManager.HasTrainController(trainCar)
? False
: null;
}
#endregion
#region Commands
[Command("aw.toggle")]
private void CommandAutomateTrain(IPlayer player, string cmd, string[] args)
{
if (player.IsServer
|| !VerifyPermission(player, PermissionToggle))
return;
var basePlayer = player.Object as BasePlayer;
var trainCar = GetTrainCarWhereAiming(basePlayer);
if (trainCar == null)
{
ReplyToPlayer(player, Lang.ErrorNoWorkcartFound);
return;
}
var trainController = _trainManager.GetTrainController(trainCar);
if (trainController == null)
{
var leadTrainEngine = GetLeadTrainEngine(trainCar);
if (leadTrainEngine == null)
{
ReplyToPlayer(player, Lang.ErrorNoWorkcart);
return;
}
if (IsTrainOwned(trainCar))
{
ReplyToPlayer(player, Lang.ErrorWorkcartOwned);
return;
}
if (!_trainManager.CanHaveMoreConductors(trainCar))
{
ReplyToPlayer(player, Lang.ErrorMaxConductors, _trainManager.CountedConductors, _pluginConfig.MaxConductors);
return;
}
TrainEngineData trainEngineData = null;
if (args.Length > 0)
{
var routeName = GetRouteNameFromArg(player, args[0], requirePrefix: false);
if (!string.IsNullOrWhiteSpace(routeName))
{
trainEngineData = new TrainEngineData { Route = routeName };
}
}
if (_trainManager.TryCreateTrainController(leadTrainEngine, trainEngineData: trainEngineData))
{
var baseMessage = trainEngineData != null
? GetMessage(player, Lang.ToggleOnWithRouteSuccess, trainEngineData.Route)
: GetMessage(player, Lang.ToggleOnSuccess);
player.Reply(baseMessage + " " + GetConductorCountMessage(player));
if (player.HasPermission(PermissionManageTriggers))
{
if (trainEngineData?.Route != null)
_triggerManager.SetPlayerDisplayedRoute(basePlayer, trainEngineData.Route);
_triggerManager.ShowAllRepeatedly(basePlayer);
}
}
else
{
ReplyToPlayer(player, Lang.ErrorAutomateBlocked);
}
}
else
{
_trainManager.KillTrainController(trainCar);
player.Reply(GetMessage(player, Lang.ToggleOffSuccess) + " " + GetConductorCountMessage(player));
}
}
[Command("aw.resetall")]
private void CommandResetTrains(IPlayer player, string cmd, string[] args)
{
if (!player.IsServer
&& !VerifyPermission(player, PermissionToggle))
return;
var trainCount = _trainManager.ResetAll();
ReplyToPlayer(player, Lang.ResetAllSuccess, trainCount);
}
[Command("aw.addtrigger", "awt.add")]
private void CommandAddTrigger(IPlayer player, string cmd, string[] args)
{
if (player.IsServer
|| !VerifyPermission(player, PermissionManageTriggers))
return;
if (!_pluginConfig.EnableMapTriggers)
{
ReplyToPlayer(player, Lang.ErrorMapTriggersDisabled);
return;
}
Vector3 trackPosition;
if (!TryGetTrackPosition(player.Object as BasePlayer, out trackPosition))
{
ReplyToPlayer(player, Lang.ErrorNoTrackFound);
return;
}
var triggerData = new TriggerData() { Position = trackPosition };
AddTriggerShared(player, cmd, args, triggerData);
}
[Command("aw.addtunneltrigger", "awt.addt")]
private void CommandAddTunnelTrigger(IPlayer player, string cmd, string[] args)
{
if (player.IsServer
|| !VerifyPermission(player, PermissionManageTriggers))
return;
Vector3 trackPosition;
if (!TryGetTrackPosition(player.Object as BasePlayer, out trackPosition))
{
ReplyToPlayer(player, Lang.ErrorNoTrackFound);
return;
}
DungeonCellWrapper dungeonCellWrapper;
if (!VerifySupportedNearbyTrainTunnel(player, trackPosition, out dungeonCellWrapper))
return;
if (!_pluginConfig.IsTunnelTypeEnabled(dungeonCellWrapper.TunnelType))
{
ReplyToPlayer(player, Lang.ErrorTunnelTypeDisabled, dungeonCellWrapper.TunnelType);
return;
}
var triggerData = new TriggerData()
{
TunnelType = dungeonCellWrapper.TunnelType.ToString(),
Position = dungeonCellWrapper.InverseTransformPoint(trackPosition),
};
AddTriggerShared(player, cmd, args, triggerData, dungeonCellWrapper);
}
private void AddTriggerShared(IPlayer player, string cmd, string[] args, TriggerData triggerData, DungeonCellWrapper dungeonCellWrapper = null)
{
foreach (var arg in args)
{
if (!VerifyValidArgAndModifyTrigger(player, cmd, arg, triggerData, Lang.AddTriggerSyntax))
return;
}
if (!triggerData.IsSpawner
&& !triggerData.AddConductor
&& !triggerData.Destroy
&& triggerData.GetTrackSelectionInstruction() == null
&& triggerData.GetSpeedInstruction() == null
&& triggerData.GetDirectionInstruction() == null)
{
triggerData.Speed = EngineSpeeds.Zero.ToString();
}
var basePlayer = player.Object as BasePlayer;
if (triggerData.IsSpawner)
{
var rotation = Quaternion.Euler(basePlayer.viewAngles);
if (dungeonCellWrapper != null)
{
rotation *= Quaternion.Inverse(dungeonCellWrapper.Rotation);
}
triggerData.RotationAngle = rotation.eulerAngles.y % 360;
}
_triggerManager.AddTrigger(triggerData);
if (triggerData.Route != null)
_triggerManager.SetPlayerDisplayedRoute(basePlayer, triggerData.Route);
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.AddTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.updatetrigger", "awt.update")]
private void CommandUpdateTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.UpdateTriggerSyntax, out triggerData, out optionArgs))
return;
if (optionArgs.Length == 0)
{
ReplyToPlayer(player, Lang.UpdateTriggerSyntax, cmd, GetTriggerOptions(player));
return;
}
var newTriggerData = triggerData.Clone();
foreach (var arg in optionArgs)
{
if (!VerifyValidArgAndModifyTrigger(player, cmd, arg, newTriggerData, Lang.UpdateTriggerSyntax))
return;
}
_triggerManager.UpdateTrigger(triggerData, newTriggerData);
var basePlayer = player.Object as BasePlayer;
if (triggerData.Route != null)
_triggerManager.SetPlayerDisplayedRoute(basePlayer, triggerData.Route);
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.replacetrigger", "awt.replace")]
private void CommandReplaceTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.UpdateTriggerSyntax, out triggerData, out optionArgs))
return;
if (optionArgs.Length == 0)
{
ReplyToPlayer(player, Lang.UpdateTriggerSyntax, cmd, GetTriggerOptions(player));
return;
}
var newTriggerData = new TriggerData();
foreach (var arg in optionArgs)
{
if (!VerifyValidArgAndModifyTrigger(player, cmd, arg, newTriggerData, Lang.UpdateTriggerSyntax))
return;
}
_triggerManager.UpdateTrigger(triggerData, newTriggerData);
var basePlayer = player.Object as BasePlayer;
if (triggerData.Route != null)
_triggerManager.SetPlayerDisplayedRoute(basePlayer, triggerData.Route);
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.enabletrigger", "awt.enable")]
private void CommandEnableTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
var newTriggerData = triggerData.Clone();
newTriggerData.Enabled = true;
_triggerManager.UpdateTrigger(triggerData, newTriggerData);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.disabletrigger", "awt.disable")]
private void CommandDisableTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
var newTriggerData = triggerData.Clone();
newTriggerData.Enabled = false;
_triggerManager.UpdateTrigger(triggerData, newTriggerData);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.movetrigger", "awt.move")]
private void CommandMoveTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
Vector3 trackPosition;
if (!VerifyTrackPosition(player, out trackPosition))
return;
if (triggerData.TriggerType == TrainTriggerType.Tunnel)
{
DungeonCellWrapper dungeonCellWrapper;
if (!VerifySupportedNearbyTrainTunnel(player, trackPosition, out dungeonCellWrapper))
return;
if (dungeonCellWrapper.TunnelType != triggerData.GetTunnelType())
{
ReplyToPlayer(player, Lang.ErrorUnsupportedTunnel);
return;
}
trackPosition = dungeonCellWrapper.InverseTransformPoint(trackPosition);
}
_triggerManager.MoveTrigger(triggerData, trackPosition);
var basePlayer = player.Object as BasePlayer;
if (triggerData.Route != null)
_triggerManager.SetPlayerDisplayedRoute(basePlayer, triggerData.Route);
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.MoveTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.removetrigger", "awt.remove")]
private void CommandRemoveTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
_triggerManager.RemoveTrigger(triggerData);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.RemoveTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.rotatetrigger", "awt.rotate")]
private void CommandSetTriggerRotation(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
var basePlayer = player.Object as BasePlayer;
var playerPosition = basePlayer.transform.position;
var triggerInstance = _triggerManager.FindNearestTrigger(playerPosition, triggerData);
var rotation = Quaternion.Euler(basePlayer.viewAngles);
var tunnelTriggerInstance = triggerInstance as TunnelTriggerInstance;
if (tunnelTriggerInstance != null)
{
rotation *= Quaternion.Inverse(tunnelTriggerInstance.DungeonCellWrapper.Rotation);
}
_triggerManager.RotateTrigger(triggerData, rotation.eulerAngles.y % 360);
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.RotateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.respawntrigger", "awt.respawn")]
private void CommandRespawnTrigger(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.SimpleTriggerSyntax, out triggerData, out optionArgs))
return;
if (!triggerData.IsSpawner)
{
ReplyToPlayer(player, Lang.ErrorRequiresSpawnTrigger);
return;
}
if (!triggerData.Enabled)
{
ReplyToPlayer(player, Lang.ErrorTriggerDisabled);
return;
}
_triggerManager.RespawnTrigger(triggerData);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
}
[Command("aw.addtriggercommand", "awt.addcommand", "awt.addcmd")]
private void CommandAddCommand(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.AddCommandSyntax, out triggerData, out optionArgs))
return;
if (optionArgs.Length < 1)
{
ReplyToPlayer(player, Lang.AddCommandSyntax, cmd);
return;
}
var quotedCommands = optionArgs.Select(command => command.Contains(" ") ? $"\"{command}\"" : command).ToArray();
_triggerManager.AddTriggerCommand(triggerData, string.Join(" ", quotedCommands));
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.removetriggercommand", "awt.removecommand", "awt.removecmd")]
private void CommandRemoveCommand(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.RemoveCommandSyntax, out triggerData, out optionArgs))
return;
int commandIndex;
if (optionArgs.Length < 1 || !int.TryParse(optionArgs[0], out commandIndex))
{
ReplyToPlayer(player, Lang.RemoveCommandSyntax, cmd);
return;
}
if (commandIndex < 1 || commandIndex > triggerData.Commands.Count)
{
ReplyToPlayer(player, Lang.RemoveCommandErrorIndex, commandIndex);
return;
}
_triggerManager.RemoveTriggerCommand(triggerData, commandIndex - 1);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.settriggertrain", "awt.train")]
private void CommandTriggerTrain(IPlayer player, string cmd, string[] args)
{
TriggerData triggerData;
string[] optionArgs;
if (!VerifyCanModifyTrigger(player, cmd, args, Lang.RemoveCommandSyntax, out triggerData, out optionArgs))
return;
var trainCarAliases = new List<string>();
foreach (var arg in optionArgs)
{
var trainCarPrefab = TrainCarPrefab.FindPrefab(arg);
if (trainCarPrefab == null)
{
ReplyToPlayer(player, Lang.ErrorUnrecognizedTrainCar, arg);
return;
}
trainCarAliases.Add(trainCarPrefab.TrainCarAlias);
}
var newTriggerData = triggerData.Clone();
newTriggerData.TrainCars = trainCarAliases.ToArray();
_triggerManager.UpdateTrigger(triggerData, newTriggerData);
var basePlayer = player.Object as BasePlayer;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, Lang.UpdateTriggerSuccess, GetTriggerPrefix(player, triggerData), triggerData.Id);
}
[Command("aw.showtriggers", "awt.show")]
private void CommandShowStops(IPlayer player, string cmd, string[] args)
{
if (player.IsServer
|| !VerifyPermission(player, PermissionManageTriggers)
|| !VerifyAnyTriggers(player))
return;
int duration = 60;
string routeName = null;
foreach (var arg in args)
{
if (duration == 60)
{
int argIntValue;
if (int.TryParse(arg, out argIntValue))
{
duration = argIntValue;
continue;
}
}
if (routeName == null)
{
var routeNameArg = GetRouteNameFromArg(player, arg, requirePrefix: false);
if (!string.IsNullOrWhiteSpace(routeNameArg))
routeName = routeNameArg;
}
}
var basePlayer = player.Object as BasePlayer;
_triggerManager.SetPlayerDisplayedRoute(basePlayer, routeName);
_triggerManager.ShowAllRepeatedly(basePlayer, duration);
if (routeName != null)
ReplyToPlayer(player, Lang.ShowTriggersWithRouteSuccess, routeName, FormatTime(duration));
else
ReplyToPlayer(player, Lang.ShowTriggersSuccess, FormatTime(duration));
}
#endregion
#region API
[HookMethod("API_AutomateWorkcart")]
private bool API_AutomateWorkcart(TrainEngine trainEngine)
{
return _trainManager.HasTrainController(trainEngine)
? true
: _trainManager.TryCreateTrainController(trainEngine);
}
[HookMethod("API_StopAutomatingWorkcart")]
private void API_StopAutomatingWorkcart(TrainEngine trainEngine, bool immediate = false)
{
_trainManager.KillTrainController(trainEngine);
}
[HookMethod("API_IsWorkcartAutomated")]
private bool API_IsWorkcartAutomated(TrainEngine trainEngine)
{
return _trainManager.HasTrainController(trainEngine);
}
[HookMethod("API_GetAutomatedWorkcarts")]
private TrainEngine[] API_GetAutomatedWorkcarts()
{
return _trainManager.GetAutomatedTrainEngines();
}
#endregion
#region Exposed Hooks
private static class ExposedHooks
{
public static object OnWorkcartAutomationStart(TrainEngine trainEngine)
{
return Interface.CallHook("OnWorkcartAutomationStart", trainEngine);
}
public static void OnWorkcartAutomationStarted(TrainEngine trainEngine)
{
Interface.CallHook("OnWorkcartAutomationStarted", trainEngine);
}
public static void OnWorkcartAutomationStopped(TrainEngine trainEngine)
{
Interface.CallHook("OnWorkcartAutomationStopped", trainEngine);
}
}
#endregion
#region Dependencies
private bool IsCargoTrain(TrainEngine trainEngine)
{
var result = CargoTrainEvent?.Call("IsTrainSpecial", trainEngine.net.ID);
return result is bool && (bool)result;
}
#endregion
#region Helper Methods - Command Checks
private bool VerifyPermission(IPlayer player, string permissionName)
{
if (player.HasPermission(permissionName))
return true;
ReplyToPlayer(player, Lang.ErrorNoPermission);
return false;
}
private bool VerifyAnyTriggers(IPlayer player)
{
if (_mapData.MapTriggers.Count > 0
|| _tunnelData.TunnelTriggers.Count > 0)
return true;
ReplyToPlayer(player, Lang.ErrorNoTriggers);
return false;
}
private bool VerifyTriggerExists(IPlayer player, int triggerId, TrainTriggerType triggerType, out TriggerData triggerData)
{
triggerData = _triggerManager.FindTrigger(triggerId, triggerType);
if (triggerData != null)
return true;
_triggerManager.ShowAllRepeatedly(player.Object as BasePlayer);
ReplyToPlayer(player, Lang.ErrorTriggerNotFound, GetTriggerPrefix(player, triggerType), triggerId);
return false;
}
private bool VerifyTrackPosition(IPlayer player, out Vector3 trackPosition)
{
if (TryGetTrackPosition(player.Object as BasePlayer, out trackPosition))
return true;
ReplyToPlayer(player, Lang.ErrorNoTrackFound);
return false;
}
private bool IsTriggerArg(IPlayer player, string arg, out int triggerId, out TrainTriggerType triggerType)
{
triggerType = TrainTriggerType.Map;
triggerId = 0;
if (arg.StartsWith("#"))
arg = arg.Substring(1);
if (arg.Length <= 1)
return false;
var triggerPrefix = arg.Substring(0, 1).ToLower();
var triggerIdString = arg.Substring(1).ToLower();
if (!int.TryParse(triggerIdString, out triggerId))
return false;
if (triggerPrefix == GetTriggerPrefix(player, TrainTriggerType.Tunnel).ToLower())
{
triggerType = TrainTriggerType.Tunnel;
return true;
}
else if (triggerPrefix == GetTriggerPrefix(player, TrainTriggerType.Map).ToLower())
{
triggerType = TrainTriggerType.Map;
return true;
}
return false;
}
private bool VerifyTriggerWhereAiming(IPlayer player, string cmd, string[] args, string errorMessageName, out TriggerData triggerData, out string[] optionArgs)
{
var basePlayer = player.Object as BasePlayer;
optionArgs = args;
triggerData = null;
triggerData = _triggerManager.FindNearestTriggerWhereAiming(basePlayer);
if (triggerData != null)
return true;
_triggerManager.ShowAllRepeatedly(basePlayer);
ReplyToPlayer(player, errorMessageName, cmd, GetTriggerOptions(player));
return false;
}
private bool VerifyCanModifyTrigger(IPlayer player, string cmd, string[] args, string errorMessageName, out TriggerData triggerData, out string[] optionArgs)
{
triggerData = null;
optionArgs = null;
if (!VerifyPermission(player, PermissionManageTriggers)
|| !VerifyAnyTriggers(player))
return false;
int triggerId;
TrainTriggerType triggerType;
if (args.Length > 0 && IsTriggerArg(player, args[0], out triggerId, out triggerType))
{
optionArgs = args.Skip(1).ToArray();
return VerifyTriggerExists(player, triggerId, triggerType, out triggerData);
}
if (player.IsServer)
{
// Server commands must specify a trigger id.
ReplyToPlayer(player, errorMessageName, cmd, GetTriggerOptions(player));
return false;
}
return VerifyTriggerWhereAiming(player, cmd, args, errorMessageName, out triggerData, out optionArgs);
}
private bool VerifySupportedNearbyTrainTunnel(IPlayer player, Vector3 trackPosition, out DungeonCellWrapper dungeonCellWrapper)
{
dungeonCellWrapper = FindNearestDungeonCell(trackPosition);
if (dungeonCellWrapper == null || dungeonCellWrapper.TunnelType == TunnelType.Unsupported)
{
ReplyToPlayer(player, Lang.ErrorUnsupportedTunnel);
return false;
}
return true;
}
private string GetRouteNameFromArg(IPlayer player, string routeName, bool requirePrefix = true)
{
if (routeName.StartsWith("@"))
return routeName.Substring(1);
return requirePrefix ? null : routeName;
}
private bool VerifyValidArgAndModifyTrigger(IPlayer player, string cmd, string arg, TriggerData triggerData, string errorMessageName)
{
var argLower = arg.ToLower();
if (argLower == "start" || argLower == "conductor")
{
triggerData.AddConductor = true;
return true;
}
if (argLower.StartsWith("brake"))
{
triggerData.Brake = true;
return true;
}
if (argLower.StartsWith("destroy"))
{
triggerData.Destroy = true;
return true;
}
if (argLower.StartsWith("enable"))
{
triggerData.Enabled = true;
return true;
}
if (argLower.StartsWith("disable"))
{
triggerData.Enabled = false;
return true;
}
var prefab = TrainCarPrefab.FindPrefab(argLower);
if (prefab != null)
{
if (triggerData.TrainCars == null)
{
triggerData.TrainCars = new string[] { prefab.TrainCarAlias };
}
else
{
var length = triggerData.TrainCars.Length;
Array.Resize(ref triggerData.TrainCars, length + 1);
triggerData.TrainCars[length] = prefab.TrainCarAlias;
}
return true;
}
float stopDuration;
if (float.TryParse(arg, out stopDuration))
{
triggerData.StopDuration = stopDuration;
return true;
}
var routeName = GetRouteNameFromArg(player, arg, requirePrefix: true);
if (!string.IsNullOrWhiteSpace(routeName))
{
triggerData.Route = routeName;
return true;
}
SpeedInstruction speedInstruction;
if (Enum.TryParse<SpeedInstruction>(arg, true, out speedInstruction))
{
var speedString = speedInstruction.ToString();
// If zero speed is already set, assume this is the departure speed.
if (triggerData.Speed == SpeedInstruction.Zero.ToString())
triggerData.DepartureSpeed = speedString;
else
triggerData.Speed = speedString;
return true;
}
DirectionInstruction directionInstruction;
if (Enum.TryParse<DirectionInstruction>(arg, true, out directionInstruction))
{
triggerData.Direction = directionInstruction.ToString();
return true;
}
TrackSelectionInstruction trackSelectionInstruction;
if (Enum.TryParse<TrackSelectionInstruction>(arg, true, out trackSelectionInstruction))
{
triggerData.TrackSelection = trackSelectionInstruction.ToString();
return true;
}
ReplyToPlayer(player, errorMessageName, cmd, GetTriggerOptions(player));
return false;
}
#endregion
#region Helper Methods - Coupling
private static void UpdateAllowedCouplings(TrainCar trainCar, bool allowFront, bool allowRear)
{
var coupling = trainCar.coupling;
var frontCoupling = coupling.frontCoupling;
var rearCoupling = coupling.rearCoupling;
if (trainCar.frontCoupling == null || trainCar.rearCoupling == null)
{
// Some train cars do not allow coupling, such as the classic workcart.
return;
}
if (!allowFront && frontCoupling.IsCoupled)
{