-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicPVP.cs
More file actions
5448 lines (4743 loc) · 177 KB
/
DynamicPVP.cs
File metadata and controls
5448 lines (4743 loc) · 177 KB
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
//Requires: ZoneManager
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Facepunch;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Prefabs.Misc;
using UnityEngine;
namespace Oxide.Plugins;
[Info("Dynamic PVP", "HunterZ/CatMeat/Arainrr", "5.0.2", ResourceId = 2728)]
[Description("Creates temporary PvP zones on certain actions/events")]
public class DynamicPVP : RustPlugin
{
#region Fields
[PluginReference] Plugin Backpacks, BotReSpawn, TruePVE, ZoneManager;
private const string PermissionAdmin = "dynamicpvp.admin";
private const string PrefabLargeOilRig =
"assets/bundled/prefabs/autospawn/monument/offshore/oilrig_1.prefab";
private const string PrefabOilRig =
"assets/bundled/prefabs/autospawn/monument/offshore/oilrig_2.prefab";
private const string PrefabSphereDome =
"assets/prefabs/visualization/sphere.prefab";
private const string PrefabSphereRedRing =
"assets/bundled/prefabs/modding/events/twitch/br_sphere_red.prefab";
private const string PrefabSphereGreenRing =
"assets/bundled/prefabs/modding/events/twitch/br_sphere_green.prefab";
private const string PrefabSphereBlueRing =
"assets/bundled/prefabs/modding/events/twitch/br_sphere.prefab";
private const string PrefabSpherePurpleRing =
"assets/bundled/prefabs/modding/events/twitch/br_sphere_purple.prefab";
private const string ZoneName = "DynamicPVP";
private readonly Dictionary<string, Timer> _eventDeleteTimers = new();
private readonly Dictionary<ulong, LeftZone> _pvpDelays = new();
// Map of event names + base events by ZoneID
private readonly Dictionary<string, BaseEvent> _activeDynamicZones =
new();
// ZoneID/NetID of Deep Sea zones that we may have tried to create
private readonly HashSet<string> _potentialDeepSeaZones = new();
// plugin integration zone tracking - used for managing hook subscriptions
// and for faster lookups
private enum PluginZoneCategory
{
BackpacksForce,
BackpacksPrevent,
LootDefender,
RestoreUponDeath
}
private readonly Dictionary<PluginZoneCategory, HashSet<string>>
_activePluginZones = new();
private Vector3 _oilRigPosition = Vector3.zero;
private Vector3 _largeOilRigPosition = Vector3.zero;
private bool _useExcludePlayer;
private bool _brokenTunnels;
private bool _dataChanged;
private Coroutine _coroutine;
private readonly YieldInstruction _fastYield = null;
private readonly YieldInstruction _throttleYield =
CoroutineEx.waitForSeconds(0.1f);
private readonly YieldInstruction _pauseYield =
CoroutineEx.waitForSeconds(0.5f);
private float _targetFps = -1.0f;
private sealed class LeftZone : Pool.IPooled
{
public string zoneId;
public BaseEvent baseEvent;
public Timer zoneTimer;
private void Reset()
{
zoneId = null;
baseEvent = null;
zoneTimer?.Destroy();
zoneTimer = null;
}
public void EnterPool() => Reset();
public void LeavePool() => Reset();
}
private enum CoroutineTypes
{
CreateStartupEvents,
CreateDeepSeaEvents,
DeleteDeepSeaEvents
}
[Flags]
[JsonConverter(typeof(StringEnumConverter))]
private enum PvpDelayTypes
{
None = 0,
ZonePlayersCanDamageDelayedPlayers = 1,
DelayedPlayersCanDamageZonePlayers = 1 << 1,
DelayedPlayersCanDamageDelayedPlayers = 1 << 2
}
// general and deep sea event types
// these are managed as a single enum to prevent name collisions
public enum GeneralEventType
{
Bradley,
Helicopter,
TimedSupply,
SupplySignal,
CargoShip,
HackableCrate,
ExcavatorIgnition,
GhostShip,
DeepSeaIsland,
IslandCannon
}
[Flags]
private enum HookCheckReasons
{
None = 0,
DelayAdded = 1 << 0,
DelayRemoved = 1 << 1,
ZoneAdded = 1 << 2,
ZoneRemoved = 1 << 3
}
private enum HookCategory
{
Command,
PluginBackpacksForce,
PluginBackpacksPrevent,
PluginLootDefender,
PluginRestoreUponDeath,
PvpDelay,
Zone
}
// hook names by hook category
private readonly Dictionary<HookCategory, List<string>> _hooksByCategory =
new()
{
{ HookCategory.Command, new List<string> {
nameof(OnPlayerCommand),
nameof(OnServerCommand) } },
{ HookCategory.PluginBackpacksForce, new List<string> {
nameof(OnPlayerDeath) } },
{ HookCategory.PluginBackpacksPrevent, new List<string> {
nameof(CanDropBackpack) } },
{ HookCategory.PluginLootDefender, new List<string> {
nameof(OnLootLockedEntity) } },
{ HookCategory.PluginRestoreUponDeath, new List<string> {
nameof(OnRestoreUponDeath) } },
{ HookCategory.PvpDelay, new List<string> {
nameof(CanEntityTakeDamage) } },
{ HookCategory.Zone, new List<string> {
nameof(OnEnterZone),
nameof(OnExitZone) } }
};
// current hook subscription state by hook category
private readonly Dictionary<HookCategory, bool> _subscriptionsByCategory =
new();
private readonly Collider[] _colliderBuffer = new Collider[8];
private enum MonumentEventType
{
Default,
Custom,
TunnelEntrance,
TunnelLink,
TunnelSection,
UnderwaterLabs
}
private readonly Dictionary<string, OriginalMonumentGeometry>
_originalMonumentGeometries = new();
#endregion Fields
#region Oxide Hooks
private void Init()
{
foreach (
PluginZoneCategory pzCat in Enum.GetValues(typeof(PluginZoneCategory)))
{
_activePluginZones[pzCat] = Pool.Get<HashSet<string>>();
}
_brokenTunnels = false;
LoadData();
permission.RegisterPermission(PermissionAdmin, this);
AddCovalenceCommand(_configData.Chat.Command, nameof(CmdDynamicPVP));
Unsubscribe(nameof(CanDropBackpack));
Unsubscribe(nameof(CanEntityTakeDamage));
Unsubscribe(nameof(OnCargoPlaneSignaled));
Unsubscribe(nameof(OnCargoShipEgress));
Unsubscribe(nameof(OnCargoShipHarborApproach));
Unsubscribe(nameof(OnCargoShipHarborArrived));
Unsubscribe(nameof(OnCargoShipHarborLeave));
Unsubscribe(nameof(OnCrateHack));
Unsubscribe(nameof(OnCrateHackEnd));
Unsubscribe(nameof(OnDeepSeaClosed));
Unsubscribe(nameof(OnDeepSeaOpened));
Unsubscribe(nameof(OnDieselEngineToggled));
Unsubscribe(nameof(OnEnterZone));
Unsubscribe(nameof(OnEntityDeath));
Unsubscribe(nameof(OnEntityKill));
Unsubscribe(nameof(OnEntitySpawned));
Unsubscribe(nameof(OnExitZone));
Unsubscribe(nameof(OnLootEntity));
Unsubscribe(nameof(OnLootLockedEntity));
Unsubscribe(nameof(OnPlayerCommand));
Unsubscribe(nameof(OnPlayerDeath));
Unsubscribe(nameof(OnRestoreUponDeath));
Unsubscribe(nameof(OnServerCommand));
Unsubscribe(nameof(OnSupplyDropLanded));
foreach (var category in _hooksByCategory.Keys)
{
_subscriptionsByCategory[category] = false;
}
if (_configData.Global.LogToFile)
{
_debugStringBuilder = Pool.Get<StringBuilder>();
}
// setup new TruePVE "ExcludePlayer" support
_useExcludePlayer = _configData.Global.UseExcludePlayer;
// if ExcludePlayer is disabled in config but is supported...
if (!_useExcludePlayer &&
null != TruePVE &&
TruePVE.Version >= new VersionNumber(2, 2, 3))
{
// ...and all PVP delays are enabled, auto-enable internally and warn
if ((PvpDelayTypes.ZonePlayersCanDamageDelayedPlayers |
PvpDelayTypes.DelayedPlayersCanDamageZonePlayers |
PvpDelayTypes.DelayedPlayersCanDamageDelayedPlayers) ==
_configData.Global.PvpDelayFlags)
{
_useExcludePlayer = true;
Puts("All PVP delay flags active and TruePVE 2.2.3+ detected, so TruePVE PVP delays will be used for performance and cross-plugin support; please consider enabling TruePVE PVP Delay API in the config file to skip this check");
}
// else just nag, since settings are not compatible
else
{
Puts("Some/all PVP delay flags NOT active, but TruePVE 2.2.3+ detected; please consider switching to TruePVE PVP Delay API in the config file for performance and cross-plugin support");
}
} // else ExcludePlayer is already enabled, or TruePVE 2.2.3+ not running
}
private void OnServerInitialized()
{
if (null == ZoneManager ||
ZoneManager.Version < new VersionNumber(3, 1, 10))
{
PrintError("Zone Manager missing or outdated; please update for proper function of this plugin!");
}
// resubscribe to any hooks that are conditional due to config options
// code is grouped alphabetically by first hook name, to make it easier t
// see what gets subscribed and why
if (_configData.GeneralEvents.SupplySignal.Enabled ||
_configData.GeneralEvents.TimedSupply.Enabled)
{
// this is subscribed if either drop event is enabled, because we need to
// differentiate either way
Subscribe(nameof(OnCargoPlaneSignaled));
Subscribe(nameof(OnSupplyDropDropped));
// this is now subscribed regardless of start on spawn-vs-landing, as we
// need to tether the zone to the drop on landing in both cases
Subscribe(nameof(OnSupplyDropLanded));
}
if (_configData.GeneralEvents.CargoShip.Enabled)
{
Subscribe(nameof(OnCargoShipEgress));
Subscribe(nameof(OnCargoShipHarborApproach));
Subscribe(nameof(OnCargoShipHarborArrived));
Subscribe(nameof(OnCargoShipHarborLeave));
}
if (_configData.GeneralEvents.HackableCrate.Enabled &&
!_configData.GeneralEvents.HackableCrate.StartWhenSpawned)
{
Subscribe(nameof(OnCrateHack));
}
if (_configData.GeneralEvents.HackableCrate.Enabled &&
_configData.GeneralEvents.HackableCrate.TimerStartWhenUnlocked)
{
Subscribe(nameof(OnCrateHackEnd));
}
if (AnySeepSeaEventEnabled())
{
Subscribe(nameof(OnDeepSeaClosed));
Subscribe(nameof(OnDeepSeaOpened));
}
if (_configData.GeneralEvents.ExcavatorIgnition.Enabled)
{
Subscribe(nameof(OnDieselEngineToggled));
}
if (_configData.GeneralEvents.PatrolHelicopter.Enabled ||
_configData.GeneralEvents.BradleyApc.Enabled)
{
Subscribe(nameof(OnEntityDeath));
}
if (_configData.GeneralEvents.TimedSupply.Enabled ||
_configData.GeneralEvents.SupplySignal.Enabled ||
_configData.GeneralEvents.HackableCrate.Enabled ||
_configData.GeneralEvents.CargoShip.Enabled)
{
Subscribe(nameof(OnEntityKill));
}
if ((_configData.GeneralEvents.HackableCrate.Enabled &&
_configData.GeneralEvents.HackableCrate.StartWhenSpawned) ||
_configData.GeneralEvents.CargoShip.Enabled)
{
Subscribe(nameof(OnEntitySpawned));
}
if ((_configData.GeneralEvents.TimedSupply.Enabled &&
_configData.GeneralEvents.TimedSupply.TimerStartWhenLooted) ||
(_configData.GeneralEvents.SupplySignal.Enabled &&
_configData.GeneralEvents.SupplySignal.TimerStartWhenLooted) ||
(_configData.GeneralEvents.HackableCrate.Enabled &&
_configData.GeneralEvents.HackableCrate.TimerStartWhenLooted))
{
Subscribe(nameof(OnLootEntity));
}
NextTick(() => TryStartCoroutine(CoroutineTypes.CreateStartupEvents));
}
private void Unload()
{
if (_coroutine != null)
{
ServerMgr.Instance.StopCoroutine(_coroutine);
}
if (_activeDynamicZones.Count > 0)
{
PrintDebug($"Unload(): Deleting {_activeDynamicZones.Count} active zone(s)");
// copy zone keys to a temporary list, because each deletion will modify
// _activeDynamicZones
var zoneKeys = Pool.Get<List<string>>();
zoneKeys.AddRange(_activeDynamicZones.Keys);
foreach (var key in zoneKeys)
{
DeleteDynamicZone(key);
}
Pool.FreeUnmanaged(ref zoneKeys);
_activeDynamicZones.Clear();
_potentialDeepSeaZones.Clear();
}
// copy LeftZone records to a temporary list to that we can reverse iterate
var leftZones = Pool.Get<List<LeftZone>>();
leftZones.AddRange(_pvpDelays.Values);
for (var i = leftZones.Count - 1; i >= 0; --i)
{
// this is cheating because it leaves leftZones[i] in a dangling state,
// but it's okay because we're going to free/clear everything anyway
var value = leftZones[i];
Pool.Free(ref value);
}
Pool.FreeUnmanaged(ref leftZones);
_pvpDelays.Clear();
// also remove LeftZone class from pool framework, in case it changes on
// plugin reload
Pool.Directory.TryRemove(typeof(LeftZone), out _);
// copy sphere lists to a temporary list so that we can reverse iterate
var spheres = Pool.Get<List<List<SphereEntity>>>();
spheres.AddRange(_zoneSpheres.Values);
for (var i = _zoneSpheres.Count - 1; i >= 0; --i)
{
// this is cheating because it leaves spheres[i] in a dangling state, but
// it's okay because we're going to free/clear everything anyway
var sphereEntities = spheres[i];
foreach (var sphereEntity in sphereEntities)
{
if (!sphereEntity || sphereEntity.IsDestroyed) continue;
sphereEntity.KillMessage();
}
Pool.FreeUnmanaged(ref sphereEntities);
}
Pool.FreeUnmanaged(ref spheres);
_zoneSpheres.Clear();
SaveData();
SaveDebug();
if (null == _debugStringBuilder) return;
Pool.FreeUnmanaged(ref _debugStringBuilder);
_debugStringBuilder = null;
_originalMonumentGeometries.Clear();
foreach (var apZone in _activePluginZones.Values)
{
// this is cheating because it leaves apZone in a dangling state, but it's
// okay because we're going to clear the list just after this
var apZoneI = apZone;
Pool.FreeUnmanaged(ref apZoneI);
}
_activePluginZones.Clear();
DomeEvent._domeEventsToCheck = null;
_activeSignaledPlanesAndDrops.Clear();
}
private void OnServerSave() =>
timer.Once(UnityEngine.Random.Range(0f, 60f), () =>
{
SaveDebug();
if (!_dataChanged) return;
SaveData();
_dataChanged = false;
});
private void OnPlayerRespawned(BasePlayer player)
{
if (!player || !player.userID.IsSteamId())
{
PrintDebug("OnPlayerRespawned(): Ignoring respawn of null/NPC player");
return;
}
TryRemovePVPDelay(player);
}
#endregion Oxide Hooks
#region Methods
// try to start event creation coroutine
// startup: true => CreateStartupEvents, false => CreateDeepSeaEvents
// if coroutine already running, waits for it to stop and then starts it
private void TryStartCoroutine(
CoroutineTypes type, DeepSeaManager deepSeaManager = null)
{
if (null != _coroutine)
{
Puts("Waiting for current event creation coroutine to finish...");
timer.Once(1.0f, () => TryStartCoroutine(type, deepSeaManager));
return;
}
if (!deepSeaManager)
{
deepSeaManager = DeepSeaManager.ServerInstance;
}
switch (type)
{
case CoroutineTypes.CreateStartupEvents:
_coroutine = ServerMgr.Instance.StartCoroutine(CreateStartupEvents());
return;
case CoroutineTypes.CreateDeepSeaEvents:
if (deepSeaManager)
{
_coroutine = ServerMgr.Instance.StartCoroutine(CreateDeepSeaEvents(
deepSeaManager, true, false));
}
else
{
Puts("ERROR: Can't start Deep Sea Events creation coroutine because DeepSeaManager is null");
}
return;
case CoroutineTypes.DeleteDeepSeaEvents:
_coroutine = ServerMgr.Instance.StartCoroutine(DeleteDeepSeaEvents());
return;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
private void TryRemoveEventTimer(string zoneId)
{
if (_eventDeleteTimers.Remove(zoneId, out var value))
{
value?.Destroy();
}
}
private LeftZone GetOrAddPVPDelay(
BasePlayer player, string zoneId, BaseEvent baseEvent)
{
PrintDebug($"GetOrAddPVPDelay(): Adding {player.displayName} to PVP delay");
var added = false;
if (_pvpDelays.TryGetValue(player.userID, out var leftZone))
{
leftZone.zoneTimer?.Destroy();
}
else
{
added = true;
leftZone = Pool.Get<LeftZone>();
_pvpDelays.Add(player.userID, leftZone);
}
leftZone.zoneId = zoneId;
leftZone.baseEvent = baseEvent;
if (added)
{
CheckHooks(HookCheckReasons.DelayAdded, baseEvent);
}
return leftZone;
}
private bool TryRemovePVPDelay(BasePlayer player)
{
PrintDebug($"TryRemovePVPDelay(): Removing {player.displayName} from PVP delay");
var playerId = player.userID.Get();
if (!_pvpDelays.Remove(playerId, out var leftZone)) return false;
Interface.CallHook("OnPlayerRemovedFromPVPDelay",
playerId, leftZone.zoneId, player);
CheckHooks(HookCheckReasons.DelayRemoved, null); // baseEvent not needed
Pool.Free(ref leftZone);
return true;
}
private bool CheckEntityOwner(BaseEntity baseEntity)
{
if (!_configData.Global.CheckEntityOwner ||
!baseEntity.OwnerID.IsSteamId() ||
// HeliSignals and BradleyDrops exception
baseEntity.skinID != 0)
{
return true;
}
PrintDebug($"CheckEntityOwner(): Skipping event creation because baseEntity={baseEntity} is owned by player={baseEntity.OwnerID}");
return false;
}
private bool CanCreateDynamicPVP(string eventName, BaseEntity entity)
{
if (Interface.CallHook("OnCreateDynamicPVP", eventName, entity) == null)
{
return true;
}
PrintDebug($"CanCreateDynamicPVP(): Skipping event creation for eventName={eventName} due to OnCreateDynamicPVP hook result");
return false;
}
private bool HasCommands()
{
// track which events we've checked, to avoid redundant calls to
// GetBaseEvent(); note that use of pool API means we need to free this
// on every return
var checkedEvents = Pool.Get<HashSet<BaseEvent>>();
// check for command-containing zones referenced by PVP delays, which
// either work when PVP delayed, or are an active zone
// HZ: I guess this is really trying to catch the corner case of players
// in PVP delay because a zone expired?
foreach (var leftZone in _pvpDelays.Values)
{
if (leftZone.baseEvent == null ||
leftZone.baseEvent.CommandList.Count <= 0)
{
continue;
}
if (leftZone.baseEvent.CommandWorksForPVPDelay ||
_activeDynamicZones.ContainsValue(leftZone.baseEvent))
{
Pool.FreeUnmanaged(ref checkedEvents);
return true;
}
checkedEvents.Add(leftZone.baseEvent);
}
foreach (var baseEvent in _activeDynamicZones.Values)
{
// optimization: skip if we've already checked this in the other loop
if (checkedEvents.Contains(baseEvent))
{
continue;
}
if (null == baseEvent || baseEvent.CommandList.Count <= 0) continue;
Pool.FreeUnmanaged(ref checkedEvents);
return true;
}
Pool.FreeUnmanaged(ref checkedEvents);
return false;
}
/// toggle dynamic hook subscription(s) based on need
private void UpdateDynamicHook(
bool needSubscription, HookCategory hookCategory)
{
// abort if subscription tracking undefined, or subscription need already
// met, or hooks not defined
if (!_subscriptionsByCategory.TryGetValue(
hookCategory, out var haveSubscription) ||
needSubscription == haveSubscription ||
!_hooksByCategory.TryGetValue(hookCategory, out var hooks))
{
return;
}
// (un)subscribe per subscription need
foreach (var hook in hooks)
{
if (needSubscription)
{
Subscribe(hook);
}
else
{
Unsubscribe(hook);
}
}
// record that we've achieved desired subscription state
_subscriptionsByCategory[hookCategory] = needSubscription;
}
private void CheckCommandHooks(bool added)
{
// optimization: avoid calling HasCommands() if added + already subscribed
if (added &&
_subscriptionsByCategory.TryGetValue(
HookCategory.Command, out var subscribed) &&
subscribed)
{
return;
}
UpdateDynamicHook(HasCommands(), HookCategory.Command);
}
/// update plugin integration tracking/subscriptions as appropriate
private void CheckPluginHooks(BaseEvent baseEvent)
{
// this currently only supports checks when baseEvent is provided
if (null == baseEvent) return;
foreach (
PluginZoneCategory pzCat in Enum.GetValues(typeof(PluginZoneCategory)))
{
if (HasPluginZoneCategory(baseEvent, pzCat))
{
UpdateDynamicHook(
_activePluginZones[pzCat].Count > 0, ToHookCategory(pzCat));
}
}
}
private void CheckPvpDelayHooks() =>
UpdateDynamicHook(
!_useExcludePlayer && _pvpDelays.Count > 0, HookCategory.PvpDelay);
private void CheckZoneHooks() =>
UpdateDynamicHook(_activeDynamicZones.Count > 0, HookCategory.Zone);
/// check whether hook subscription changes are warranted
//
// baseEvent is used as an optimization to only check plugin integration
// hook subscriptions when relevant zones are added/removed
private void CheckHooks(HookCheckReasons reasons, BaseEvent baseEvent)
{
// update command hooks based on PVP delay or zone changes
if (reasons.HasFlag(HookCheckReasons.DelayAdded) ||
reasons.HasFlag(HookCheckReasons.ZoneAdded))
{
CheckCommandHooks(true);
}
else if (reasons.HasFlag(HookCheckReasons.DelayRemoved) ||
reasons.HasFlag(HookCheckReasons.ZoneRemoved))
{
CheckCommandHooks(false);
}
// update PVP delay hooks based on PVP delay changes
if (reasons.HasFlag(HookCheckReasons.DelayAdded) ||
reasons.HasFlag(HookCheckReasons.DelayRemoved))
{
CheckPvpDelayHooks();
}
// update plugin and zone hooks based on zone changes
if (reasons.HasFlag(HookCheckReasons.ZoneAdded) ||
reasons.HasFlag(HookCheckReasons.ZoneRemoved))
{
CheckPluginHooks(baseEvent);
CheckZoneHooks();
}
}
#endregion Methods
#region Events
#region Startup
// utility method to return an appropriate yield instruction based on
// whether this is a long pause for debug logging to catch up, whether
// current server framerate is too low, etc.
private YieldInstruction DynamicYield(bool pause = false)
{
// perform one-time caching of target FPS
if (_targetFps <= 0) _targetFps = Mathf.Min(ConVar.FPS.limit, 30);
return
pause && _configData.Global.DebugEnabled ? _pauseYield :
Performance.report.frameRate >= _targetFps ? _fastYield :
_throttleYield;
}
// coroutine to orchestrate creation of all relevant events on startup
private IEnumerator CreateStartupEvents()
{
var startTime = DateTime.UtcNow;
Puts("Creating General Events");
yield return CreateGeneralEvents();
var deepSeaManager = DeepSeaManager.ServerInstance;
switch (AnySeepSeaEventEnabled())
{
case true when IsDeepSeaOpen(deepSeaManager):
// this will get logged at a lower level
yield return CreateDeepSeaEvents(
deepSeaManager, delay: false, init: true);
break;
case true when deepSeaManager:
Puts("Skipping Deep Sea Events (Deep Sea closed)");
break;
case true:
Puts("Skipping Deep Sea Events (Deep Sea disabled)");
break;
default:
Puts("Skipping Deep Sea Events (no events enabled)");
break;
}
// this will get logged at a lower level
yield return CreateMonumentEvents();
Puts("Creating Auto Events");
yield return CreateAutoEvents();
Puts($"Startup event creation completed in {(DateTime.UtcNow - startTime).TotalSeconds} seconds");
_coroutine = null;
}
#endregion Startup
#region General Events
// coroutine to determine whether any General Events should be created based
// on currently existing entities of interest
// this is expected to only be called on startup
private IEnumerator CreateGeneralEvents()
{
// determine up-front whether there are any general events to create,
// because iterating over all net entities is not cheap
var checkGeneralEvents = false;
// TODO: Bradley, Patrol Helicopter, Supply Drop, Timed Supply
checkGeneralEvents |= _configData.GeneralEvents.CargoShip.Enabled;
// NOTE: StopWhenKilled is checked because we don't want to start events
// whose end is determined by a timer, as we don't know elapsed times
checkGeneralEvents |=
_configData.GeneralEvents.HackableCrate.Enabled &&
_configData.GeneralEvents.HackableCrate.StopWhenKilled;
checkGeneralEvents |= _configData.GeneralEvents.ExcavatorIgnition.Enabled;
if (checkGeneralEvents)
{
foreach (var serverEntity in BaseNetworkable.serverEntities)
{
switch (serverEntity)
{
// Cargo Ship Event
case CargoShip cargoShip:
StartupCargoShip(cargoShip);
yield return DynamicYield();
break;
// Excavator Ignition Event
case DieselEngine dieselEngine:
StartupDieselEngine(dieselEngine);
yield return DynamicYield();
break;
// Hackable Crate Event
case HackableLockedCrate hackableLockedCrate:
StartupHackableLockedCrate(hackableLockedCrate);
yield return DynamicYield();
break;
}
}
}
yield return DynamicYield(true);
}
#region ExcavatorIgnition Event
// invoke appropriate hook handler for current DieselEngine state
// this is only used on startup, to (re)create events for already-existing
// DieselEngine entities
private void StartupDieselEngine(DieselEngine dieselEngine)
{
if (!dieselEngine)
{
PrintDebug("StartupDieselEngine(): DieselEngine is null");
return;
}
if (!_configData.GeneralEvents.ExcavatorIgnition.Enabled)
{
PrintDebug("StartupDieselEngine(): Excavator Ignition Event is disabled");
return;
}
if (!dieselEngine.IsOn())
{
PrintDebug("StartupDieselEngine(): DieselEngine is off");
return;
}
PrintDebug("StartupDieselEngine(): Found activated Giant Excavator");
OnDieselEngineToggled(dieselEngine);
}
private void OnDieselEngineToggled(DieselEngine dieselEngine)
{
if (!dieselEngine || null == dieselEngine.net)
{
PrintDebug("OnDieselEngineToggled(): ERROR: Engine or Net is null", DebugLevel.Error);
return;
}
var zoneId = dieselEngine.net.ID.ToString();
if (dieselEngine.IsOn())
{
PrintDebug(
$"OnDieselEngineToggled(): Requesting 'just-in-case' delete of zoneId={zoneId} due to excavator enable");
DeleteDynamicZone(zoneId);
HandleGeneralEvent(
_configData.GeneralEvents.ExcavatorIgnition, dieselEngine, true);
}
else
{
PrintDebug($"OnDieselEngineToggled(): Scheduling delete of zoneId={zoneId} due to excavator disable");
HandleDeleteDynamicZone(zoneId);
}
}
#endregion ExcavatorIgnition Event
#region HackableLockedCrate Event
// invoke appropriate hook handler for current HackableLockedCrate state
// this is only used on startup, to (re)create events for already-existing
// HackableLockedCrate entities
private void StartupHackableLockedCrate(
HackableLockedCrate hackableLockedCrate)
{
if (!hackableLockedCrate)
{
PrintDebug("StartupHackableLockedCrate(): HackableLockedCrate is null");
return;
}
var baseEvent = _configData.GeneralEvents.HackableCrate;
if (!baseEvent.Enabled)
{
PrintDebug("StartupHackableLockedCrate(): Hackable Crate Event is disabled");
return;
}
if (!baseEvent.StopWhenKilled)
{
PrintDebug("StartupHackableLockedCrate(): Hackable Crate Event doesn't stop when killed");
return;
}
if (0 != hackableLockedCrate.FirstLooterId &&
baseEvent.TimerStartWhenLooted)
{
// looted and stop after time since loot enabled
// we don't know elapsed time, so err on the side of assuming the event
// has already ended
PrintDebug(
"StartupHackableLockedCrate(): Found looted hackable locked crate, and TimerStartWhenLooted set; ignoring because elapsed time unknown");
}
else if (
hackableLockedCrate.HasFlag(HackableLockedCrate.Flag_FullyHacked) &&
baseEvent.TimerStartWhenUnlocked)
{
// unlocked and stop after time since unlock enabled
// we don't know elapsed time, so err on the side of assuming the event
// has already ended
PrintDebug(
"StartupHackableLockedCrate(): Found unlocked hackable locked crate and TimerStartWhenUnlocked set; ignoring because elapsed time unknown");
}
else if (hackableLockedCrate.HasFlag(HackableLockedCrate.Flag_Hacking) &&
!baseEvent.StartWhenSpawned)
{
// hacking and start on hacking enabled
PrintDebug("StartupHackableLockedCrate(): Found hacking hackable locked crate and StartWhenSpawned NOT set; triggering OnCrateHack()");
OnCrateHack(hackableLockedCrate);
}
else if (baseEvent.StartWhenSpawned)
{
// any other state and start on spawn + stop when killed enabled
PrintDebug("StartupHackableLockedCrate(): Found hackable locked crate, and StartWhenSpawned set; triggering OnEntitySpawned()");
OnEntitySpawned(hackableLockedCrate);
}
else
{
PrintDebug(
"StartupHackableLockedCrate(): Found hackable locked crate, but ignoring because of either start on hack, or stop on timer with elapsed time unknown");
}
}
private void OnEntitySpawned(HackableLockedCrate hackableLockedCrate)
{
var baseEvent = _configData.GeneralEvents.HackableCrate;
if (!baseEvent.Enabled)
{
return;
}
if (!hackableLockedCrate || null == hackableLockedCrate.net)
{
PrintDebug("OnEntitySpawned(): ERROR: HackableLockedCrate or Net is null", DebugLevel.Error);
return;
}
if (!baseEvent.StartWhenSpawned)
{
PrintDebug("OnEntitySpawned(HackableLockedCrate): Ignoring due to start-when-spawned false");
return;
}
PrintDebug("OnEntitySpawned(): Trying to create HackableCrate spawn event");
NextTick(() => LockedCrateEvent(hackableLockedCrate));
}
private void OnCrateHack(HackableLockedCrate hackableLockedCrate)
{
if (!hackableLockedCrate || null == hackableLockedCrate.net)
{
PrintDebug("OnCrateHack(): ERROR: Crate or Net is null", DebugLevel.Error);
return;
}
PrintDebug("OnCrateHack(): Trying to create hackable crate hack event");
NextTick(() => LockedCrateEvent(hackableLockedCrate));
}
private void OnCrateHackEnd(HackableLockedCrate hackableLockedCrate)
{
if (!hackableLockedCrate || null == hackableLockedCrate.net)
{
PrintDebug("OnCrateHackEnd(): ERROR: Crate or Net is null", DebugLevel.Error);
return;
}
var zoneId = hackableLockedCrate.net.ID.ToString();
var duration = _configData.GeneralEvents.HackableCrate.Duration;
PrintDebug(
$"OnCrateHackEnd(): Scheduling delete of zoneId={zoneId} in {duration} seconds");
HandleDeleteDynamicZone(zoneId, duration);
}
private void OnLootEntity(
BasePlayer player, HackableLockedCrate hackableLockedCrate)
{
if (!hackableLockedCrate || null == hackableLockedCrate.net)
{
PrintDebug("OnLootEntity(HackableLockedCrate): ERROR: Crate or Net is null", DebugLevel.Error);
return;
}