-
Notifications
You must be signed in to change notification settings - Fork 1
/
HeliControl.cs
2075 lines (1899 loc) · 98.2 KB
/
HeliControl.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 Oxide.Core;
using System;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Oxide.Core.Plugins;
using System.Text;
using Newtonsoft.Json;
using Oxide.Core.Libraries.Covalence;
using System.Diagnostics;
namespace Oxide.Plugins
{
[Info("HeliControl", "Shady", "1.4.0", ResourceId = 1348)]
[Description("Tweak various settings of helicopters.")]
class HeliControl : RustPlugin
{
#region Config/Init
StoredData lootData = new StoredData();
StoredData2 weaponsData = new StoredData2();
StoredData3 cooldownData = new StoredData3();
StoredData4 spawnsData = new StoredData4();
private float boundary;
private HashSet<BaseHelicopter> BaseHelicopters = new HashSet<BaseHelicopter>();
private HashSet<CH47HelicopterAIController> Chinooks = new HashSet<CH47HelicopterAIController>();
private HashSet<CargoShip> CargoShips = new HashSet<CargoShip>();
private HashSet<HelicopterDebris> Gibs = new HashSet<HelicopterDebris>();
private HashSet<FireBall> FireBalls = new HashSet<FireBall>();
private HashSet<BaseHelicopter> forceCalled = new HashSet<BaseHelicopter>();
private HashSet<CH47HelicopterAIController> forceCalledCH = new HashSet<CH47HelicopterAIController>();
private HashSet<CargoShip> forceCalledShip = new HashSet<CargoShip>();
private HashSet<LockedByEntCrate> lockedCrates = new HashSet<LockedByEntCrate>();
private HashSet<HackableLockedCrate> hackLockedCrates = new HashSet<HackableLockedCrate>();
private Dictionary<BaseHelicopter, int> strafeCount = new Dictionary<BaseHelicopter, int>();
FieldInfo tooHotUntil = typeof(HelicopterDebris).GetField("tooHotUntil", (BindingFlags.Instance | BindingFlags.NonPublic));
bool init = false;
private static System.Random rng = new System.Random(); //used for loot crates, better alternative
private readonly int groundLayer = LayerMask.GetMask("Terrain", "World", "Default");
private readonly string heliPrefab = "assets/prefabs/npc/patrol helicopter/patrolhelicopter.prefab";
private readonly string chinookPrefab = "assets/prefabs/npc/ch47/ch47scientists.entity.prefab";
private readonly string cargoshipPrefab = "assets/content/vehicles/boats/cargoship/cargoshiptest.prefab";
bool DisableHeli;
bool DisableDefaultHeliSpawns;
bool DisableDefaultChinookSpawns;
bool DisableDefaultCargoShipSpawns;
bool UseCustomLoot;
bool DisableGibs;
bool DisableNapalm;
bool AutoCallIfExists;
bool AutoCallIfExistsCH47;
bool AutoCallIfExistsShip;
bool DisableCratesDeath;
bool HelicopterCanShootWhileDying;
bool UseCustomHeliSpawns;
bool UseOldSpawning;
float GlobalDamageMultiplier;
float HeliBulletDamageAmount;
float MainRotorHealth;
float TailRotorHealth;
float BaseHealth;
float HeliSpeed;
float HeliStartSpeed;
float HeliStartLength;
float HeliAccuracy;
float TimeBeforeUnlocking;
float TimeBeforeUnlockingHack;
float TurretFireRate;
float TurretburstLength;
float TurretTimeBetweenBursts;
float TurretMaxRange;
float GibsTooHotLength;
float GibsHealth;
float TimeBetweenRockets;
float MinSpawnTime;
float MinSpawnTimeCH47;
float MinSpawnTimeShip;
float MaxSpawnTime;
float MaxSpawnTimeCH47;
float MaxSpawnTimeShip;
float RocketDamageBlunt;
float RocketDamageExplosion;
float RocketExplosionRadius;
int MaxLootCrates;
int MaxHeliRockets;
int BulletSpeed;
int LifeTimeMinutes;
int WaterRequired;
int MaxActiveHelicopters;
Dictionary<string, object> cds => GetConfig("Cooldowns", new Dictionary<string, object>());
Dictionary<string, object> limits => GetConfig("Limits", new Dictionary<string, object>());
[PluginReference]
Plugin Vanish;
private Timer CallTimer;
private Timer CallTimerCH47;
private Timer CallTimerShip;
private BaseHelicopter TimerHeli;
private CH47HelicopterAIController TimerCH47;
private CargoShip TimerShip;
protected override void LoadDefaultConfig()
{
Config["Spawning - Disable Helicopter"] = DisableHeli = GetConfig("Spawning - Disable Helicopter", false);
Config["Spawning - Disable Rust's default spawns"] = DisableDefaultHeliSpawns = GetConfig("Spawning - Disable Rust's default spawns", false);
Config["Spawning - Disable CH47 default spawns"] = DisableDefaultChinookSpawns = GetConfig("Spawning - Disable CH47 default spawns", false);
Config["Spawning - Disable CargoShip default spawns"] = DisableDefaultCargoShipSpawns = GetConfig("Spawning - Disable CargoShip default spawns", false);
Config["Loot - Use Custom loot spawns"] = UseCustomLoot = GetConfig("Loot - Use Custom loot spawns", false);
Config["Damage - Global damage multiplier"] = GlobalDamageMultiplier = GetConfig("Damage - Global damage multiplier", 1f);
Config["Turrets - Helicopter bullet damage"] = HeliBulletDamageAmount = GetConfig("Turrets - Helicopter bullet damage", 20f);
Config["Misc - Helicopter can shoot while dying"] = HelicopterCanShootWhileDying = GetConfig("Misc - Helicopter can shoot while dying", true);
Config["Health - Main rotor health"] = MainRotorHealth = GetConfig("Health - Main rotor health", 750f);
Config["Health - Tail rotor health"] = TailRotorHealth = GetConfig("Health - Tail rotor health", 375f);
Config["Health - Base Helicopter health"] = BaseHealth = GetConfig("Health - Base Helicopter health", 10000f);
Config["Loot - Max Crates to drop"] = MaxLootCrates = GetConfig("Loot - Max Crates to drop", 4);
Config["Misc - Helicopter speed"] = HeliSpeed = GetConfig("Misc - Helicopter speed", 25f);
Config["Turrets - Helicopter bullet accuracy"] = HeliAccuracy = GetConfig("Turrets - Helicopter bullet accuracy", 2f);
Config["Rockets - Max helicopter rockets"] = MaxHeliRockets = GetConfig("Rockets - Max helicopter rockets", 12);
Config["Spawning - Disable helicopter gibs"] = DisableGibs = GetConfig("Spawning - Disable helicopter gibs", false);
Config["Spawning - Disable helicopter napalm"] = DisableNapalm = GetConfig("Spawning - Disable helicopter napalm", false);
Config["Turrets - Helicopter bullet speed"] = BulletSpeed = GetConfig("Turrets - Helicopter bullet speed", 250);
Config["Loot - Time before unlocking crates"] = TimeBeforeUnlocking = GetConfig("Loot - Time before unlocking crates", -1f);
Config["Loot - Time before unlocking CH47 crates"] = TimeBeforeUnlockingHack = GetConfig("Loot - Time before unlocking CH47 crates", -1f);
Config["Misc - Maximum helicopter life time in minutes"] = LifeTimeMinutes = GetConfig("Misc - Maximum helicopter life time in minutes", 15);
Config["Rockets - Time between each rocket in seconds"] = TimeBetweenRockets = GetConfig("Rockets - Time between each rocket in seconds", 0.2f);
Config["Turrets - Turret fire rate in seconds"] = TurretFireRate = GetConfig("Turrets - Fire rate in seconds", 0.125f);
Config["Turrets - Turret burst length in seconds"] = TurretburstLength = GetConfig("Turrets - Burst length in seconds", 3f);
Config["Turrets - Time between turret bursts in seconds"] = TurretTimeBetweenBursts = GetConfig("Turrets - Time between turret bursts in seconds", 3f);
Config["Turrets - Max range"] = TurretMaxRange = GetConfig("Turrets - Max range", 300f);
Config["Rockets - Blunt damage to deal"] = RocketDamageBlunt = GetConfig("Rockets - Blunt damage to deal", 175f);
Config["Rockets - Explosion damage to deal"] = RocketDamageExplosion = GetConfig("Rockets - Explosion damage to deal", 100f);
Config["Rockets - Explosion radius"] = RocketExplosionRadius = GetConfig("Rockets - Explosion radius", 6f);
Config["Gibs - Time until gibs can be harvested in seconds"] = GibsTooHotLength = GetConfig("Gibs - Time until gibs can be harvested in seconds", 480f);
Config["Gibs - Health of gibs"] = GibsHealth = GetConfig("Gibs - Health of gibs", 500f);
Config["Spawning - Automatically call helicopter between min seconds"] = MinSpawnTime = GetConfig("Spawning - Automatically call helicopter between min seconds", 0f);
Config["Spawning - Automatically call helicopter between max seconds"] = MaxSpawnTime = GetConfig("Spawning - Automatically call helicopter between max seconds", 0f);
Config["Spawning - Automatically call CH47 between min seconds"] = MinSpawnTimeCH47 = GetConfig("Spawning - Automatically call CH47 between min seconds", 0f);
Config["Spawning - Automatically call CH47 between max seconds"] = MaxSpawnTimeCH47 = GetConfig("Spawning - Automatically call CH47 between max seconds", 0f);
Config["Spawning - Automatically call CargoShip between min seconds"] = MinSpawnTimeShip = GetConfig("Spawning - Automatically call CargoShip between min seconds", 0f);
Config["Spawning - Automatically call CargoShip between max seconds"] = MaxSpawnTimeShip = GetConfig("Spawning - Automatically call CargoShip between max seconds", 0f);
Config["Spawning - Use static spawning"] = UseOldSpawning = GetConfig("Spawning - Use static spawning", false);
Config["Spawning - Automatically call helicopter if one is already flying"] = AutoCallIfExists = GetConfig("Spawning - Automatically call helicopter if one is already flying", false);
Config["Spawning - Automatically call CH47 if one is already flying"] = AutoCallIfExistsCH47 = GetConfig("Spawning - Automatically call CH47 if one is already flying", false);
Config["Spawning - Automatically call CargoShip if one is already active"] = AutoCallIfExistsShip = GetConfig("Spawning - Automatically call CargoShip if one is already active", false);
Config["Misc - Water required to extinguish napalm flames"] = WaterRequired = GetConfig("Misc - Water required to extinguish napalm flames", 10000);
Config["Spawning - Use custom helicopter spawns"] = UseCustomHeliSpawns = GetConfig("Spawning - Use custom helicopter spawns", false);
Config["Misc - Helicopter startup speed"] = HeliStartSpeed = GetConfig("Misc - Helicopter startup speed", 25f);
Config["Misc - Helicopter startup length in seconds"] = HeliStartLength = GetConfig("Misc - Helicopter startup length in seconds", 0f);
Config["Misc - Prevent crates from spawning when forcefully killing helicopter"] = DisableCratesDeath = GetConfig("Misc - Prevent crates from spawning when forcefully killing helicopter", true);
Config["Spawning - Max active helicopters"] = MaxActiveHelicopters = GetConfig("Spawning - Max active helicopters", -1);
for (int i = 0; i < 10; i++)
{
object outObj;
if (!cds.TryGetValue("Cooldown." + i, out outObj)) cds["Cooldown." + i] = 86400f;
if (!limits.TryGetValue("Limit." + i, out outObj)) limits["Limit." + i] = 5;
if (!cds.TryGetValue("cooldown.ch47." + i, out outObj)) cds["cooldown.ch47." + i] = 86400f;
if (!limits.TryGetValue("limit.ch47." + i, out outObj)) limits["limit.ch47." + i] = 5;
}
Config["Cooldowns"] = cds;
Config["Limits"] = limits;
SaveConfig();
}
void Init()
{
cooldownData = Interface.GetMod()?.DataFileSystem?.ReadObject<StoredData3>("HeliControlCooldowns");
if (cooldownData == null) cooldownData = new StoredData3();
LoadDefaultConfig();
Config["Cooldowns"] = cds; // unsure if needed
Config["Limits"] = limits;
SaveConfig();
string[] perms = { "callheli", "callheliself", "callhelitarget", "callch47", "callch47self", "callch47target", "killch47", "killheli", "strafe", "update", "destination", "dropcrate", "killnapalm", "killgibs", "unlockcrates", "admin", "ignorecooldown", "ignorelimits", "tpheli", "tpch47", "helispawn", "callmultiple", "callmultiplech47", "nodrop" };
for (int j = 0; j < perms.Length; j++) permission.RegisterPermission("helicontrol." + perms[j], this);
foreach (var limit in limits.Keys) permission.RegisterPermission("helicontrol." + limit, this);
foreach (var cd in cds.Keys) permission.RegisterPermission("helicontrol." + cd, this);
if (HelicopterCanShootWhileDying)
{
Unsubscribe(nameof(CanBeTargeted));
Unsubscribe(nameof(OnHelicopterTarget));
Unsubscribe(nameof(CanHelicopterStrafeTarget));
Unsubscribe(nameof(CanHelicopterStrafe));
Unsubscribe(nameof(CanHelicopterTarget));
}
AddCovalenceCommand("unlockcrates", "cmdUnlockCrates");
AddCovalenceCommand("tpheli", "cmdTeleportHeli");
AddCovalenceCommand("killheli", "cmdKillHeli");
AddCovalenceCommand("killch47", "cmdKillCH47");
AddCovalenceCommand("dropcrate", "cmdDropCH47Crate");
AddCovalenceCommand("updatehelis", "cmdUpdateHelicopters");
AddCovalenceCommand("strafe", "cmdStrafeHeli");
AddCovalenceCommand("helidest", "cmdDestChangeHeli");
AddCovalenceCommand("killnapalm", "cmdKillFB");
AddCovalenceCommand("killgibs", "cmdKillGibs");
LoadDefaultMessages();
}
protected override void LoadDefaultMessages()
{
var messages = new Dictionary<string, string>
{
//DO NOT EDIT LANGUAGE FILES HERE! Navigate to oxide\lang
{"noPerms", "You do not have permission to use this command!"},
{"invalidSyntax", "Invalid Syntax, usage example: {0} {1}"},
{"invalidSyntaxMultiple", "Invalid Syntax, usage example: {0} {1} or {2} {3}"},
{"heliCalled", "Helicopter Inbound!"},
{"helisCalledPlayer", "{0} Helicopter(s) called on: {1}"},
{"entityDestroyed", "{0} {1}(s) were annihilated!"},
{"helisForceDestroyed", "{0} Helicopter(s) were forcefully destroyed!"},
{"heliAutoDestroyed", "Helicopter auto-destroyed because config has it disabled!" },
{"playerNotFound", "Could not find player: {0}"},
{"noHelisFound", "No active helicopters were found!"},
{"cannotBeCalled", "This can only be called on a single Helicopter, there are: {0} active."},
{"strafingOtherPosition", "Helicopter is now strafing {0}'s position."},
{"destinationOtherPosition", "Helicopter's destination has been set to {0}'s position."},
{"IDnotFound", "Could not find player by ID: {0}" },
{"updatedHelis", "{0} helicopters were updated successfully!" },
{"callheliCooldown", "You must wait before using this again! You've waited: {0}/{1}" },
{"invalidCoordinate", "Incorrect argument supplied for {0} coordinate!" },
{"coordinatesOutOfBoundaries", "Coordinates are out of map boundaries!" },
{"callheliLimit", "You've used your daily limit of {0} heli calls!" },
{"unlockedAllCrates", "Unlocked all Helicopter crates!" },
{"teleportedToHeli", "You've been teleported to the ground below the active Helicopter!" },
{"removeAddSpawn", "To remove a Spawn, type: /helispawn remove SpawnName\n\nTo add a Spawn, type: /helispawn add SpawnName -- This will add the spawn on your current position." },
{"addedSpawn", "Added helicopter spawn {0} with the position of: {1}" },
{"spawnExists", "A spawn point with this name already exists!" },
{"noSpawnsExist", "No Helicopter spawns have been created!" },
{"removedSpawn", "Removed Helicopter spawn point: {0}: {1}" },
{"noSpawnFound", "No spawn could be found with that name!" },
{"onlyCallSelf", "You can only call a Helicopter on yourself, try: /callheli {0}" },
{"spawnCommandLiner", "<color=orange>----</color>Spawns<color=orange>----</color>\n" },
{"spawnCommandBottom", "\n<color=orange>----------------</color>" },
{"cantCallTargetOrSelf", "You do not have the permission to call a Helicopter on a target! Try: /callheli" },
{"maxHelis", "Killing helicopter because the maximum active helicopters has been reached" },
{"cmdError", "An error happened while using this command. Please report this to your server administrator." },
{"ch47AlreadyDropped", "This CH47 has already dropped a crate!" },
{"ch47DroppedCrate", "Dropped crate!" },
{"itemNotFound", "Item not found!" },
{"shipCalled", "CargoShip inbound!" },
};
lang.RegisterMessages(messages, this);
}
private string GetMessage(string key, string steamId = null) => lang.GetMessage(key, this, steamId);
void OnServerInitialized()
{
timer.Every(10f, () => CheckHelicopter());
BaseHelicopters = new HashSet<BaseHelicopter>(GameObject.FindObjectsOfType<BaseHelicopter>());
Chinooks = new HashSet<CH47HelicopterAIController>(GameObject.FindObjectsOfType<CH47HelicopterAIController>());
CargoShips = new HashSet<CargoShip>(GameObject.FindObjectsOfType<CargoShip>());
lockedCrates = new HashSet<LockedByEntCrate>(GameObject.FindObjectsOfType<LockedByEntCrate>());
hackLockedCrates = new HashSet<HackableLockedCrate>(GameObject.FindObjectsOfType<HackableLockedCrate>());
Gibs = new HashSet<HelicopterDebris>(GameObject.FindObjectsOfType<HelicopterDebris>());
FireBalls = new HashSet<FireBall>(BaseNetworkable.serverEntities?.Where(p => p != null && p is FireBall && (p.PrefabName.Contains("napalm") || p.PrefabName.Contains("oil")))?.Select(p => p as FireBall) ?? null); //this can and should probably be used for the above debris, crates and helicopter as well, as it most likely is quicker
foreach (var heli in BaseHelicopters)
{
if (heli == null) continue;
UpdateHeli(heli, false);
}
if (DisableDefaultHeliSpawns)
{
var heliEvent = GameObject.FindObjectsOfType<TriggeredEventPrefab>()?.Where(p => (p?.targetPrefab?.resourcePath ?? string.Empty).Contains("heli"))?.FirstOrDefault() ?? null;
if (heliEvent != null)
{
GameObject.Destroy(heliEvent);
Puts("Disabled default Helicopter spawning.");
}
}
if (DisableDefaultChinookSpawns)
{
var heliEvent = GameObject.FindObjectsOfType<TriggeredEventPrefab>()?.Where(p => (p?.targetPrefab?.resourcePath ?? string.Empty).Contains("ch47"))?.FirstOrDefault() ?? null;
if (heliEvent != null)
{
GameObject.Destroy(heliEvent);
Puts("Disabled default Chinook spawning.");
}
}
if (DisableDefaultCargoShipSpawns)
{
var cargoShipEvent = GameObject.FindObjectsOfType<TriggeredEventPrefab>()?.Where(p => (p?.targetPrefab?.resourcePath ?? string.Empty).Contains("cargoship"))?.FirstOrDefault() ?? null;
if (cargoShipEvent != null)
{
GameObject.Destroy(cargoShipEvent);
Puts("Disabled default cargo ship spawning.");
}
}
ConVar.PatrolHelicopter.bulletAccuracy = HeliAccuracy;
ConVar.PatrolHelicopter.lifetimeMinutes = LifeTimeMinutes;
if (TimeBeforeUnlockingHack > 0f) HackableLockedCrate.requiredHackSeconds = TimeBeforeUnlockingHack;
if (UseCustomLoot) LoadSavedData();
LoadHeliSpawns();
LoadWeaponData();
boundary = TerrainMeta.Size.x / 2;
CH47Instance = Chinooks?.FirstOrDefault() ?? null;
var rngTime = GetRandomSpawnTime();
var rngTimeCH47 = GetRandomSpawnTime(true);
var rngTimeShip = GetRandomSpawnTimeShip();
if (rngTime > 0f)
{
if (!UseOldSpawning) CallTimer = timer.Once(rngTime, () => { if (HeliCount < 1 || AutoCallIfExists) TimerHeli = callHeli(); });
else timer.Every(rngTime, () => { if (HeliCount < 1 || AutoCallIfExists) callHeli(); });
Puts("Next Helicopter spawn: " + (rngTime >= 60 ? ((rngTime / 60).ToString("N0") + " minutes") : rngTime.ToString("N0") + " seconds"));
}
if (rngTimeCH47 > 0f)
{
if (!UseOldSpawning) CallTimerCH47 = timer.Once(rngTimeCH47, () => { if (CH47Count < 1 || AutoCallIfExistsCH47) TimerCH47 = callChinook(); });
else timer.Every(rngTimeCH47, () => { if (CH47Count < 1 || AutoCallIfExistsCH47) callChinook(); });
Puts("Next CH47 spawn: " + (rngTimeCH47 >= 60 ? ((rngTimeCH47 / 60).ToString("N0") + " minutes") : rngTimeCH47.ToString("N0") + " seconds"));
}
if (rngTimeShip > 0f)
{
if (!UseOldSpawning) CallTimerShip = timer.Once(rngTimeShip, () => { if (ShipCount < 1 || AutoCallIfExistsShip) TimerShip = callCargoShip(); });
else timer.Every(rngTimeShip, () => { if (ShipCount < 1 || AutoCallIfExistsShip) callCargoShip(); });
Puts("Next CargoShip spawn: " + (rngTimeShip >= 60 ? ((rngTimeShip / 60).ToString("N0") + " minutes") : rngTimeShip.ToString("N0") + " seconds"));
}
init = true;
}
#endregion
#region Hooks
void Unload()
{
SaveData3();
SaveData4();
}
void OnServerSave()
{
timer.Once(UnityEngine.Random.Range(1f, 2f), () =>
{
SaveData3();
SaveData4();
}); //delay saving to avoid potential lag spikes
}
void OnEntitySpawned(BaseNetworkable entity)
{
if (entity == null || !init) return;
var prefabname = entity?.ShortPrefabName ?? string.Empty;
var longprefabname = entity?.PrefabName ?? string.Empty;
if (string.IsNullOrEmpty(prefabname) || string.IsNullOrEmpty(longprefabname)) return;
var ownerID = (entity as BaseEntity)?.OwnerID ?? 0;
if (entity is LockedByEntCrate) lockedCrates.Add(entity as LockedByEntCrate);
if (entity is HackableLockedCrate) hackLockedCrates.Add(entity as HackableLockedCrate);
if (entity is CH47HelicopterAIController)
{
Chinooks.Add((entity as CH47HelicopterAIController));
CH47Instance = (entity as CH47HelicopterAIController);
}
if (entity is CargoShip)
{
CargoShips.Add(entity as CargoShip);
CargoShipInstance = (entity as CargoShip);
}
if ((prefabname.Contains("napalm") || prefabname.Contains("oilfireball")) && !prefabname.Contains("rocket"))
{
var fireball = entity?.GetComponent<FireBall>() ?? null;
if (fireball == null) return;
if (DisableNapalm)
{
fireball.enableSaving = false; //potential fix for entity is null but still in save list
NextTick(() => { if (!(entity?.IsDestroyed ?? true)) entity.Kill(); });
}
else
{
if (!entity.IsDestroyed)
{
fireball.waterToExtinguish = WaterRequired;
fireball.SendNetworkUpdate();
if (!FireBalls.Contains(fireball)) FireBalls.Add(fireball);
}
}
}
if (prefabname.Contains("rocket_heli"))
{
var explosion = entity?.GetComponent<TimedExplosive>() ?? null;
if (explosion == null) return;
if (MaxHeliRockets < 1) explosion.Kill();
else
{
if (MaxHeliRockets > 12 && ownerID == 0)
{
var strafeHeli = BaseHelicopters?.Where(p => (p?.GetComponent<PatrolHelicopterAI>()?._currentState ?? PatrolHelicopterAI.aiState.IDLE) == PatrolHelicopterAI.aiState.STRAFE)?.FirstOrDefault() ?? null;
if (strafeHeli == null || strafeHeli.IsDestroyed) return;
var curCount = 0;
if (!strafeCount.TryGetValue(strafeHeli, out curCount)) curCount = (strafeCount[strafeHeli] = 1);
else curCount = (strafeCount[strafeHeli] += 1);
if (curCount >= 12)
{
var heliAI = strafeHeli?.GetComponent<PatrolHelicopterAI>() ?? null;
var actCount = 0;
Action fireAct = null;
fireAct = new Action(() =>
{
if (actCount >= (MaxHeliRockets - 12))
{
InvokeHandler.CancelInvoke(heliAI, fireAct);
return;
}
actCount++;
FireRocket(heliAI);
});
InvokeHandler.InvokeRepeating(heliAI, fireAct, TimeBetweenRockets, TimeBetweenRockets);
strafeCount[strafeHeli] = 0;
}
}
else if (MaxHeliRockets < 12 && (HeliInstance.ClipRocketsLeft() > MaxHeliRockets))
{
explosion.Kill();
return;
}
var dmgTypes = explosion?.damageTypes ?? null;
explosion.explosionRadius = RocketExplosionRadius;
if (dmgTypes != null && dmgTypes.Count > 0)
{
for (int i = 0; i < dmgTypes.Count; i++)
{
var dmg = dmgTypes[i];
if (dmg.type == Rust.DamageType.Blunt) dmg.amount = RocketDamageBlunt;
if (dmg.type == Rust.DamageType.Explosion) dmg.amount = RocketDamageExplosion;
}
}
}
}
if (prefabname == "heli_crate")
{
if (UseCustomLoot && lootData?.HeliInventoryLists != null && lootData.HeliInventoryLists.Count > 0)
{
var heli_crate = entity?.GetComponent<LootContainer>() ?? null;
if (heli_crate == null || heli_crate?.inventory == null) return; //possible that the inventory is somehow null? not sure
int index;
index = rng.Next(lootData.HeliInventoryLists.Count);
var inv = lootData.HeliInventoryLists[index];
var itemList = heli_crate?.inventory?.itemList?.ToList() ?? null;
if (itemList != null && itemList.Count > 0) for (int i = 0; i < itemList.Count; i++) RemoveFromWorld(itemList[i]);
for (int i = 0; i < inv.lootBoxContents.Count; i++)
{
var itemDef = inv.lootBoxContents[i];
if (itemDef == null) continue;
var amount = (itemDef.amountMin > 0 && itemDef.amountMax > 0) ? UnityEngine.Random.Range(itemDef.amountMin, itemDef.amountMax) : itemDef.amount;
var skinID = 0ul;
ulong.TryParse(itemDef.skinID.ToString(), out skinID);
var item = ItemManager.CreateByItemID(ItemManager.FindItemDefinition(itemDef.name).itemid, amount, skinID);
if (item != null && !item.MoveToContainer(heli_crate.inventory)) RemoveFromWorld(item); //ensure the item is completely removed if we can't move it, so we're not causing issues
}
heli_crate.inventory.MarkDirty();
}
if (TimeBeforeUnlocking != -1f)
{
var crate2 = entity?.GetComponent<LockedByEntCrate>() ?? null;
if (TimeBeforeUnlocking == 0f) UnlockCrate(crate2);
else timer.Once(TimeBeforeUnlocking, () =>
{
if (entity == null || entity.IsDestroyed || crate2 == null) return;
UnlockCrate(crate2);
});
}
}
if (entity is HelicopterDebris)
{
var debris = entity?.GetComponent<HelicopterDebris>() ?? null;
if (debris == null) return;
if (DisableGibs)
{
NextTick(() => { if (!(entity?.IsDestroyed ?? true)) entity.Kill(); });
return;
}
if (GibsHealth != 500f)
{
debris.InitializeHealth(GibsHealth, GibsHealth);
debris.SendNetworkUpdate();
}
Gibs.Add(debris);
if (GibsTooHotLength != 480f) tooHotUntil.SetValue(debris, Time.realtimeSinceStartup + GibsTooHotLength);
}
if (prefabname.Contains("patrolhelicopter") && !prefabname.Contains("gibs"))
{
var isMax = (HeliCount >= MaxActiveHelicopters && MaxActiveHelicopters != -1);
if (DisableHeli || isMax) NextTick(() => { if (!(entity?.IsDestroyed ?? true)) entity.Kill(); });
if (DisableHeli)
{
Puts(GetMessage("heliAutoDestroyed"));
return;
}
else if (isMax)
{
Puts(GetMessage("maxHelis"));
return;
}
var AIHeli = entity?.GetComponent<PatrolHelicopterAI>() ?? null;
var BaseHeli = entity?.GetComponent<BaseHelicopter>() ?? null;
if (AIHeli == null || BaseHeli == null) return;
BaseHelicopters.Add(BaseHeli);
UpdateHeli(BaseHeli, true);
if (UseCustomHeliSpawns && spawnsData.heliSpawns.Count > 0 && !forceCalled.Contains(BaseHeli))
{
var valCount = spawnsData.heliSpawns.Values.Count;
var rng = UnityEngine.Random.Range(0, valCount);
var pos = GetVector3FromString(spawnsData.heliSpawns.Values.ToArray()[rng]);
BaseHeli.transform.position = pos;
AIHeli.transform.position = pos;
}
if (HeliStartLength > 0.0f && HeliStartSpeed != HeliSpeed)
{
AIHeli.maxSpeed = HeliStartSpeed;
timer.Once(HeliStartLength, () =>
{
if (AIHeli == null || BaseHeli == null || BaseHeli.IsDead()) return;
AIHeli.maxSpeed = HeliSpeed;
});
}
}
}
object CanBeTargeted(BaseCombatEntity entity, MonoBehaviour monoTurret)
{
if (!init || entity == null || (entity?.IsDestroyed ?? true) || monoTurret == null) return null;
var aiHeli = monoTurret?.GetComponent<HelicopterTurret>()?._heliAI ?? null;
if (aiHeli == null) return null;
var player = entity?.GetComponent<BasePlayer>() ?? null;
if (player != null && Vanish != null && (Vanish?.Call<bool>("IsInvisible", player) ?? false)) return null;
if ((aiHeli?._currentState ?? PatrolHelicopterAI.aiState.DEATH) == PatrolHelicopterAI.aiState.DEATH) return false;
return null;
}
object OnHelicopterTarget(HelicopterTurret turret, BaseCombatEntity entity)
{
if (turret == null || entity == null) return null;
if ((turret?._heliAI?._currentState ?? PatrolHelicopterAI.aiState.DEATH) == PatrolHelicopterAI.aiState.DEATH) return false;
return null;
}
object CanHelicopterStrafeTarget(PatrolHelicopterAI entity, BasePlayer target)
{
if (entity == null || target == null) return null;
if ((entity?._currentState ?? PatrolHelicopterAI.aiState.DEATH) == PatrolHelicopterAI.aiState.DEATH) return false;
return null;
}
object CanHelicopterStrafe(PatrolHelicopterAI entity)
{
if (entity == null) return null;
if ((entity?._currentState ?? PatrolHelicopterAI.aiState.DEATH) == PatrolHelicopterAI.aiState.DEATH) return false;
return null;
}
object CanHelicopterTarget(PatrolHelicopterAI entity, BasePlayer player)
{
if (entity == null) return null;
if ((entity?._currentState ?? PatrolHelicopterAI.aiState.DEATH) == PatrolHelicopterAI.aiState.DEATH) return false;
return null;
}
void OnEntityKill(BaseNetworkable entity)
{
if (entity == null) return;
var name = entity?.ShortPrefabName ?? string.Empty;
var crate = entity?.GetComponent<LockedByEntCrate>() ?? null;
if (crate != null && lockedCrates.Contains(crate)) lockedCrates.Remove(crate);
if (name.Contains("patrolhelicopter") && !name.Contains("gib"))
{
var baseHeli = entity?.GetComponent<BaseHelicopter>() ?? null;
if (baseHeli == null) return;
if (BaseHelicopters.Contains(baseHeli)) BaseHelicopters.Remove(baseHeli);
if (forceCalled.Contains(baseHeli)) forceCalled.Remove(baseHeli);
if (!UseOldSpawning && (CallTimer == null || CallTimer.Destroyed) && baseHeli == TimerHeli)
{
var rngTime = GetRandomSpawnTime();
CallTimer = timer.Once(rngTime, () => { if (HeliCount < 1 || AutoCallIfExists) TimerHeli = callHeli(); });
Puts("Next Helicopter spawn: " + (rngTime >= 60 ? ((rngTime / 60).ToString("N0") + " minutes") : rngTime.ToString("N0") + " seconds"));
} //otherwise, a timer is already firing (or heli is not a timer heli or old spawning is enabled)
}
if (entity is CH47HelicopterAIController)
{
var CH47 = entity?.GetComponent<CH47HelicopterAIController>() ?? null;
if (CH47 == null) return;
if (Chinooks.Contains(CH47)) Chinooks.Remove(CH47);
if (forceCalledCH.Contains(CH47)) forceCalledCH.Remove(CH47);
if (!UseOldSpawning && (CallTimerCH47 == null || CallTimerCH47.Destroyed) && CH47 == TimerCH47)
{
var rngTime = GetRandomSpawnTime(true);
CallTimerCH47 = timer.Once(rngTime, () => { if (CH47Count < 1 || AutoCallIfExistsCH47) TimerCH47 = callChinook(); });
Puts("Next CH47 spawn: " + (rngTime >= 60 ? ((rngTime / 60).ToString("N0") + " minutes") : rngTime.ToString("N0") + " seconds"));
} //otherwise, a timer is already firing (or heli is not a timer heli or old spawning is enabled)
}
if (entity is CargoShip)
{
var cargoShip = entity?.GetComponent<CargoShip>() ?? null;
if (cargoShip == null) return;
if (CargoShips.Contains(cargoShip)) CargoShips.Remove(cargoShip);
if (forceCalledShip.Contains(cargoShip)) forceCalledShip.Remove(cargoShip);
if (!UseOldSpawning && (CallTimerShip == null || CallTimerShip.Destroyed) && cargoShip == TimerShip)
{
var rngTime = GetRandomSpawnTimeShip();
CallTimerShip = timer.Once(rngTime, () => { if (ShipCount < 1 || AutoCallIfExistsShip) TimerShip = callCargoShip(); });
Puts("Next cargoShip spawn: " + (rngTime >= 60 ? ((rngTime / 60).ToString("N0") + " minutes") : rngTime.ToString("N0") + " seconds"));
} //otherwise, a timer is already firing (or heli is not a timer heli or old spawning is enabled)
}
if (entity is FireBall || name.Contains("fireball") || name.Contains("napalm"))
{
var fireball = entity?.GetComponent<FireBall>() ?? null;
if (fireball != null && FireBalls.Contains(fireball)) FireBalls.Remove(fireball);
}
if (entity is HelicopterDebris)
{
var debris = entity?.GetComponent<HelicopterDebris>() ?? null;
if (debris != null && Gibs.Contains(debris)) Gibs.Remove(debris);
}
}
void OnPlayerAttack(BasePlayer attacker, HitInfo hitInfo)
{
if (attacker == null || hitInfo == null || hitInfo.HitEntity == null) return;
var name = hitInfo?.HitEntity?.ShortPrefabName ?? string.Empty;
if (name == "patrolhelicopter")
{
if (GlobalDamageMultiplier != 1f && !(GlobalDamageMultiplier < 0))
{
hitInfo?.damageTypes?.ScaleAll(GlobalDamageMultiplier);
return;
}
var shortName = hitInfo?.Weapon?.GetItem()?.info?.shortname ?? string.Empty;
var displayName = hitInfo?.Weapon?.GetItem()?.info?.displayName?.english ?? string.Empty;
var weaponConfig = 0.0f;
if (string.IsNullOrEmpty(shortName)) return;
if (!weaponsData.WeaponList.TryGetValue(shortName, out weaponConfig)) weaponsData.WeaponList.TryGetValue(displayName, out weaponConfig);
if (weaponConfig != 0.0f && weaponConfig != 1.0f) hitInfo?.damageTypes?.ScaleAll(weaponConfig);
}
}
#endregion
#region Main
private void UpdateHeli(BaseHelicopter heli, bool justCreated = false)
{
if (heli == null || (heli?.IsDestroyed ?? true)) return;
heli.startHealth = BaseHealth;
if (justCreated) heli.InitializeHealth(BaseHealth, BaseHealth);
heli.maxCratesToSpawn = MaxLootCrates;
heli.bulletDamage = HeliBulletDamageAmount;
heli.bulletSpeed = BulletSpeed;
var weakspots = heli.weakspots;
if (justCreated)
{
weakspots[0].health = MainRotorHealth;
weakspots[1].health = TailRotorHealth;
}
weakspots[0].maxHealth = MainRotorHealth;
weakspots[1].maxHealth = TailRotorHealth;
var heliAI = heli?.GetComponent<PatrolHelicopterAI>() ?? null;
if (heliAI == null) return;
heliAI.maxSpeed = Mathf.Clamp(HeliSpeed, 0.1f, 125);
heliAI.timeBetweenRockets = Mathf.Clamp(TimeBetweenRockets, 0.1f, 1f);
heliAI.numRocketsLeft = Mathf.Clamp(MaxHeliRockets, 0, 48);
updateTurrets(heliAI);
heli.SendNetworkUpdateImmediate(justCreated);
}
//nearly exact code used by Rust to fire helicopter rockets
private void FireRocket(PatrolHelicopterAI heliAI)
{
if (heliAI == null || !(heliAI?.IsAlive() ?? false)) return;
var num1 = 4f;
var strafeTarget = heliAI.strafe_target_position;
if (strafeTarget == Vector3.zero) return;
var vector3 = heliAI.transform.position + heliAI.transform.forward * 1f;
var direction = (strafeTarget - vector3).normalized;
if (num1 > 0.0) direction = Quaternion.Euler(UnityEngine.Random.Range((float)(-(double)num1 * 0.5), num1 * 0.5f), UnityEngine.Random.Range((float)(-(double)num1 * 0.5), num1 * 0.5f), UnityEngine.Random.Range((float)(-(double)num1 * 0.5), num1 * 0.5f)) * direction;
var flag = heliAI.leftTubeFiredLast;
heliAI.leftTubeFiredLast = !flag;
Effect.server.Run(heliAI.helicopterBase.rocket_fire_effect.resourcePath, heliAI.helicopterBase, StringPool.Get(!flag ? "rocket_tube_right" : "rocket_tube_left"), Vector3.zero, Vector3.forward, (Network.Connection)null, true);
var entity = GameManager.server.CreateEntity(!heliAI.CanUseNapalm() ? heliAI.rocketProjectile.resourcePath : heliAI.rocketProjectile_Napalm.resourcePath, vector3, new Quaternion(), true);
if (entity == null) return;
entity.SendMessage("InitializeVelocity", (direction * 1f));
entity.OwnerID = 1337; //assign ownerID so it doesn't infinitely loop on OnEntitySpawned
entity.Spawn();
}
private CargoShip callCargoShip(Vector3 coordinates = new Vector3())
{
var ship = (CargoShip) GameManager.server.CreateEntity(cargoshipPrefab, new Vector3(), new Quaternion(), true);
ship.SendMessage("TriggeredEventSpawn", SendMessageOptions.DontRequireReceiver);
forceCalledShip.Add(ship);
ship.Spawn();
return ship;
}
private BaseHelicopter callHeli(Vector3 coordinates = new Vector3())
{
var heli = (BaseHelicopter)GameManager.server.CreateEntity(heliPrefab, new Vector3(), new Quaternion(), true);
if (heli == null) return null;
var heliAI = heli?.GetComponent<PatrolHelicopterAI>() ?? null;
if (heliAI == null) return null;
if (coordinates != Vector3.zero) heliAI.SetInitialDestination(coordinates + new Vector3(0f, 10f, 0f), 0.25f);
forceCalled.Add(heliAI.helicopterBase);
heli.Spawn();
return heli;
}
//chinook position setting code is based off of the same code used by patrolhelicopter in order to (try to) get it to spawn out of the map and fly in
private CH47HelicopterAIController callChinook(Vector3 coordinates = new Vector3())
{
var heli = (CH47HelicopterAIController)GameManager.server.CreateEntity(chinookPrefab, new Vector3(0, 100, 0), new Quaternion(), true);
if (heli == null) return null;
float x = TerrainMeta.Size.x;
float num = coordinates.y + 50f;
var mapScaleDistance = 0.8f; //high scale for further out distances/positions
var vector3_1 = Vector3Ex.Range(-1f, 1f);
vector3_1.y = 0.0f;
vector3_1.Normalize();
var vector3_2 = vector3_1 * (x * mapScaleDistance);
vector3_2.y = num;
heli.transform.position = vector3_2;
forceCalledCH.Add(heli);
heli.Spawn();
if (coordinates != Vector3.zero) timer.Once(1f, () => { if (heli != null && !heli.IsDestroyed) SetDestination(heli, coordinates + new Vector3(0f, 10f, 0));});
return heli;
}
private List<BaseHelicopter> callHelis(int amount, Vector3 coordinates = new Vector3())
{
if (amount < 1) return null;
var listHelis = new List<BaseHelicopter>(amount);
for (int i = 0; i < amount; i++) listHelis.Add(callHeli(coordinates));
return listHelis;
}
private List<CH47HelicopterAIController> callChinooks(int amount, Vector3 coordinates = new Vector3())
{
if (amount < 1) return null;
var listHelis = new List<CH47HelicopterAIController>(amount);
for (int i = 0; i < amount; i++) listHelis.Add(callChinook(coordinates));
return listHelis;
}
BaseHelicopter callCoordinates(Vector3 coordinates)
{
var heli = (BaseHelicopter)GameManager.server.CreateEntity(heliPrefab, new Vector3(), new Quaternion(), true);
if (heli == null) return null;
var heliAI = heli?.GetComponent<PatrolHelicopterAI>() ?? null;
if (heliAI == null) return null;
heliAI.SetInitialDestination(coordinates + new Vector3(0f, 10f, 0f), 0.25f);
forceCalled.Add(heliAI.helicopterBase);
heli.Spawn();
return heli;
}
private void updateTurrets(PatrolHelicopterAI helicopter)
{
if (helicopter == null) return;
helicopter.leftGun.fireRate = (helicopter.rightGun.fireRate = TurretFireRate);
helicopter.leftGun.timeBetweenBursts = (helicopter.rightGun.timeBetweenBursts = TurretTimeBetweenBursts);
helicopter.leftGun.burstLength = (helicopter.rightGun.burstLength = TurretburstLength);
helicopter.leftGun.maxTargetRange = (helicopter.rightGun.maxTargetRange = TurretMaxRange);
}
private int killAllHelis(bool isForced = false)
{
CheckHelicopter();
var count = 0;
if (BaseHelicopters.Count < 1) return count;
foreach (var helicopter in BaseHelicopters.ToList())
{
if (helicopter == null || helicopter.IsDead()) continue;
if (DisableCratesDeath) helicopter.maxCratesToSpawn = 0;
if (isForced) helicopter.Kill();
else helicopter.DieInstantly();
count++;
}
CheckHelicopter();
return count;
}
private int killAllChinooks(bool isForced = false)
{
CheckHelicopter();
var count = 0;
if (Chinooks.Count < 1) return count;
foreach (var ch47 in Chinooks.ToList())
{
if (ch47 == null || ch47.IsDestroyed) continue;
if (isForced) ch47.Kill();
else ch47.DieInstantly();
count++;
}
CheckHelicopter();
return count;
}
#endregion
#region Commands
[ChatCommand("helispawn")]
private void cmdHeliSpawns(BasePlayer player, string command, string[] args)
{
if (!HasPerms(player.UserIDString, "helispawn"))
{
SendNoPerms(player);
return;
}
if (args.Length < 1)
{
var msgSB = new StringBuilder();
foreach (var spawn in spawnsData.heliSpawns) msgSB.Append(spawn.Key + ": " + spawn.Value + ", ");
var msg = msgSB.ToString().TrimEnd(", ".ToCharArray());
if (!string.IsNullOrEmpty(msg)) SendReply(player, GetMessage("spawnCommandLiner", player.UserIDString) + msgSB + GetMessage("spawnCommandBottom", player.UserIDString));
SendReply(player, GetMessage("removeAddSpawn"), player.UserIDString); //this isn't combined with a new line with the above because there is a strange character limitation per-message, so we send two messages
return;
}
var lowerArg0 = args[0].ToLower();
if (lowerArg0 == "add" && args.Length > 1)
{
string outStr;
if (!spawnsData.heliSpawns.TryGetValue(args[1], out outStr))
{
var pos = player?.transform?.position ?? Vector3.zero;
if (pos == Vector3.zero) return;
spawnsData.heliSpawns[args[1]] = pos.ToString().Replace("(", "").Replace(")", "");
SendReply(player, string.Format(GetMessage("addedSpawn", player.UserIDString), args[1], pos));
}
else SendReply(player, GetMessage("spawnExists", player.UserIDString));
}
else if (lowerArg0 == "remove" && args.Length > 1)
{
if (spawnsData.heliSpawns.Keys.Count < 1)
{
SendReply(player, GetMessage("noSpawnsExist", player.UserIDString));
return;
}
string outStr;
if (spawnsData.heliSpawns.TryGetValue(args[1], out outStr))
{
var value = spawnsData.heliSpawns[args[1]];
spawnsData.heliSpawns.Remove(args[1]);
SendReply(player, string.Format(GetMessage("removedSpawn", player.UserIDString), args[1], value));
}
else SendReply(player, GetMessage("noSpawnFound", player.UserIDString));
}
else SendReply(player, string.Format(GetMessage("invalidSyntaxMultiple", player.UserIDString), "/helispawn add", "SpawnName", "/helispawn remove", "SpawnName"));
}
private void cmdUnlockCrates(IPlayer player, string command, string[] args)
{
if (!HasPerms(player.Id, "unlockcrates"))
{
SendNoPerms(player);
return;
}
var chCrate = args.Length > 0 ? args[0].Equals("ch47", StringComparison.OrdinalIgnoreCase) : false;
var bothCrates = args.Length > 0 ? args[0].Equals("all", StringComparison.OrdinalIgnoreCase) : false;
if (!chCrate || bothCrates) foreach (var crate in lockedCrates) UnlockCrate(crate);
else if (bothCrates || chCrate) foreach (var crate in hackLockedCrates) UnlockCrate(crate);
player.Message(GetMessage("unlockedAllCrates", player.Id));
}
private void cmdDropCH47Crate(IPlayer player, string command, string[] args)
{
if (!HasPerms(player.Id, "dropcrate"))
{
SendNoPerms(player);
return;
}
if (CH47Instance == null || CH47Instance.IsDestroyed || CH47Instance.IsDead())
{
player.Message(GetMessage("noHelisFound", player.Id));
return;
}
var all = args.Length > 0 && args[0].ToLower() == "all";
if (CH47Count > 1 && !all)
{
player.Message(string.Format(GetMessage("cannotBeCalled", player.Id), HeliCount.ToString()));
return;
}
if (all) foreach (var ch47 in Chinooks) { if (ch47.CanDropCrate()) ch47.DropCrate(); }
else
{
if (!CH47Instance.CanDropCrate())
{
player.Message(GetMessage("ch47AlreadyDropped", player.Id));
return;
}
CH47Instance.DropCrate();
}
player.Message(GetMessage("ch47DroppedCrate", player.Id));
}
private void cmdTeleportHeli(IPlayer player, string command, string[] args)
{
var ply = player?.Object as BasePlayer;
if (player.IsServer || ply == null) return;
var tpPos = Vector3.zero;
var tpCh47 = args.Length > 0 ? args[0].Equals("ch47", StringComparison.OrdinalIgnoreCase) : false;
if (!tpCh47)
{
if (!HasPerms(player.Id, "tpheli"))
{
SendNoPerms(player);
return;
}
if (HeliInstance == null || HeliInstance?.transform == null)
{
player.Message(GetMessage("noHelisFound", player.Id));
return;
}
if (HeliCount > 1)
{
player.Message(string.Format(GetMessage("cannotBeCalled", player.Id), HeliCount.ToString()));
return;
}
tpPos = HeliInstance.transform.position;
}
else
{
if (!HasPerms(player.Id, "tpch47"))
{
SendNoPerms(player);
return;
}
if (CH47Instance == null || CH47Instance?.transform == null)
{
player.Message(GetMessage("noHelisFound", player.Id));
return;
}
if (HeliCount > 1)
{
player.Message(string.Format(GetMessage("cannotBeCalled", player.Id), HeliCount.ToString()));
return;
}
tpPos = CH47Instance.transform.position;
}
if (tpPos == Vector3.zero)
{
player.Message(GetMessage("noHelisFound", player.Id));
return;
}
TeleportPlayer(ply, GetGround(tpPos));
player.Message(GetMessage("teleportedToHeli", player.Id));
}
object CanPlayerCallHeli(BasePlayer player, bool ch47 = false)
{
if (player == null) return null;
var permMsg = GetNoPerms(player.UserIDString);
var callPerm = ch47 ? "callch47" : "callheli";
var callMult = ch47 ? "callmultiplech47" : "callmultiple";
var callTarget = ch47 ? "callch47target" : "callhelitarget";
var callSelf = ch47 ? "callch47self" : "callheliself";
var cooldownTime = GetLowestCooldown(player, ch47);
var limit = GetHighestLimit(player, ch47);
var now = DateTime.Now;
var today = now.ToString("d");
var cdd = GetCooldownInfo(player.userID);
if (cdd == null)
{
cdd = new CooldownInfo(player);
cooldownData.cooldownList.Add(cdd);
}
var timesCalled = (ch47) ? cdd.TimesCalledCH47 : cdd.TimesCalled;
var lastCall = (ch47) ? cdd.LastCallDayCH47 : cdd.LastCallDay;
var coolTime = (ch47) ? cdd.CooldownTimeCH47 : cdd.CooldownTime;
if (limit < 1 && !ignoreLimits(player) && !HasPerms(player.UserIDString, callPerm)) return permMsg;
if (!HasPerms(player.UserIDString, callPerm))
{
if (!ignoreLimits(player) && limit > 0)
{
if (timesCalled >= limit && today == lastCall) return string.Format(GetMessage("callheliLimit", player.UserIDString), limit);
else if (today != lastCall)
{
if (ch47) cdd.TimesCalledCH47 = 0;
else cdd.TimesCalled = 0;
}