Guest User

DynamicPVP.cs

a guest
Feb 6th, 2026
161
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 175.05 KB | Gaming | 0 0
  1. //Requires: ZoneManager
  2.  
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Text;
  8. using Facepunch;
  9. using Newtonsoft.Json;
  10. using Newtonsoft.Json.Converters;
  11. using Oxide.Core;
  12. using Oxide.Core.Libraries.Covalence;
  13. using Oxide.Core.Plugins;
  14. using Prefabs.Misc;
  15. using UnityEngine;
  16.  
  17. namespace Oxide.Plugins;
  18.  
  19. [Info("Dynamic PVP", "HunterZ/CatMeat/Arainrr", "4.10.0", ResourceId = 2728)]
  20. [Description("Creates temporary PvP zones on certain actions/events")]
  21. public class DynamicPVP : RustPlugin
  22. {
  23.   #region Fields
  24.  
  25.   [PluginReference] Plugin Backpacks, BotReSpawn, TruePVE, ZoneManager;
  26.  
  27.   private const string PermissionAdmin = "dynamicpvp.admin";
  28.   private const string PrefabLargeOilRig =
  29.     "assets/bundled/prefabs/autospawn/monument/offshore/oilrig_1.prefab";
  30.   private const string PrefabOilRig =
  31.     "assets/bundled/prefabs/autospawn/monument/offshore/oilrig_2.prefab";
  32.   private const string PrefabSphereDome =
  33.     "assets/prefabs/visualization/sphere.prefab";
  34.   private const string PrefabSphereRedRing =
  35.     "assets/bundled/prefabs/modding/events/twitch/br_sphere_red.prefab";
  36.   private const string PrefabSphereGreenRing =
  37.     "assets/bundled/prefabs/modding/events/twitch/br_sphere_green.prefab";
  38.   private const string PrefabSphereBlueRing =
  39.     "assets/bundled/prefabs/modding/events/twitch/br_sphere.prefab";
  40.   private const string PrefabSpherePurpleRing =
  41.     "assets/bundled/prefabs/modding/events/twitch/br_sphere_purple.prefab";
  42.   private const string ZoneName = "DynamicPVP";
  43.  
  44.   private readonly Dictionary<string, Timer> _eventTimers = new();
  45.   private readonly Dictionary<ulong, LeftZone> _pvpDelays = new();
  46.  
  47.   //ID -> EventName
  48.   private readonly Dictionary<string, string> _activeDynamicZones = new();
  49.  
  50.   // plugin integration zone tracking - used for managing hook subscriptions
  51.   //  and for faster lookups
  52.  
  53.   private enum PluginZoneCategory
  54.   {
  55.     BackpacksForce,
  56.     BackpacksPrevent,
  57.     LootDefender,
  58.     RestoreUponDeath
  59.   }
  60.  
  61.   private readonly Dictionary<PluginZoneCategory, HashSet<string>>
  62.     _activePluginZones = new();
  63.  
  64.   private Vector3 _oilRigPosition = Vector3.zero;
  65.   private Vector3 _largeOilRigPosition = Vector3.zero;
  66.   private bool _useExcludePlayer;
  67.   private bool _brokenTunnels;
  68.   private bool _dataChanged;
  69.   private Coroutine _createEventsCoroutine;
  70.   private readonly YieldInstruction _fastYield = null;
  71.   private readonly YieldInstruction _throttleYield =
  72.     CoroutineEx.waitForSeconds(0.1f);
  73.   private readonly YieldInstruction _pauseYield =
  74.     CoroutineEx.waitForSeconds(0.5f);
  75.   private float _targetFps = -1.0f;
  76.  
  77.   private sealed class LeftZone : Pool.IPooled
  78.   {
  79.     public string zoneId;
  80.     public string eventName;
  81.     public Timer zoneTimer;
  82.  
  83.     private void Reset()
  84.     {
  85.       zoneId = null;
  86.       eventName = null;
  87.       zoneTimer?.Destroy();
  88.       zoneTimer = null;
  89.     }
  90.  
  91.     public void EnterPool() => Reset();
  92.  
  93.     public void LeavePool() => Reset();
  94.   }
  95.  
  96.   [Flags]
  97.   [JsonConverter(typeof(StringEnumConverter))]
  98.   private enum PvpDelayTypes
  99.   {
  100.     None = 0,
  101.     ZonePlayersCanDamageDelayedPlayers = 1,
  102.     DelayedPlayersCanDamageZonePlayers = 1 << 1,
  103.     DelayedPlayersCanDamageDelayedPlayers = 1 << 2
  104.   }
  105.  
  106.   // general and deep sea event types
  107.   // these are managed as a single enum to prevent name collisions
  108.   private enum GeneralEventType
  109.   {
  110.     Bradley,
  111.     Helicopter,
  112.     SupplyDrop,
  113.     SupplySignal,
  114.     CargoShip,
  115.     HackableCrate,
  116.     ExcavatorIgnition,
  117.     GhostShip,
  118.     DeepSeaIsland,
  119.     IslandCannon
  120.   }
  121.  
  122.   [Flags]
  123.   private enum HookCheckReasons
  124.   {
  125.     None         = 0,
  126.     DelayAdded   = 1 << 0,
  127.     DelayRemoved = 1 << 1,
  128.     ZoneAdded    = 1 << 2,
  129.     ZoneRemoved  = 1 << 3
  130.   }
  131.  
  132.   private enum HookCategory
  133.   {
  134.     Command,
  135.     PluginBackpacksForce,
  136.     PluginBackpacksPrevent,
  137.     PluginLootDefender,
  138.     PluginRestoreUponDeath,
  139.     PvpDelay,
  140.     Zone,
  141.   }
  142.  
  143.   // hook names by hook category
  144.   private readonly Dictionary<HookCategory, List<string>> _hooksByCategory =
  145.     new()
  146.     {
  147.       { HookCategory.Command,                new List<string> {
  148.         nameof(OnPlayerCommand),
  149.         nameof(OnServerCommand) } },
  150.       { HookCategory.PluginBackpacksForce,   new List<string> {
  151.         nameof(OnPlayerDeath) } },
  152.       { HookCategory.PluginBackpacksPrevent, new List<string> {
  153.         nameof(CanDropBackpack) } },
  154.       { HookCategory.PluginLootDefender,     new List<string> {
  155.         nameof(OnLootLockedEntity) } },
  156.       { HookCategory.PluginRestoreUponDeath, new List<string> {
  157.         nameof(OnRestoreUponDeath) } },
  158.       { HookCategory.PvpDelay,               new List<string> {
  159.         nameof(CanEntityTakeDamage) } },
  160.       { HookCategory.Zone,                   new List<string> {
  161.         nameof(OnEnterZone),
  162.         nameof(OnExitZone) } }
  163.     };
  164.  
  165.   // current hook subscription state by hook category
  166.   private readonly Dictionary<HookCategory, bool> _subscriptionsByCategory =
  167.     new();
  168.  
  169.   private readonly Collider[] _colliderBuffer = new Collider[8];
  170.  
  171.   private enum MonumentEventType
  172.   {
  173.     Default,
  174.     Custom,
  175.     TunnelEntrance,
  176.     TunnelLink,
  177.     TunnelSection,
  178.     UnderwaterLabs
  179.   }
  180.  
  181.   private readonly Dictionary<string, OriginalMonumentGeometry>
  182.     _originalMonumentGeometries = new();
  183.  
  184.   #endregion Fields
  185.  
  186.   #region Oxide Hooks
  187.  
  188.   private void Init()
  189.   {
  190.     foreach (
  191.       PluginZoneCategory pzCat in Enum.GetValues(typeof(PluginZoneCategory)))
  192.     {
  193.       _activePluginZones[pzCat] = Pool.Get<HashSet<string>>();
  194.     }
  195.  
  196.     _brokenTunnels = false;
  197.  
  198.     LoadData();
  199.     permission.RegisterPermission(PermissionAdmin, this);
  200.     AddCovalenceCommand(_configData.Chat.Command, nameof(CmdDynamicPVP));
  201.  
  202.     Unsubscribe(nameof(CanDropBackpack));
  203.     Unsubscribe(nameof(CanEntityTakeDamage));
  204.     Unsubscribe(nameof(OnCargoPlaneSignaled));
  205.     Unsubscribe(nameof(OnCargoShipEgress));
  206.     Unsubscribe(nameof(OnCargoShipHarborApproach));
  207.     Unsubscribe(nameof(OnCargoShipHarborArrived));
  208.     Unsubscribe(nameof(OnCargoShipHarborLeave));
  209.     Unsubscribe(nameof(OnCrateHack));
  210.     Unsubscribe(nameof(OnCrateHackEnd));
  211.     Unsubscribe(nameof(OnDieselEngineToggled));
  212.     Unsubscribe(nameof(OnEnterZone));
  213.     Unsubscribe(nameof(OnEntityDeath));
  214.     Unsubscribe(nameof(OnEntityKill));
  215.     Unsubscribe(nameof(OnEntitySpawned));
  216.     Unsubscribe(nameof(OnExitZone));
  217.     Unsubscribe(nameof(OnLootEntity));
  218.     Unsubscribe(nameof(OnLootLockedEntity));
  219.     Unsubscribe(nameof(OnPlayerCommand));
  220.     Unsubscribe(nameof(OnPlayerDeath));
  221.     Unsubscribe(nameof(OnRestoreUponDeath));
  222.     Unsubscribe(nameof(OnServerCommand));
  223.     Unsubscribe(nameof(OnSupplyDropLanded));
  224.     foreach (var category in _hooksByCategory.Keys)
  225.     {
  226.       _subscriptionsByCategory[category] = false;
  227.     }
  228.  
  229.     if (_configData.Global.LogToFile)
  230.     {
  231.       _debugStringBuilder = Pool.Get<StringBuilder>();
  232.     }
  233.  
  234.     // setup new TruePVE "ExcludePlayer" support
  235.     _useExcludePlayer = _configData.Global.UseExcludePlayer;
  236.     // if ExcludePlayer is disabled in config but is supported...
  237.     if (!_useExcludePlayer &&
  238.         null != TruePVE &&
  239.         TruePVE.Version >= new VersionNumber(2, 2, 3))
  240.     {
  241.       // ...and all PVP delays are enabled, auto-enable internally and warn
  242.       if ((PvpDelayTypes.ZonePlayersCanDamageDelayedPlayers |
  243.            PvpDelayTypes.DelayedPlayersCanDamageZonePlayers |
  244.            PvpDelayTypes.DelayedPlayersCanDamageDelayedPlayers) ==
  245.           _configData.Global.PvpDelayFlags)
  246.       {
  247.         _useExcludePlayer = true;
  248.         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");
  249.       }
  250.       // else just nag, since settings are not compatible
  251.       else
  252.       {
  253.         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");
  254.       }
  255.     } // else ExcludePlayer is already enabled, or TruePVE 2.2.3+ not running
  256.   }
  257.  
  258.   private void OnServerInitialized()
  259.   {
  260.     if (null == ZoneManager ||
  261.         ZoneManager.Version < new VersionNumber(3, 1, 10))
  262.     {
  263.       PrintError("Zone Manager missing or outdated; please update for proper function of this plugin!");
  264.     }
  265.  
  266.     if (_configData.GeneralEvents.ExcavatorIgnition.Enabled)
  267.     {
  268.       Subscribe(nameof(OnDieselEngineToggled));
  269.     }
  270.     if (_configData.GeneralEvents.PatrolHelicopter.Enabled ||
  271.         _configData.GeneralEvents.BradleyApc.Enabled)
  272.     {
  273.       Subscribe(nameof(OnEntityDeath));
  274.     }
  275.     if (_configData.GeneralEvents.SupplySignal.Enabled ||
  276.         _configData.GeneralEvents.TimedSupply.Enabled)
  277.     {
  278.       // this is subscribed if either drop event is enabled, because we need to
  279.       //  differentiate either way
  280.       Subscribe(nameof(OnCargoPlaneSignaled));
  281.       Subscribe(nameof(OnSupplyDropDropped));
  282.       // this is now subscribed regardless of start on spawn-vs-landing, as we
  283.       //  need to tether the zone to the drop on landing in both cases
  284.       Subscribe(nameof(OnSupplyDropLanded));
  285.     }
  286.     if (_configData.GeneralEvents.HackableCrate.Enabled &&
  287.         _configData.GeneralEvents.HackableCrate.TimerStartWhenUnlocked)
  288.     {
  289.       Subscribe(nameof(OnCrateHackEnd));
  290.     }
  291.     if ((_configData.GeneralEvents.TimedSupply.Enabled &&
  292.          _configData.GeneralEvents.TimedSupply.TimerStartWhenLooted) ||
  293.         (_configData.GeneralEvents.SupplySignal.Enabled &&
  294.          _configData.GeneralEvents.SupplySignal.TimerStartWhenLooted) ||
  295.         (_configData.GeneralEvents.HackableCrate.Enabled &&
  296.          _configData.GeneralEvents.HackableCrate.TimerStartWhenLooted))
  297.     {
  298.       Subscribe(nameof(OnLootEntity));
  299.     }
  300.     if (_configData.GeneralEvents.HackableCrate.Enabled &&
  301.         !_configData.GeneralEvents.HackableCrate.StartWhenSpawned)
  302.     {
  303.       Subscribe(nameof(OnCrateHack));
  304.     }
  305.     if ((_configData.GeneralEvents.TimedSupply.Enabled &&
  306.          _configData.GeneralEvents.TimedSupply.StartWhenSpawned) ||
  307.         (_configData.GeneralEvents.SupplySignal.Enabled &&
  308.          _configData.GeneralEvents.SupplySignal.StartWhenSpawned) ||
  309.         (_configData.GeneralEvents.HackableCrate.Enabled &&
  310.          _configData.GeneralEvents.HackableCrate.StartWhenSpawned) ||
  311.          _configData.GeneralEvents.CargoShip.Enabled ||
  312.          _configData.DeepSeaEvents.GhostShip.Enabled ||
  313.          _configData.DeepSeaEvents.DeepSeaIsland.Enabled ||
  314.          _configData.DeepSeaEvents.IslandCannon.Enabled)
  315.     {
  316.       Subscribe(nameof(OnEntitySpawned));
  317.     }
  318.     if ((_configData.GeneralEvents.TimedSupply.Enabled &&
  319.          _configData.GeneralEvents.TimedSupply.StopWhenKilled) ||
  320.         (_configData.GeneralEvents.SupplySignal.Enabled &&
  321.          _configData.GeneralEvents.SupplySignal.StopWhenKilled) ||
  322.         (_configData.GeneralEvents.HackableCrate.Enabled &&
  323.          _configData.GeneralEvents.HackableCrate.StopWhenKilled) ||
  324.          _configData.GeneralEvents.CargoShip.Enabled ||
  325.          _configData.DeepSeaEvents.GhostShip.Enabled ||
  326.          _configData.DeepSeaEvents.DeepSeaIsland.Enabled ||
  327.          _configData.DeepSeaEvents.IslandCannon.Enabled)
  328.     {
  329.       Subscribe(nameof(OnEntityKill));
  330.     }
  331.     if (_configData.GeneralEvents.CargoShip.Enabled)
  332.     {
  333.       Subscribe(nameof(OnCargoShipEgress));
  334.       Subscribe(nameof(OnCargoShipHarborApproach));
  335.       Subscribe(nameof(OnCargoShipHarborArrived));
  336.       Subscribe(nameof(OnCargoShipHarborLeave));
  337.     }
  338.  
  339.     NextTick(() =>
  340.     {
  341.       _createEventsCoroutine =
  342.         ServerMgr.Instance.StartCoroutine(CreateEvents());
  343.     });
  344.   }
  345.  
  346.   private void Unload()
  347.   {
  348.     if (_createEventsCoroutine != null)
  349.     {
  350.       ServerMgr.Instance.StopCoroutine(_createEventsCoroutine);
  351.     }
  352.  
  353.     if (_activeDynamicZones.Count > 0)
  354.     {
  355.       PrintDebug($"Unload(): Deleting {_activeDynamicZones.Count} active zone(s)");
  356.       // copy zone keys to a temporary list, because each deletion will modify
  357.       //  _activeDynamicZones
  358.       var zoneKeys = Pool.Get<List<string>>();
  359.       zoneKeys.AddRange(_activeDynamicZones.Keys);
  360.       foreach (var key in zoneKeys)
  361.       {
  362.         DeleteDynamicZone(key);
  363.       }
  364.       Pool.FreeUnmanaged(ref zoneKeys);
  365.       _activeDynamicZones.Clear();
  366.     }
  367.  
  368.     // copy LeftZone records to a temporary list to that we can reverse iterate
  369.     var leftZones = Pool.Get<List<LeftZone>>();
  370.     leftZones.AddRange(_pvpDelays.Values);
  371.     for (var i = leftZones.Count - 1; i >= 0; --i)
  372.     {
  373.       // this is cheating because it leaves leftZones[i] in a dangling state,
  374.       //  but it's okay because we're going to free/clear everything anyway
  375.       var value = leftZones[i];
  376.       Pool.Free(ref value);
  377.     }
  378.     Pool.FreeUnmanaged(ref leftZones);
  379.     _pvpDelays.Clear();
  380.     // also remove LeftZone class from pool framework, in case it changes on
  381.     //  plugin reload
  382.     Pool.Directory.TryRemove(typeof(LeftZone), out _);
  383.  
  384.     // copy sphere lists to a temporary list so that we can reverse iterate
  385.     var spheres = Pool.Get<List<List<SphereEntity>>>();
  386.     spheres.AddRange(_zoneSpheres.Values);
  387.     for (var i = _zoneSpheres.Count - 1; i >= 0; --i)
  388.     {
  389.       // this is cheating because it leaves spheres[i] in a dangling state, but
  390.       //  it's okay because we're going to free/clear everything anyway
  391.       var sphereEntities = spheres[i];
  392.       foreach (var sphereEntity in sphereEntities)
  393.       {
  394.         if (!sphereEntity || sphereEntity.IsDestroyed) continue;
  395.         sphereEntity.KillMessage();
  396.       }
  397.       Pool.FreeUnmanaged(ref sphereEntities);
  398.     }
  399.     Pool.FreeUnmanaged(ref spheres);
  400.     _zoneSpheres.Clear();
  401.  
  402.     SaveData();
  403.     SaveDebug();
  404.  
  405.     if (null == _debugStringBuilder) return;
  406.     Pool.FreeUnmanaged(ref _debugStringBuilder);
  407.     _debugStringBuilder = null;
  408.  
  409.     _originalMonumentGeometries.Clear();
  410.  
  411.     foreach (var apZone in _activePluginZones.Values)
  412.     {
  413.       // this is cheating because it leaves apZone in a dangling state, but it's
  414.       //  okay because we're going to clear the list just after this
  415.       var apZoneI = apZone;
  416.       Pool.FreeUnmanaged(ref apZoneI);
  417.     }
  418.     _activePluginZones.Clear();
  419.     DomeEvent._domeEventsToCheck = null;
  420.  
  421.     _activeSignaledPlanesAndDrops.Clear();
  422.   }
  423.  
  424.   private void OnServerSave() =>
  425.     timer.Once(UnityEngine.Random.Range(0f, 60f), () =>
  426.     {
  427.       SaveDebug();
  428.       if (!_dataChanged) return;
  429.       SaveData();
  430.       _dataChanged = false;
  431.     });
  432.  
  433.   private void OnPlayerRespawned(BasePlayer player)
  434.   {
  435.     if (!player || !player.userID.IsSteamId())
  436.     {
  437.       PrintDebug("OnPlayerRespawned(): Ignoring respawn of null/NPC player");
  438.       return;
  439.     }
  440.  
  441.     TryRemovePVPDelay(player);
  442.   }
  443.  
  444.   #endregion Oxide Hooks
  445.  
  446.   #region Methods
  447.  
  448.   private void TryRemoveEventTimer(string zoneId)
  449.   {
  450.     if (_eventTimers.Remove(zoneId, out var value))
  451.     {
  452.       value?.Destroy();
  453.     }
  454.   }
  455.  
  456.   private LeftZone GetOrAddPVPDelay(
  457.     BasePlayer player, string zoneId, string eventName, BaseEvent baseEvent)
  458.   {
  459.     PrintDebug($"GetOrAddPVPDelay(): Adding {player.displayName} to PVP delay");
  460.     var added = false;
  461.     if (_pvpDelays.TryGetValue(player.userID, out var leftZone))
  462.     {
  463.       leftZone.zoneTimer?.Destroy();
  464.     }
  465.     else
  466.     {
  467.       added = true;
  468.       leftZone = Pool.Get<LeftZone>();
  469.       _pvpDelays.Add(player.userID, leftZone);
  470.     }
  471.  
  472.     leftZone.zoneId = zoneId;
  473.     leftZone.eventName = eventName;
  474.     if (added)
  475.     {
  476.       CheckHooks(HookCheckReasons.DelayAdded, baseEvent);
  477.     }
  478.  
  479.     return leftZone;
  480.   }
  481.  
  482.   private bool TryRemovePVPDelay(BasePlayer player)
  483.   {
  484.     PrintDebug($"TryRemovePVPDelay(): Removing {player.displayName} from PVP delay");
  485.     var playerId = player.userID.Get();
  486.     if (!_pvpDelays.Remove(playerId, out var leftZone)) return false;
  487.     Interface.CallHook("OnPlayerRemovedFromPVPDelay",
  488.       playerId, leftZone.zoneId, player);
  489.     CheckHooks(HookCheckReasons.DelayRemoved, null); // baseEvent not needed
  490.     Pool.Free(ref leftZone);
  491.     return true;
  492.   }
  493.  
  494.   private bool CheckEntityOwner(BaseEntity baseEntity)
  495.   {
  496.     if (!_configData.Global.CheckEntityOwner ||
  497.         !baseEntity.OwnerID.IsSteamId() ||
  498.         // HeliSignals and BradleyDrops exception
  499.         baseEntity.skinID != 0)
  500.     {
  501.       return true;
  502.     }
  503.  
  504.     PrintDebug($"CheckEntityOwner(): Skipping event creation because baseEntity={baseEntity} is owned by player={baseEntity.OwnerID}");
  505.     return false;
  506.   }
  507.  
  508.   private bool CanCreateDynamicPVP(string eventName, BaseEntity entity)
  509.   {
  510.     if (Interface.CallHook("OnCreateDynamicPVP", eventName, entity) == null)
  511.     {
  512.       return true;
  513.     }
  514.  
  515.     PrintDebug($"CanCreateDynamicPVP(): Skipping event creation for eventName={eventName} due to OnCreateDynamicPVP hook result");
  516.     return false;
  517.   }
  518.  
  519.   private bool HasCommands()
  520.   {
  521.     // track which events we've checked, to avoid redundant calls to
  522.     //  GetBaseEvent(); note that use of pool API means we need to free this
  523.     //  on every return
  524.     var checkedEvents = Pool.Get<HashSet<string>>();
  525.     // check for command-containing zones referenced by PVP delays, which
  526.     //  either work when PVP delayed, or are an active zone
  527.     // HZ: I guess this is really trying to catch the corner case of players
  528.     //  in PVP delay because a zone expired?
  529.     foreach (var leftZone in _pvpDelays.Values)
  530.     {
  531.       var baseEvent = GetBaseEvent(leftZone.eventName);
  532.       if (baseEvent == null || baseEvent.CommandList.Count <= 0)
  533.       {
  534.         continue;
  535.       }
  536.  
  537.       if (baseEvent.CommandWorksForPVPDelay ||
  538.           _activeDynamicZones.ContainsValue(leftZone.eventName))
  539.       {
  540.         Pool.FreeUnmanaged(ref checkedEvents);
  541.         return true;
  542.       }
  543.  
  544.       checkedEvents.Add(leftZone.eventName);
  545.     }
  546.  
  547.     foreach (var eventName in _activeDynamicZones.Values)
  548.     {
  549.       // optimization: skip if we've already checked this in the other loop
  550.       if (checkedEvents.Contains(eventName))
  551.       {
  552.         continue;
  553.       }
  554.  
  555.       var baseEvent = GetBaseEvent(eventName);
  556.       if (null == baseEvent || baseEvent.CommandList.Count <= 0) continue;
  557.       Pool.FreeUnmanaged(ref checkedEvents);
  558.       return true;
  559.     }
  560.  
  561.     Pool.FreeUnmanaged(ref checkedEvents);
  562.     return false;
  563.   }
  564.  
  565.   /// toggle dynamic hook subscription(s) based on need
  566.   private void UpdateDynamicHook(
  567.     bool needSubscription, HookCategory hookCategory)
  568.   {
  569.     // abort if subscription tracking undefined, or subscription need already
  570.     //  met, or hooks not defined
  571.     if (!_subscriptionsByCategory.TryGetValue(
  572.           hookCategory, out var haveSubscription) ||
  573.         needSubscription == haveSubscription ||
  574.         !_hooksByCategory.TryGetValue(hookCategory, out var hooks))
  575.     {
  576.       return;
  577.     }
  578.  
  579.     // (un)subscribe per subscription need
  580.     foreach (var hook in hooks)
  581.     {
  582.       if (needSubscription)
  583.       {
  584.         Subscribe(hook);
  585.       }
  586.       else
  587.       {
  588.         Unsubscribe(hook);
  589.       }
  590.     }
  591.  
  592.     // record that we've achieved desired subscription state
  593.     _subscriptionsByCategory[hookCategory] = needSubscription;
  594.   }
  595.  
  596.   private void CheckCommandHooks(bool added)
  597.   {
  598.     // optimization: avoid calling HasCommands() if added + already subscribed
  599.     if (added &&
  600.         _subscriptionsByCategory.TryGetValue(
  601.           HookCategory.Command, out var subscribed) &&
  602.         subscribed)
  603.     {
  604.       return;
  605.     }
  606.  
  607.     UpdateDynamicHook(HasCommands(), HookCategory.Command);
  608.   }
  609.  
  610.   /// update plugin integration tracking/subscriptions as appropriate
  611.   private void CheckPluginHooks(BaseEvent baseEvent)
  612.   {
  613.     // this currently only supports checks when baseEvent is provided
  614.     if (null == baseEvent) return;
  615.  
  616.     foreach (
  617.       PluginZoneCategory pzCat in Enum.GetValues(typeof(PluginZoneCategory)))
  618.     {
  619.       if (HasPluginZoneCategory(baseEvent, pzCat))
  620.       {
  621.         UpdateDynamicHook(
  622.           _activePluginZones[pzCat].Count > 0, ToHookCategory(pzCat));
  623.       }
  624.     }
  625.   }
  626.  
  627.   private void CheckPvpDelayHooks() =>
  628.     UpdateDynamicHook(
  629.       !_useExcludePlayer && _pvpDelays.Count > 0, HookCategory.PvpDelay);
  630.  
  631.   private void CheckZoneHooks() =>
  632.     UpdateDynamicHook(_activeDynamicZones.Count > 0, HookCategory.Zone);
  633.  
  634.   /// check whether hook subscription changes are warranted
  635.   //
  636.   // baseEvent is used as an optimization to only check plugin integration
  637.   //  hook subscriptions when relevant zones are added/removed
  638.   private void CheckHooks(HookCheckReasons reasons, BaseEvent baseEvent)
  639.   {
  640.     // update command hooks based on PVP delay or zone changes
  641.     if (reasons.HasFlag(HookCheckReasons.DelayAdded) ||
  642.         reasons.HasFlag(HookCheckReasons.ZoneAdded))
  643.     {
  644.       CheckCommandHooks(true);
  645.     }
  646.     else if (reasons.HasFlag(HookCheckReasons.DelayRemoved) ||
  647.              reasons.HasFlag(HookCheckReasons.ZoneRemoved))
  648.     {
  649.       CheckCommandHooks(false);
  650.     }
  651.  
  652.     // update PVP delay hooks based on PVP delay changes
  653.     if (reasons.HasFlag(HookCheckReasons.DelayAdded) ||
  654.         reasons.HasFlag(HookCheckReasons.DelayRemoved))
  655.     {
  656.       CheckPvpDelayHooks();
  657.     }
  658.  
  659.     // update plugin and zone hooks based on zone changes
  660.     if (reasons.HasFlag(HookCheckReasons.ZoneAdded) ||
  661.         reasons.HasFlag(HookCheckReasons.ZoneRemoved))
  662.     {
  663.       CheckPluginHooks(baseEvent);
  664.       CheckZoneHooks();
  665.     }
  666.   }
  667.  
  668.   private BaseEvent GetBaseEvent(string eventName)
  669.   {
  670.     if (string.IsNullOrEmpty(eventName))
  671.     {
  672.       throw new ArgumentNullException(nameof(eventName));
  673.     }
  674.  
  675.     if (Interface.CallHook("OnGetBaseEvent", eventName)
  676.         is BaseEvent externalEvent)
  677.     {
  678.       return externalEvent;
  679.     }
  680.  
  681.     if (Enum.IsDefined(typeof(GeneralEventType), eventName) &&
  682.         Enum.TryParse(eventName, true, out GeneralEventType generalEventType))
  683.     {
  684.       switch (generalEventType)
  685.       {
  686.         case GeneralEventType.Bradley:
  687.           return _configData.GeneralEvents.BradleyApc;
  688.         case GeneralEventType.Helicopter:
  689.           return _configData.GeneralEvents.PatrolHelicopter;
  690.         case GeneralEventType.SupplyDrop:
  691.           return _configData.GeneralEvents.TimedSupply;
  692.         case GeneralEventType.SupplySignal:
  693.           return _configData.GeneralEvents.SupplySignal;
  694.         case GeneralEventType.CargoShip:
  695.           return _configData.GeneralEvents.CargoShip;
  696.         case GeneralEventType.HackableCrate:
  697.           return _configData.GeneralEvents.HackableCrate;
  698.         case GeneralEventType.ExcavatorIgnition:
  699.           return _configData.GeneralEvents.ExcavatorIgnition;
  700.         case GeneralEventType.GhostShip:
  701.           return _configData.DeepSeaEvents.GhostShip;
  702.         case GeneralEventType.DeepSeaIsland:
  703.           return _configData.DeepSeaEvents.DeepSeaIsland;
  704.         case GeneralEventType.IslandCannon:
  705.           return _configData.DeepSeaEvents.IslandCannon;
  706.         default:
  707.           PrintDebug(
  708.             $"GetBaseEvent(): ERROR: Missing BaseEvent lookup for generalEventType={generalEventType} for eventName={eventName}.",
  709.             DebugLevel.Error);
  710.           return null;
  711.       }
  712.     }
  713.  
  714.     if (_storedData.autoEvents.TryGetValue(eventName, out var autoEvent))
  715.     {
  716.       return autoEvent;
  717.     }
  718.  
  719.     if (_storedData.timedEvents.TryGetValue(eventName, out var timedEvent))
  720.     {
  721.       return timedEvent;
  722.     }
  723.  
  724.     if (_configData.MonumentEvents.TryGetValue(
  725.           eventName, out var monumentEvent))
  726.     {
  727.       return monumentEvent;
  728.     }
  729.  
  730.     PrintDebug($"GetBaseEvent(): ERROR: Failed to get base event settings for {eventName}", DebugLevel.Error);
  731.     return null;
  732.   }
  733.  
  734.   #endregion Methods
  735.  
  736.   #region Events
  737.  
  738.   #region Startup
  739.  
  740.   // utility method to return an appropriate yield instruction based on
  741.   //  whether this is a long pause for debug logging to catch up, whether
  742.   //  current server framerate is too low, etc.
  743.   private YieldInstruction DynamicYield(bool pause = false)
  744.   {
  745.     // perform one-time caching of target FPS
  746.     if (_targetFps <= 0) _targetFps = Mathf.Min(ConVar.FPS.limit, 30);
  747.  
  748.     return
  749.       pause && _configData.Global.DebugEnabled ? _pauseYield :
  750.       Performance.report.frameRate >= _targetFps ? _fastYield :
  751.       _throttleYield;
  752.   }
  753.  
  754.   // coroutine to orchestrate creation of all relevant events on startup
  755.   private IEnumerator CreateEvents()
  756.   {
  757.     var startTime = DateTime.UtcNow;
  758.     Puts("Creating General Events");
  759.     yield return CreateGeneralEvents();
  760.     // this will get logged at a lower level
  761.     yield return CreateMonumentEvents();
  762.     Puts("Creating Auto Events");
  763.     yield return CreateAutoEvents();
  764.     _createEventsCoroutine = null;
  765.     Puts($"Startup event creation completed in {(DateTime.UtcNow - startTime).TotalSeconds} seconds");
  766.   }
  767.  
  768.   #endregion Startup
  769.  
  770.   #region General Event
  771.  
  772.   // coroutine to determine whether any General Events should be created based
  773.   //  on currently existing entities of interest
  774.   // this is expected to only be called on startup
  775.   private IEnumerator CreateGeneralEvents()
  776.   {
  777.     // determine up-front whether there are any general events to create,
  778.     //  because iterating over all net entities is not cheap
  779.     var checkGeneralEvents = false;
  780.     // TODO: Bradley, Patrol Helicopter, Supply Drop, Timed Supply
  781.     checkGeneralEvents |= _configData.GeneralEvents.CargoShip.Enabled;
  782.     // NOTE: StopWhenKilled is checked because we don't want to start events
  783.     //  whose end is determined by a timer, as we don't know elapsed times
  784.     checkGeneralEvents |=
  785.       _configData.GeneralEvents.HackableCrate.Enabled &&
  786.       _configData.GeneralEvents.HackableCrate.StopWhenKilled;
  787.     checkGeneralEvents |= _configData.GeneralEvents.ExcavatorIgnition.Enabled;
  788.     if (checkGeneralEvents)
  789.     {
  790.       foreach (var serverEntity in BaseNetworkable.serverEntities)
  791.       {
  792.         switch (serverEntity)
  793.         {
  794.           // Island Cannon Event
  795.           case Cannon cannon:
  796.             StartupIslandCannon(cannon);
  797.             yield return DynamicYield();
  798.             break;
  799.           // Cargo Ship Event
  800.           case CargoShip cargoShip:
  801.             StartupCargoShip(cargoShip);
  802.             yield return DynamicYield();
  803.             break;
  804.           // Deep Sea Island Event
  805.           case DeepSeaIsland deepSeaIsland:
  806.             StartupDeepSeaIsland(deepSeaIsland);
  807.             yield return DynamicYield();
  808.             break;
  809.           // Excavator Ignition Event
  810.           case DieselEngine dieselEngine:
  811.             StartupDieselEngine(dieselEngine);
  812.             yield return DynamicYield();
  813.             break;
  814.           // Ghost Ship Event
  815.           case GhostShip ghostShip:
  816.             StartupGhostShip(ghostShip);
  817.             yield return DynamicYield();
  818.             break;
  819.           // Hackable Crate Event
  820.           case HackableLockedCrate hackableLockedCrate:
  821.             StartupHackableLockedCrate(hackableLockedCrate);
  822.             yield return DynamicYield();
  823.             break;
  824.         }
  825.       }
  826.     }
  827.  
  828.     yield return DynamicYield(true);
  829.   }
  830.  
  831.   #region ExcavatorIgnition Event
  832.  
  833.   // invoke appropriate hook handler for current DieselEngine state
  834.   // this is only used on startup, to (re)create events for already-existing
  835.   //  DieselEngine entities
  836.   private void StartupDieselEngine(DieselEngine dieselEngine)
  837.   {
  838.     if (!dieselEngine)
  839.     {
  840.       PrintDebug("StartupDieselEngine(): DieselEngine is null");
  841.       return;
  842.     }
  843.  
  844.     if (!_configData.GeneralEvents.ExcavatorIgnition.Enabled)
  845.     {
  846.       PrintDebug("StartupDieselEngine(): Excavator Ignition Event is disabled");
  847.       return;
  848.     }
  849.  
  850.     if (!dieselEngine.IsOn())
  851.     {
  852.       PrintDebug("StartupDieselEngine(): DieselEngine is off");
  853.       return;
  854.     }
  855.  
  856.     PrintDebug("StartupDieselEngine(): Found activated Giant Excavator");
  857.     OnDieselEngineToggled(dieselEngine);
  858.   }
  859.  
  860.   private void OnDieselEngineToggled(DieselEngine dieselEngine)
  861.   {
  862.     if (!dieselEngine || null == dieselEngine.net)
  863.     {
  864.       PrintDebug("OnDieselEngineToggled(): ERROR: Engine or Net is null", DebugLevel.Error);
  865.       return;
  866.     }
  867.  
  868.     var zoneId = dieselEngine.net.ID.ToString();
  869.     if (dieselEngine.IsOn())
  870.     {
  871.       PrintDebug(
  872.         $"OnDieselEngineToggled(): Requesting 'just-in-case' delete of zoneId={zoneId} due to excavator enable");
  873.       DeleteDynamicZone(zoneId);
  874.       HandleGeneralEvent(
  875.         GeneralEventType.ExcavatorIgnition, dieselEngine, true);
  876.     }
  877.     else
  878.     {
  879.       PrintDebug($"OnDieselEngineToggled(): Scheduling delete of zoneId={zoneId} due to excavator disable");
  880.       HandleDeleteDynamicZone(zoneId);
  881.     }
  882.   }
  883.  
  884.   #endregion ExcavatorIgnition Event
  885.  
  886.   #region HackableLockedCrate Event
  887.  
  888.   // invoke appropriate hook handler for current HackableLockedCrate state
  889.   // this is only used on startup, to (re)create events for already-existing
  890.   //  HackableLockedCrate entities
  891.   private void StartupHackableLockedCrate(
  892.     HackableLockedCrate hackableLockedCrate)
  893.   {
  894.     if (!hackableLockedCrate)
  895.     {
  896.       PrintDebug("StartupHackableLockedCrate(): HackableLockedCrate is null");
  897.       return;
  898.     }
  899.  
  900.     if (!_configData.GeneralEvents.HackableCrate.Enabled)
  901.     {
  902.       PrintDebug("StartupHackableLockedCrate(): Hackable Crate Event is disabled");
  903.       return;
  904.     }
  905.  
  906.     if (!_configData.GeneralEvents.HackableCrate.StopWhenKilled)
  907.     {
  908.       PrintDebug("StartupHackableLockedCrate(): Hackable Crate Event doesn't stop when killed");
  909.       return;
  910.     }
  911.  
  912.     if (0 != hackableLockedCrate.FirstLooterId &&
  913.         _configData.GeneralEvents.HackableCrate.TimerStartWhenLooted)
  914.     {
  915.       // looted and stop after time since loot enabled
  916.       // we don't know elapsed time, so err on the side of assuming the event
  917.       //  has already ended
  918.       PrintDebug(
  919.         "StartupHackableLockedCrate(): Found looted hackable locked crate, and TimerStartWhenLooted set; ignoring because elapsed time unknown");
  920.     }
  921.     else if (
  922.       hackableLockedCrate.HasFlag(HackableLockedCrate.Flag_FullyHacked) &&
  923.       _configData.GeneralEvents.HackableCrate.TimerStartWhenUnlocked)
  924.     {
  925.       // unlocked and stop after time since unlock enabled
  926.       // we don't know elapsed time, so err on the side of assuming the event
  927.       //  has already ended
  928.       PrintDebug(
  929.         "StartupHackableLockedCrate(): Found unlocked hackable locked crate and TimerStartWhenUnlocked set; ignoring because elapsed time unknown");
  930.     }
  931.     else if (hackableLockedCrate.HasFlag(HackableLockedCrate.Flag_Hacking) &&
  932.              !_configData.GeneralEvents.HackableCrate.StartWhenSpawned)
  933.     {
  934.       // hacking and start on hacking enabled
  935.       PrintDebug("StartupHackableLockedCrate(): Found hacking hackable locked crate and StartWhenSpawned NOT set; triggering OnCrateHack()");
  936.       OnCrateHack(hackableLockedCrate);
  937.     }
  938.     else if (_configData.GeneralEvents.HackableCrate.StartWhenSpawned)
  939.     {
  940.       // any other state and start on spawn + stop when killed enabled
  941.       PrintDebug("StartupHackableLockedCrate(): Found hackable locked crate, and StartWhenSpawned set; triggering OnEntitySpawned()");
  942.       OnEntitySpawned(hackableLockedCrate);
  943.     }
  944.     else
  945.     {
  946.       PrintDebug(
  947.         "StartupHackableLockedCrate(): Found hackable locked crate, but ignoring because of either start on hack, or stop on timer with elapsed time unknown");
  948.     }
  949.   }
  950.  
  951.   private void OnEntitySpawned(HackableLockedCrate hackableLockedCrate)
  952.   {
  953.     if (!hackableLockedCrate || null == hackableLockedCrate.net)
  954.     {
  955.       PrintDebug("StartupHackableLockedCrate(): ERROR: Crate or Net is null", DebugLevel.Error);
  956.       return;
  957.     }
  958.  
  959.     if (!_configData.GeneralEvents.HackableCrate.Enabled ||
  960.         !_configData.GeneralEvents.HackableCrate.StartWhenSpawned)
  961.     {
  962.       PrintDebug("OnEntitySpawned(HackableLockedCrate): Ignoring due to event or spawn start disabled");
  963.       return;
  964.     }
  965.  
  966.     PrintDebug("StartupHackableLockedCrate(): Trying to create hackable crate spawn event");
  967.     NextTick(() => LockedCrateEvent(hackableLockedCrate));
  968.   }
  969.  
  970.   private void OnCrateHack(HackableLockedCrate hackableLockedCrate)
  971.   {
  972.     if (!hackableLockedCrate || null == hackableLockedCrate.net)
  973.     {
  974.       PrintDebug("OnCrateHack(): ERROR: Crate or Net is null", DebugLevel.Error);
  975.       return;
  976.     }
  977.  
  978.     PrintDebug("OnCrateHack(): Trying to create hackable crate hack event");
  979.     NextTick(() => LockedCrateEvent(hackableLockedCrate));
  980.   }
  981.  
  982.   private void OnCrateHackEnd(HackableLockedCrate hackableLockedCrate)
  983.   {
  984.     if (!hackableLockedCrate || null == hackableLockedCrate.net)
  985.     {
  986.       PrintDebug("OnCrateHackEnd(): ERROR: Crate or Net is null", DebugLevel.Error);
  987.       return;
  988.     }
  989.  
  990.     var zoneId = hackableLockedCrate.net.ID.ToString();
  991.     PrintDebug(
  992.       $"OnCrateHackEnd(): Scheduling delete of zoneId={zoneId} in {_configData.GeneralEvents.HackableCrate.Duration}s");
  993.     HandleDeleteDynamicZone(
  994.       zoneId,
  995.       _configData.GeneralEvents.HackableCrate.Duration,
  996.       nameof(GeneralEventType.HackableCrate));
  997.   }
  998.  
  999.   private void OnLootEntity(
  1000.     BasePlayer player, HackableLockedCrate hackableLockedCrate)
  1001.   {
  1002.     if (!hackableLockedCrate || null == hackableLockedCrate.net)
  1003.     {
  1004.       PrintDebug("OnLootEntity(HackableLockedCrate): ERROR: Crate or Net is null", DebugLevel.Error);
  1005.       return;
  1006.     }
  1007.  
  1008.     if (!_configData.GeneralEvents.HackableCrate.Enabled ||
  1009.         !_configData.GeneralEvents.HackableCrate.TimerStartWhenLooted)
  1010.     {
  1011.       PrintDebug("OnLootEntity(HackableLockedCrate): Ignoring due to event or loot delay disabled");
  1012.       return;
  1013.     }
  1014.  
  1015.     var zoneId = hackableLockedCrate.net.ID.ToString();
  1016.     PrintDebug(
  1017.       $"OnLootEntity(HackableLockedCrate): Scheduling delete of zoneId={zoneId} in {_configData.GeneralEvents.HackableCrate.Duration}s");
  1018.     HandleDeleteDynamicZone(
  1019.       zoneId,
  1020.       _configData.GeneralEvents.HackableCrate.Duration,
  1021.       nameof(GeneralEventType.HackableCrate));
  1022.   }
  1023.  
  1024.   private void OnEntityKill(HackableLockedCrate hackableLockedCrate)
  1025.   {
  1026.     if (!hackableLockedCrate || null == hackableLockedCrate.net)
  1027.     {
  1028.       PrintDebug("OnEntityKill(HackableLockedCrate): ERROR: Crate or Net is null", DebugLevel.Error);
  1029.       return;
  1030.     }
  1031.  
  1032.     if (!_configData.GeneralEvents.HackableCrate.Enabled ||
  1033.         !_configData.GeneralEvents.HackableCrate.StopWhenKilled)
  1034.     {
  1035.       PrintDebug("OnEntityKill(HackableLockedCrate): Ignoring due to event or kill stop disabled");
  1036.       return;
  1037.     }
  1038.  
  1039.     var zoneId = hackableLockedCrate.net.ID.ToString();
  1040.     if (!_activeDynamicZones.ContainsKey(zoneId))
  1041.     {
  1042.       // no active zone for this hackable locked crate
  1043.       return;
  1044.     }
  1045.  
  1046.     // untether everything that we may have parented to the
  1047.     //  HackableLockedCrate so that they don't get killed along with it
  1048.     ZM_GetZoneByID(zoneId)?.transform.SetParent(null, true);
  1049.     ParentDome(zoneId, Vector3.zero);
  1050.  
  1051.     //When the timer starts, don't stop the event immediately
  1052.     if (_eventTimers.ContainsKey(zoneId))
  1053.     {
  1054.       PrintDebug(
  1055.         $"OnEntityKill(HackableLockedCrate): Ignoring due to event timer already active for zoneId={zoneId}");
  1056.       return;
  1057.     }
  1058.  
  1059.     PrintDebug($"OnEntityKill(HackableLockedCrate): Scheduling delete of zoneId={zoneId}");
  1060.     HandleDeleteDynamicZone(zoneId);
  1061.   }
  1062.  
  1063.   private void LockedCrateEvent(HackableLockedCrate hackableLockedCrate)
  1064.   {
  1065.     if (!CheckEntityOwner(hackableLockedCrate))
  1066.     {
  1067.       return;
  1068.     }
  1069.  
  1070.     if (_configData.GeneralEvents.HackableCrate.ExcludeOilRig &&
  1071.         IsOnTheOilRig(hackableLockedCrate))
  1072.     {
  1073.       PrintDebug("LockedCrateEvent(): The hackable locked crate is on an oil rig. Skipping event creation.");
  1074.       return;
  1075.     }
  1076.  
  1077.     if (_configData.GeneralEvents.HackableCrate.ExcludeCargoShip &&
  1078.         IsOnTheCargoShip(hackableLockedCrate))
  1079.     {
  1080.       PrintDebug("LockedCrateEvent(): The hackable locked crate is on a cargo ship. Skipping event creation.");
  1081.       return;
  1082.     }
  1083.  
  1084.     if (_configData.GeneralEvents.HackableCrate.ExcludeGhostShip &&
  1085.         IsOnGhostShip(hackableLockedCrate))
  1086.     {
  1087.       PrintDebug("LockedCrateEvent(): The hackable locked crate is on a ghost ship. Skipping event creation.");
  1088.       return;
  1089.     }
  1090.  
  1091.     // call this here, because otherwise it's difficult to ensure that we call
  1092.     //  it exactly once
  1093.     const string eventName = nameof(GeneralEventType.HackableCrate);
  1094.     if (!CanCreateDynamicPVP(eventName, hackableLockedCrate))
  1095.     {
  1096.       return;
  1097.     }
  1098.  
  1099.     // NOTE: we are already NextTick() protected here
  1100.     HandleParentedEntityEvent(
  1101.       eventName, hackableLockedCrate, parentOnCreate: true);
  1102.   }
  1103.  
  1104.   private static bool IsOnTheCargoShip
  1105.     (HackableLockedCrate hackableLockedCrate) =>
  1106.     true == hackableLockedCrate?.transform.parent?.HasComponent<CargoShip>();
  1107.  
  1108.   private static bool IsOnGhostShip(HackableLockedCrate hackableLockedCrate) =>
  1109.     true == hackableLockedCrate?.transform.parent?.HasComponent<GhostShip>();
  1110.  
  1111.   private bool IsOnTheOilRig(HackableLockedCrate hackableLockedCrate)
  1112.   {
  1113.     // this may now get called before monument event creation if hackable
  1114.     //  crates exist on startup, so populate oilrig positions here if needed
  1115.     if (Vector3.zero == _oilRigPosition ||
  1116.         Vector3.zero == _largeOilRigPosition)
  1117.     {
  1118.       foreach (LandmarkInfo landmarkInfo in TerrainMeta.Path.Landmarks)
  1119.       {
  1120.         switch (landmarkInfo.name)
  1121.         {
  1122.           case PrefabLargeOilRig:
  1123.             _largeOilRigPosition = landmarkInfo.transform.position;
  1124.             break;
  1125.           case PrefabOilRig:
  1126.             _oilRigPosition = landmarkInfo.transform.position;
  1127.             break;
  1128.         }
  1129.  
  1130.         if (Vector3.zero != _oilRigPosition &&
  1131.             Vector3.zero != _largeOilRigPosition)
  1132.         {
  1133.           break;
  1134.         }
  1135.       }
  1136.     }
  1137.  
  1138.     if (_oilRigPosition != Vector3.zero && Vector3Ex.Distance2D(
  1139.           hackableLockedCrate.transform.position, _oilRigPosition) < 50f)
  1140.     {
  1141.       return true;
  1142.     }
  1143.  
  1144.     if (_largeOilRigPosition != Vector3.zero && Vector3Ex.Distance2D(
  1145.           hackableLockedCrate.transform.position, _largeOilRigPosition) < 50f)
  1146.     {
  1147.       return true;
  1148.     }
  1149.  
  1150.     return false;
  1151.   }
  1152.  
  1153.   #endregion HackableLockedCrate Event
  1154.  
  1155.   #region PatrolHelicopter And BradleyAPC Event
  1156.  
  1157.   private void OnEntityDeath(PatrolHelicopter patrolHelicopter, HitInfo info)
  1158.   {
  1159.     if (!patrolHelicopter || null == patrolHelicopter.net)
  1160.     {
  1161.       return;
  1162.     }
  1163.  
  1164.     PatrolHelicopterEvent(patrolHelicopter);
  1165.   }
  1166.  
  1167.   private void OnEntityDeath(BradleyAPC bradleyApc, HitInfo info)
  1168.   {
  1169.     if (!bradleyApc || null == bradleyApc.net)
  1170.     {
  1171.       return;
  1172.     }
  1173.  
  1174.     BradleyApcEvent(bradleyApc);
  1175.   }
  1176.  
  1177.   private void PatrolHelicopterEvent(PatrolHelicopter patrolHelicopter)
  1178.   {
  1179.     if (!_configData.GeneralEvents.PatrolHelicopter.Enabled)
  1180.     {
  1181.       return;
  1182.     }
  1183.  
  1184.     PrintDebug("PatrolHelicopterEvent(): Trying to create Patrol Helicopter killed event.");
  1185.     if (!CheckEntityOwner(patrolHelicopter))
  1186.     {
  1187.       return;
  1188.     }
  1189.  
  1190.     HandleGeneralEvent(GeneralEventType.Helicopter, patrolHelicopter, false);
  1191.   }
  1192.  
  1193.   private void BradleyApcEvent(BradleyAPC bradleyAPC)
  1194.   {
  1195.     if (!_configData.GeneralEvents.BradleyApc.Enabled)
  1196.     {
  1197.       return;
  1198.     }
  1199.  
  1200.     PrintDebug("BradleyApcEvent(): Trying to create Bradley APC killed event.");
  1201.     if (!CheckEntityOwner(bradleyAPC))
  1202.     {
  1203.       return;
  1204.     }
  1205.  
  1206.     HandleGeneralEvent(GeneralEventType.Bradley, bradleyAPC, false);
  1207.   }
  1208.  
  1209.   #endregion PatrolHelicopter And BradleyAPC Event
  1210.  
  1211.   #region SupplyDrop And SupplySignal Event
  1212.  
  1213.   // stores NetIDs of active CargoPlane and SupplyDrop instances spawned by a
  1214.   //  SupplySignal
  1215.   private readonly HashSet<NetworkableId> _activeSignaledPlanesAndDrops = new();
  1216.  
  1217.   private void OnCargoPlaneSignaled(
  1218.     CargoPlane plane, SupplySignal signal) => NextTick(() =>
  1219.   {
  1220.     if (!plane || !signal)
  1221.     {
  1222.       return;
  1223.     }
  1224.  
  1225.     // record that plane was signaled
  1226.     var planeID = plane.net.ID;
  1227.     if (!_activeSignaledPlanesAndDrops.Add(planeID))
  1228.     {
  1229.       return;
  1230.     }
  1231.  
  1232.     PrintDebug($"OnCargoPlaneSignaled(): Supply Signal {signal.net.ID} spawned Cargo Plane {planeID} with drop position {plane.dropPosition}");
  1233.   });
  1234.  
  1235.   private void OnSupplyDropDropped(
  1236.     BaseEntity entity, CargoPlane plane) => NextTick(() =>
  1237.   {
  1238.     var supplyDrop = entity as SupplyDrop;
  1239.     if (!supplyDrop || null == supplyDrop.net ||
  1240.         !plane || null == plane.net)
  1241.     {
  1242.       return;
  1243.     }
  1244.  
  1245.     // if plane was signaled, record drop as signaled too
  1246.     var planeID = plane.net.ID;
  1247.     var supplyDropID = supplyDrop.net.ID;
  1248.     if (_activeSignaledPlanesAndDrops.Contains(planeID))
  1249.     {
  1250.       _activeSignaledPlanesAndDrops.Add(supplyDropID);
  1251.       PrintDebug($"OnSupplyDropDropped(): Signaled Cargo Plane {planeID} spawned Supply Drop {supplyDropID} at position {supplyDrop.transform.position}");
  1252.     }
  1253.     else
  1254.     {
  1255.       // must be a timed drop rather than a signaled one
  1256.       PrintDebug($"OnSupplyDropDropped(): Timed Cargo Plane {planeID} spawned Supply Drop {supplyDropID} at position {supplyDrop.transform.position}");
  1257.     }
  1258.  
  1259.     HandleSupplyDropEvent(supplyDrop, false);
  1260.   });
  1261.  
  1262.   private void OnSupplyDropLanded(SupplyDrop supplyDrop) => NextTick(() =>
  1263.   {
  1264.     if (!supplyDrop || null == supplyDrop.net)
  1265.     {
  1266.       return;
  1267.     }
  1268.  
  1269.     var zoneId = supplyDrop.net.ID.ToString();
  1270.     if (_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  1271.     {
  1272.       // event was already created on spawn; parent the event to the entity, so
  1273.       //  that they move together
  1274.       // NOTES:
  1275.       // - don't delete on failure, because leaving the existing zone on the
  1276.       //    ground is better than deleting it
  1277.       // - no need to delay parenting, as the zone presumably has already
  1278.       //    existed for a bit
  1279.       ParentEventToEntity(
  1280.         zoneId, GetBaseEvent(eventName), supplyDrop, deleteOnFailure: false,
  1281.         delay: false);
  1282.       return;
  1283.     }
  1284.  
  1285.     HandleSupplyDropEvent(supplyDrop, true);
  1286.   });
  1287.  
  1288.   private void OnLootEntity(BasePlayer _, SupplyDrop supplyDrop)
  1289.   {
  1290.     if (!supplyDrop || null == supplyDrop.net)
  1291.     {
  1292.       return;
  1293.     }
  1294.  
  1295.     var zoneId = supplyDrop.net.ID.ToString();
  1296.     if (!_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  1297.     {
  1298.       // no active zone for this supply drop
  1299.       return;
  1300.     }
  1301.  
  1302.     var eventConfig = eventName switch
  1303.     {
  1304.       nameof(GeneralEventType.SupplySignal) =>
  1305.         _configData.GeneralEvents.SupplySignal,
  1306.       nameof(GeneralEventType.SupplyDrop) =>
  1307.         _configData.GeneralEvents.TimedSupply,
  1308.       _ => null
  1309.     };
  1310.     if (null == eventConfig)
  1311.     {
  1312.       // pathological
  1313.       PrintDebug($"OnLootEntity(): Unknown SupplyDrop eventName={eventName} for zoneId={zoneId}", DebugLevel.Warning);
  1314.       return;
  1315.     }
  1316.  
  1317.     if (!eventConfig.Enabled || !eventConfig.TimerStartWhenLooted)
  1318.     {
  1319.       return;
  1320.     }
  1321.  
  1322.     HandleDeleteDynamicZone(zoneId, eventConfig.Duration, eventName);
  1323.   }
  1324.  
  1325.   private void OnEntityKill(SupplyDrop supplyDrop)
  1326.   {
  1327.     if (!supplyDrop || null == supplyDrop.net)
  1328.     {
  1329.       PrintDebug("OnEntityKill(SupplyDrop): ERROR: Drop or Net is null", DebugLevel.Error);
  1330.       return;
  1331.     }
  1332.  
  1333.     var supplyDropID = supplyDrop.net.ID;
  1334.     _activeSignaledPlanesAndDrops.Remove(supplyDropID);
  1335.  
  1336.     var zoneId = supplyDropID.ToString();
  1337.     if (!_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  1338.     {
  1339.       // no active zone for this supply drop
  1340.       return;
  1341.     }
  1342.  
  1343.     // untether everything that we may have parented to the SupplyDrop so that
  1344.     //  they don't get killed along with it
  1345.     ZM_GetZoneByID(zoneId)?.transform.SetParent(null, true);
  1346.     ParentDome(zoneId, Vector3.zero);
  1347.  
  1348.     var eventConfig = eventName switch
  1349.     {
  1350.       nameof(GeneralEventType.SupplySignal) =>
  1351.         _configData.GeneralEvents.SupplySignal,
  1352.       nameof(GeneralEventType.SupplyDrop) =>
  1353.         _configData.GeneralEvents.TimedSupply,
  1354.       _ => null
  1355.     };
  1356.     if (eventConfig is not { Enabled: true } || !eventConfig.StopWhenKilled)
  1357.     {
  1358.       return;
  1359.     }
  1360.  
  1361.     // When the timer starts, don't stop the event immediately
  1362.     if (_eventTimers.ContainsKey(zoneId))
  1363.     {
  1364.       PrintDebug(
  1365.         $"OnEntityKill(SupplyDrop): Ignoring due to event timer already active for zoneId={zoneId}");
  1366.       return;
  1367.     }
  1368.  
  1369.     PrintDebug($"OnEntityKill(SupplyDrop): Scheduling delete of zoneId={zoneId}");
  1370.     HandleDeleteDynamicZone(zoneId);
  1371.   }
  1372.  
  1373.   private void OnEntityKill(CargoPlane plane)
  1374.   {
  1375.     if (!plane || null == plane.net)
  1376.     {
  1377.       return;
  1378.     }
  1379.  
  1380.     _activeSignaledPlanesAndDrops.Remove(plane.net.ID);
  1381.   }
  1382.  
  1383.   private static string GetSupplyDropConfigName(string eventName) =>
  1384.     eventName switch
  1385.     {
  1386.       nameof(GeneralEventType.SupplySignal) => "SupplySignal",
  1387.       nameof(GeneralEventType.SupplyDrop) => "TimedSupply",
  1388.       _ => $"<unknown:{eventName}>"
  1389.     };
  1390.  
  1391.   private static string GetSupplyDropStateName(bool isLanded) =>
  1392.     isLanded ? "Landed" : "Spawned";
  1393.  
  1394.   private void HandleSupplyDropEvent(SupplyDrop supplyDrop, bool isLanded)
  1395.   {
  1396.     if (!supplyDrop || null == supplyDrop.net)
  1397.     {
  1398.       return;
  1399.     }
  1400.  
  1401.     PrintDebug(
  1402.       $"HandleSupplyDropEvent(): Trying to create supply drop {GetSupplyDropStateName(isLanded)} event at {supplyDrop.transform.position}.");
  1403.     if (!CheckEntityOwner(supplyDrop))
  1404.     {
  1405.       return;
  1406.     }
  1407.  
  1408.     var supplyDropID = supplyDrop.net.ID;
  1409.     var isSignaled = _activeSignaledPlanesAndDrops.Contains(supplyDropID);
  1410.     if (isSignaled)
  1411.     {
  1412.       PrintDebug($"HandleSupplyDropEvent(): Supply Drop {supplyDropID} is from supply signal");
  1413.       HandleSupplyDropEvent(
  1414.         _configData.GeneralEvents.SupplySignal, isLanded,
  1415.         nameof(GeneralEventType.SupplySignal), supplyDrop);
  1416.     }
  1417.     else
  1418.     {
  1419.       PrintDebug($"HandleSupplyDropEvent(): Supply Drop {supplyDropID} is from timed event");
  1420.       HandleSupplyDropEvent(
  1421.         _configData.GeneralEvents.TimedSupply, isLanded,
  1422.         nameof(GeneralEventType.SupplyDrop), supplyDrop);
  1423.     }
  1424.   }
  1425.  
  1426.   private void HandleSupplyDropEvent(
  1427.     SupplyDropEvent eventConfig, bool isLanded, string eventName,
  1428.     SupplyDrop supplyDrop)
  1429.   {
  1430.     if (!eventConfig.Enabled)
  1431.     {
  1432.       PrintDebug($"HandleSupplyDropEvent(): Skipping event creation because supply drop event type is disabled: {GetSupplyDropConfigName(eventName)}");
  1433.       return;
  1434.     }
  1435.  
  1436.     // abort if:
  1437.     // - landed but configured to start on spawn, or
  1438.     // - not landed but configured to start on landing
  1439.     if (isLanded == eventConfig.StartWhenSpawned)
  1440.     {
  1441.       PrintDebug($"HandleSupplyDropEvent(): Skipping event creation because supply drop event state is disabled: {GetSupplyDropStateName(isLanded)}");
  1442.       return;
  1443.     }
  1444.  
  1445.     if (!CanCreateDynamicPVP(eventName, supplyDrop))
  1446.     {
  1447.       return;
  1448.     }
  1449.  
  1450.     HandleParentedEntityEvent(eventName, supplyDrop, parentOnCreate: isLanded);
  1451.   }
  1452.  
  1453.   #endregion SupplyDrop And SupplySignal Event
  1454.  
  1455.   #region CargoShip Event
  1456.  
  1457.   private bool IsLeavingHarbor(CargoShip cargoShip)
  1458.   {
  1459.     // abort if ship invalid, not doing approach sequence, or currently docked
  1460.     if (
  1461.       !cargoShip || !cargoShip.isDoingHarborApproach || cargoShip.IsShipDocked)
  1462.     {
  1463.       return false;
  1464.     }
  1465.  
  1466.     // abort with error if path object or node list is missing
  1467.     if (null == cargoShip.harborApproachPath?.nodes)
  1468.     {
  1469.       PrintError($"IsLeavingHarbor(): ERROR: Cargo ship at {cargoShip.transform.position} is on harbor docking sequence, but the path data is null");
  1470.       return false;
  1471.     }
  1472.  
  1473.     // scan the remaining approach path nodes to see if the docking node is
  1474.     //  still coming up
  1475.     for (var i = cargoShip.currentHarborApproachNode;
  1476.          i < cargoShip.harborApproachPath.nodes.Count;
  1477.          ++i)
  1478.     {
  1479.       if (cargoShip.harborApproachPath.nodes[i].maxVelocityOnApproach == 0.0f)
  1480.       {
  1481.         // this is the docking node, so it must still be approaching
  1482.         return false;
  1483.       }
  1484.     }
  1485.     // scanned all remaining nodes without finding the docking one, so it must
  1486.     //  have already docked and is leaving
  1487.     return true;
  1488.   }
  1489.  
  1490.   // invoke appropriate hook handler for current CargoShip state
  1491.   // this is only used on startup, to (re)create events for already-existing
  1492.   //  CargoShip entities
  1493.   private void StartupCargoShip(CargoShip cargoShip)
  1494.   {
  1495.     if (!cargoShip)
  1496.     {
  1497.       PrintDebug("StartupCargoShip(): CargoShip is null");
  1498.       return;
  1499.     }
  1500.  
  1501.     if (!_configData.GeneralEvents.CargoShip.Enabled)
  1502.     {
  1503.       PrintDebug("StartupCargoShip(): Cargo Ship Event is disabled");
  1504.       return;
  1505.     }
  1506.  
  1507.     if (cargoShip.HasFlag(CargoShip.Egressing))
  1508.     {
  1509.       // leaving the map
  1510.       PrintDebug("StartupCargoShip(): Found cargo ship in egress from the map");
  1511.       OnCargoShipEgress(cargoShip);
  1512.     }
  1513.     else if (cargoShip.isDoingHarborApproach)
  1514.     {
  1515.       // approaching, docked at, or leaving a Harbor
  1516.       if (cargoShip.IsShipDocked)
  1517.       {
  1518.         // docked at a Harbor
  1519.         PrintDebug("StartupCargoShip(): Found cargo ship docked at a Harbor");
  1520.         OnCargoShipHarborArrived(cargoShip);
  1521.       }
  1522.       else if (IsLeavingHarbor(cargoShip))
  1523.       {
  1524.         // leaving a Harbor
  1525.         PrintDebug("StartupCargoShip(): Found cargo ship leaving a Harbor");
  1526.         OnCargoShipHarborLeave(cargoShip);
  1527.       }
  1528.       else
  1529.       {
  1530.         // approaching a Harbor
  1531.         PrintDebug("StartupCargoShip(): Found cargo ship approaching a Harbor");
  1532.         OnCargoShipHarborApproach(cargoShip);
  1533.       }
  1534.     }
  1535.     else if (cargoShip.HasFlag(CargoShip.HasDocked))
  1536.     {
  1537.       // not doing anything of interest, but has previously docked, so treat as
  1538.       //  leaving harbor since that was the last state change of interest
  1539.       PrintDebug("StartupCargoShip(): Found cargo ship that has previously docked at a Harbor");
  1540.       OnCargoShipHarborLeave(cargoShip);
  1541.     }
  1542.     else
  1543.     {
  1544.       // not doing anything of interest, so treat as a normal spawn
  1545.       PrintDebug("StartupCargoShip(): Found cargo ship that has not approached a Harbor");
  1546.       OnEntitySpawned(cargoShip);
  1547.     }
  1548.   }
  1549.  
  1550.   // create/update or attempt to delete CargoShip event zone, based on
  1551.   //  specified desired state
  1552.   private void HandleCargoState(CargoShip cargoShip, bool state)
  1553.   {
  1554.     if (!cargoShip || null == cargoShip.net)
  1555.     {
  1556.       return;
  1557.     }
  1558.  
  1559.     if (!_configData.GeneralEvents.CargoShip.Enabled)
  1560.     {
  1561.       return;
  1562.     }
  1563.  
  1564.     // create/update or attempt to delete zone, based on desired state
  1565.     var zoneId = cargoShip.net.ID.ToString();
  1566.     var zoneExists = _activeDynamicZones.ContainsKey(zoneId);
  1567.     if (zoneExists == state)
  1568.     {
  1569.       PrintDebug($"HandleCargoState(): CargoShip event {zoneId} is already in desired state={state}");
  1570.       return;
  1571.     }
  1572.  
  1573.     if (state)
  1574.     {
  1575.       PrintDebug($"HandleCargoState(): Trying to create CargoShip post-spawn event {zoneId}");
  1576.       if (!CheckEntityOwner(cargoShip))
  1577.       {
  1578.         return;
  1579.       }
  1580.  
  1581.       const string eventName = nameof(GeneralEventType.CargoShip);
  1582.       // call this here, because otherwise it's difficult to ensure that we
  1583.       //  call it exactly once
  1584.       if (!CanCreateDynamicPVP(eventName, cargoShip))
  1585.       {
  1586.         return;
  1587.       }
  1588.  
  1589.       NextTick(() => HandleParentedEntityEvent(
  1590.         eventName, cargoShip, parentOnCreate: true));
  1591.     }
  1592.     else
  1593.     {
  1594.       PrintDebug($"HandleCargoState(): Trying to delete CargoShip post-spawn event {zoneId}");
  1595.       HandleDeleteDynamicZone(zoneId);
  1596.     }
  1597.   }
  1598.  
  1599.   private void OnEntitySpawned(CargoShip cargoShip)
  1600.   {
  1601.     if (!cargoShip || null == cargoShip.net)
  1602.     {
  1603.       // bad entity
  1604.       return;
  1605.     }
  1606.  
  1607.     if (!_configData.GeneralEvents.CargoShip.Enabled ||
  1608.         !_configData.GeneralEvents.CargoShip.SpawnState)
  1609.     {
  1610.       // not configured to create event on spawn
  1611.       return;
  1612.     }
  1613.  
  1614.     PrintDebug("OnEntitySpawned(CargoShip): Trying to create CargoShip spawn event");
  1615.     if (!CheckEntityOwner(cargoShip))
  1616.     {
  1617.       return;
  1618.     }
  1619.  
  1620.     const string eventName = nameof(GeneralEventType.CargoShip);
  1621.     // call this here, because otherwise it's difficult to ensure that we call
  1622.     //  it exactly once
  1623.     if (!CanCreateDynamicPVP(eventName, cargoShip))
  1624.     {
  1625.       return;
  1626.     }
  1627.  
  1628.     NextTick(() =>
  1629.       HandleParentedEntityEvent(eventName, cargoShip, parentOnCreate: true));
  1630.   }
  1631.  
  1632.   private void OnEntityKill(CargoShip cargoShip)
  1633.   {
  1634.     if (!cargoShip || null == cargoShip.net)
  1635.     {
  1636.       return;
  1637.     }
  1638.  
  1639.     if (!_configData.GeneralEvents.CargoShip.Enabled)
  1640.     {
  1641.       return;
  1642.     }
  1643.  
  1644.     HandleDeleteDynamicZone(cargoShip.net.ID.ToString());
  1645.   }
  1646.  
  1647.   private void OnCargoShipEgress(CargoShip cargoShip) =>
  1648.     HandleCargoState(
  1649.       cargoShip, _configData.GeneralEvents.CargoShip.EgressState);
  1650.  
  1651.   private void OnCargoShipHarborApproach(CargoShip cargoShip) =>
  1652.     HandleCargoState(
  1653.       cargoShip, _configData.GeneralEvents.CargoShip.ApproachState);
  1654.  
  1655.   private void OnCargoShipHarborArrived(CargoShip cargoShip) =>
  1656.     HandleCargoState(
  1657.       cargoShip, _configData.GeneralEvents.CargoShip.DockState);
  1658.  
  1659.   private void OnCargoShipHarborLeave(CargoShip cargoShip) =>
  1660.     HandleCargoState(
  1661.       cargoShip, _configData.GeneralEvents.CargoShip.DepartState);
  1662.  
  1663.   #endregion CargoShip Event
  1664.  
  1665.   #region GhostShip Event
  1666.  
  1667.   private void StartupGhostShip(GhostShip ghostShip) =>
  1668.     OnEntitySpawned(ghostShip);
  1669.  
  1670.   private void OnEntitySpawned(GhostShip ghostShip)
  1671.   {
  1672.     if (!ghostShip || null == ghostShip.net)
  1673.     {
  1674.       PrintDebug("OnEntitySpawned(GhostShip): ERROR: GhostShip or Net is null", DebugLevel.Error);
  1675.       return;
  1676.     }
  1677.  
  1678.     if (!_configData.DeepSeaEvents.GhostShip.Enabled)
  1679.     {
  1680.       PrintDebug("OnEntitySpawned(GhostShip): Ignoring due to event disabled");
  1681.       return;
  1682.     }
  1683.  
  1684.     PrintDebug("OnEntitySpawned(GhostShip): Trying to create Ghost Ship event");
  1685.     if (!CheckEntityOwner(ghostShip))
  1686.     {
  1687.       return;
  1688.     }
  1689.  
  1690.     // center event at sea level
  1691.     HandleGeneralEvent(
  1692.       GeneralEventType.GhostShip, ghostShip, true, EventHeightStrategy.Zero);
  1693.   }
  1694.  
  1695.   private void OnEntityKill(GhostShip ghostShip)
  1696.   {
  1697.     if (!ghostShip || null == ghostShip.net)
  1698.     {
  1699.       return;
  1700.     }
  1701.  
  1702.     if (!_configData.DeepSeaEvents.GhostShip.Enabled)
  1703.     {
  1704.       return;
  1705.     }
  1706.  
  1707.     HandleDeleteDynamicZone(ghostShip.net.ID.ToString());
  1708.   }
  1709.  
  1710.   #endregion GhostShip Event
  1711.  
  1712.   #region DeepSeaIsland Event
  1713.  
  1714.   private void StartupDeepSeaIsland(DeepSeaIsland deepSeaIsland) =>
  1715.     OnEntitySpawned(deepSeaIsland);
  1716.  
  1717.   private void OnEntitySpawned(DeepSeaIsland deepSeaIsland)
  1718.   {
  1719.     if (!deepSeaIsland || null == deepSeaIsland.net)
  1720.     {
  1721.       PrintDebug("OnEntitySpawned(DeepSeaIsland): ERROR: DeepSeaIsland or Net is null", DebugLevel.Error);
  1722.       return;
  1723.     }
  1724.  
  1725.     if (!_configData.DeepSeaEvents.DeepSeaIsland.Enabled)
  1726.     {
  1727.       PrintDebug("OnEntitySpawned(DeepSeaIsland): Ignoring due to event disabled");
  1728.       return;
  1729.     }
  1730.  
  1731.     PrintDebug("OnEntitySpawned(DeepSeaIsland): Trying to create Deep Sea Island event");
  1732.     if (!CheckEntityOwner(deepSeaIsland))
  1733.     {
  1734.       return;
  1735.     }
  1736.  
  1737.     // center event at sea level
  1738.     HandleIslandEvent(deepSeaIsland);
  1739.   }
  1740.  
  1741.   private void OnEntityKill(DeepSeaIsland deepSeaIsland)
  1742.   {
  1743.     if (!deepSeaIsland || null == deepSeaIsland.net)
  1744.     {
  1745.       return;
  1746.     }
  1747.  
  1748.     if (!_configData.DeepSeaEvents.DeepSeaIsland.Enabled)
  1749.     {
  1750.       return;
  1751.     }
  1752.  
  1753.     HandleDeleteDynamicZone(deepSeaIsland.net.ID.ToString());
  1754.   }
  1755.  
  1756.   #endregion DeepSeaIsland Event
  1757.  
  1758.   #region IslandCannon Event
  1759.  
  1760.   private void StartupIslandCannon(Cannon cannon) => OnEntitySpawned(cannon);
  1761.  
  1762.   private void OnEntitySpawned(Cannon cannon)
  1763.   {
  1764.     if (!cannon || null == cannon.net)
  1765.     {
  1766.       PrintDebug("OnEntitySpawned(Cannon): ERROR: Cannon or Net is null", DebugLevel.Error);
  1767.       return;
  1768.     }
  1769.  
  1770.     if (!_configData.DeepSeaEvents.IslandCannon.Enabled)
  1771.     {
  1772.       PrintDebug("OnEntitySpawned(Cannon): Ignoring due to event disabled");
  1773.       return;
  1774.     }
  1775.  
  1776.     // only create zones for static land-based cannons
  1777.     var cannonPrefab = cannon.ShortPrefabName;
  1778.     if ("cannon.land.static" != cannonPrefab)
  1779.     {
  1780.       // also suppress debug log for deployed cannons (e.g. on player boats)
  1781.       if ("cannon.deployed" != cannonPrefab)
  1782.       {
  1783.         PrintDebug($"OnEntitySpawned(Cannon): Ignoring unsupported Cannon prefab '{cannonPrefab}'");
  1784.       }
  1785.       return;
  1786.     }
  1787.  
  1788.     PrintDebug("OnEntitySpawned(Cannon): Trying to create Island Cannon event");
  1789.     if (!CheckEntityOwner(cannon))
  1790.     {
  1791.       return;
  1792.     }
  1793.  
  1794.     HandleGeneralEvent(GeneralEventType.IslandCannon, cannon, true);
  1795.   }
  1796.  
  1797.   private void OnEntityKill(Cannon cannon)
  1798.   {
  1799.     if (!cannon || null == cannon.net)
  1800.     {
  1801.       return;
  1802.     }
  1803.  
  1804.     if (!_configData.DeepSeaEvents.IslandCannon.Enabled)
  1805.     {
  1806.       return;
  1807.     }
  1808.  
  1809.     HandleDeleteDynamicZone(cannon.net.ID.ToString());
  1810.   }
  1811.  
  1812.   #endregion IslandCannon Event
  1813.  
  1814.   #endregion General Event
  1815.  
  1816.   #region Monument Event
  1817.  
  1818.   #region Automatic Geometry
  1819.  
  1820.   private static bool IsCustomPreventBuildingPrefab(string name) =>
  1821.     name is "assets/bundled/prefabs/modding/volumes_and_triggers/prevent_building_cube.prefab"
  1822.       or "assets/bundled/prefabs/modding/volumes_and_triggers/prevent_building_sphere.prefab";
  1823.  
  1824.   // return Prevent Building collider that engulfs the given location, or null
  1825.   //  if none found
  1826.   // this only works for custom monuments, as vanilla ones hide their volumes
  1827.   //  within their monument transform/component trees
  1828.   // credit: WhiteThunder (Monument Finder)
  1829.   private Collider GetPreventBuildingCollider(Vector3 position)
  1830.   {
  1831.     var position2D = position.XZ2D();
  1832.     var count = Physics.OverlapSphereNonAlloc(
  1833.       position, 1, _colliderBuffer, Rust.Layers.Mask.Prevent_Building,
  1834.       QueryTriggerInteraction.Ignore);
  1835.  
  1836.     // scan discovered colliders (if any) and choose in decreasing priority
  1837.     //  order: closest, largest, first
  1838.     var mDist = float.MaxValue;
  1839.     var mSize = 0.0f;
  1840.     var mIndex = -1;
  1841.     for (var i = 0; i < count; ++i)
  1842.     {
  1843.       var collider = _colliderBuffer[i];
  1844.       // skip non-box/sphere colliders
  1845.       if (collider is not BoxCollider && collider is not SphereCollider)
  1846.       {
  1847.         continue;
  1848.       }
  1849.       // skip non-modding PB prefabs
  1850.       if (!IsCustomPreventBuildingPrefab(collider.name)) continue;
  1851.       // check 2D distance from reference position
  1852.       var center2D = GetCenter(collider).XZ2D();
  1853.       var dist = Vector2.Distance(position2D, center2D);
  1854.       var size = GetSize(collider);
  1855.       // choose closer colliders
  1856.       if (dist < mDist)
  1857.       {
  1858.         mDist = dist;
  1859.         mSize = size;
  1860.         mIndex = i;
  1861.         continue;
  1862.       }
  1863.       // skip more distance colliders
  1864.       if (dist > mDist) continue;
  1865.       // skip smaller or equal-but-later colliders
  1866.       if (size <= mSize) continue;
  1867.       // choose larger colliders
  1868.       mDist = dist;
  1869.       mSize = size;
  1870.       mIndex = i;
  1871.     }
  1872.  
  1873.     return mIndex >= 0 ? _colliderBuffer[mIndex] : null;
  1874.   }
  1875.  
  1876.   // get center of box or sphere collider, or collider's transform position if
  1877.   //  something else
  1878.   private static Vector3 GetCenter(Collider collider)
  1879.   {
  1880.     return collider switch
  1881.     {
  1882.       BoxCollider b => collider.transform.TransformPoint(b.center),
  1883.       SphereCollider s => collider.transform.TransformPoint(s.center),
  1884.       _ => collider.transform.position
  1885.     };
  1886.   }
  1887.  
  1888.   // get size of box or sphere collider, or zero if something else
  1889.   private static float GetSize(Collider collider)
  1890.   {
  1891.     return collider switch
  1892.     {
  1893.       BoxCollider b => b.size.magnitude,
  1894.       SphereCollider s => s.radius,
  1895.       _ => 0f
  1896.     };
  1897.   }
  1898.  
  1899.   // return most suitable Prevent Building collider that is attached somewhere
  1900.   //  under the given transform's child tree, or null if none found
  1901.   // this only works for vanilla monuments, as custom ones are global
  1902.   private static Collider GetPreventBuildingCollider(Transform transform)
  1903.   {
  1904.     if (!transform) return null;
  1905.  
  1906.     var list = Pool.Get<List<Collider>>();
  1907.     // prefer monument marker oriented bounds if available
  1908.     if (transform.TryGetComponent<MonumentInfo>(out var monumentInfo))
  1909.     {
  1910.       Vis.Colliders(
  1911.         monumentInfo.obbBounds, list, Rust.Layers.Mask.Prevent_Building);
  1912.     }
  1913.     else
  1914.     {
  1915.       // fall back to transform world bounds
  1916.       var tSize = transform.GetBounds().size.Max();
  1917.       if (tSize <= 0.0f)
  1918.       {
  1919.         // use a default hard-coded size (this seems to not trigger)
  1920.         tSize = 5.0f;
  1921.       }
  1922.       Vis.Colliders(
  1923.         transform.position, tSize, list, Rust.Layers.Mask.Prevent_Building);
  1924.     }
  1925.     // scan the list for optimal collider
  1926.     Collider mCollider = null;
  1927.     var mSize = 0.0f;
  1928.     var mDist = float.MaxValue;
  1929.     foreach (var collider in list)
  1930.     {
  1931.       // ignore if not under the main transform's child tree
  1932.       if (!collider.transform.IsChildOf(transform)) continue;
  1933.       var cSize = GetSize(collider);
  1934.       // ignore if unknown shape or zero size
  1935.       if (cSize <= 0) continue;
  1936.       // record if no previous candidate, or larger than previous candidate
  1937.       if (!mCollider || cSize > mSize)
  1938.       {
  1939.         mCollider = collider;
  1940.         mSize = cSize;
  1941.         mDist = Vector3.Distance(transform.position, GetCenter(collider));
  1942.         continue;
  1943.       }
  1944.       // ignore if smaller than largest found so far
  1945.       if (cSize < mSize) continue;
  1946.       // same size - choose the one closer to main transform
  1947.       var cCenter = GetCenter(collider);
  1948.       var cDist = Vector3.Distance(transform.position, cCenter);
  1949.       if (cDist >= mDist) continue;
  1950.       mCollider = collider;
  1951.       mSize = cSize;
  1952.       mDist = cDist;
  1953.     }
  1954.     Pool.FreeUnmanaged(ref list);
  1955.  
  1956.     return mCollider;
  1957.   }
  1958.  
  1959.   // return the largest Prevent Building collider found for the given monument
  1960.   //  transform and type, or null if none found
  1961.   private Collider GetPreventBuildingCollider(
  1962.     Transform transform, bool customMonument)
  1963.   {
  1964.     if (!transform) return null;
  1965.  
  1966.     return customMonument ?
  1967.       GetPreventBuildingCollider(transform.position) :
  1968.       GetPreventBuildingCollider(transform);
  1969.   }
  1970.  
  1971.   // apply Collider data to the given DynamicPVP zone parameters
  1972.   // used by GetPreventBuildingParams() to apply values before returning
  1973.   private static (Vector3 size, float rotation, Vector3 offset)
  1974.     ApplyColliderData(
  1975.       Collider collider, Vector3 size, float rotation, Vector3 offset)
  1976.   {
  1977.     if (!collider) return (Vector3.zero, 0.0f, Vector3.zero);
  1978.     switch (collider)
  1979.     {
  1980.       case BoxCollider b:
  1981.       {
  1982.         size.Scale(b.size);
  1983.         offset += b.center;
  1984.         break;
  1985.       }
  1986.       case SphereCollider s:
  1987.       {
  1988.         size *= s.radius;
  1989.         offset += s.center;
  1990.         break;
  1991.       }
  1992.       default:
  1993.       {
  1994.         return (Vector3.zero, 0.0f, Vector3.zero);
  1995.       }
  1996.     }
  1997.     return (size, rotation, offset);
  1998.   }
  1999.  
  2000.   // get cumulative size, rotation, offset of prevent building volume relative
  2001.   //  to given monument transform
  2002.   // if global=false, monument rotation is subtracted from volume rotation
  2003.   //  prior to normalizing (NOTE: custom monuments have global PB colliders,
  2004.   //  while vanilla ones attach them to their transform hierarchies)
  2005.   // returns all zeroes if something went wrong
  2006.   private static (Vector3 size, float rotation, Vector3 offset)
  2007.     GetPreventBuildingParams(
  2008.       Collider collider, Transform tMonument, bool global)
  2009.   {
  2010.     if (!collider || !tMonument)
  2011.     {
  2012.       return (Vector3.zero, 0.0f, Vector3.zero);
  2013.     }
  2014.  
  2015.     // collect the parent transform hierarchy into a list
  2016.     // for global colliders this will only collect the parent, but for all
  2017.     //  others it will collect everything below the root of the hierarchy
  2018.     var tList = Pool.Get<List<Transform>>();
  2019.     for (var transform = collider.transform;
  2020.          transform && transform != tMonument;
  2021.          transform = transform.parent)
  2022.     {
  2023.       tList.Add(transform);
  2024.       if (global) break;
  2025.     }
  2026.     // now walk the list backwards, accumulating offset+rotation+size values
  2027.     var offset = Vector3.zero;
  2028.     var rotation = Quaternion.identity;
  2029.     var size = Vector3.one;
  2030.     for (var i = tList.Count - 1; i >= 0; --i)
  2031.     {
  2032.       var transform = tList[i];
  2033.       offset += rotation * transform.localPosition;
  2034.       rotation *= transform.localRotation;
  2035.       size.Scale(transform.localScale);
  2036.     }
  2037.     Pool.FreeUnmanaged(ref tList);
  2038.  
  2039.     if (global)
  2040.     {
  2041.       // we actually calculated the world position/rotation for a global PB
  2042.       //  volume, so calculate the offset from the custom monument transform
  2043.       offset -= tMonument.position;
  2044.     }
  2045.  
  2046.     // apply collider's non-transform size and offset values and return that
  2047.     return ApplyColliderData(collider, size, rotation.eulerAngles.y, offset);
  2048.  
  2049. /* TODO: Is it worth cleaning up excessive rotations?
  2050.       // normalize rotation to range [0, 90)
  2051.       // confine to [0, 180) by flipping +/- 180 degrees as needed
  2052.       while (rotation >= 180.0f) rotation -= 180.0f;
  2053.       while (rotation < 0) rotation += 180.0f;
  2054.       if (rotation >= 90.0f)
  2055.       {
  2056.         // confine to [0, 90) by swapping x and y
  2057.         rotation -= 90.0f;
  2058.         (size.x, size.z) = (size.z, size.x);
  2059.       }
  2060. */
  2061.   }
  2062.  
  2063.   // get DynamicPVP event zone geometry (radius/size, rotation, offset) for
  2064.   //  given monument info, or all zeroes if not found
  2065.   // only one of radius or size can be nonzero, depending on whether a sphere
  2066.   //  or box volume was found, respectively
  2067.   private (float radius, Vector3 size, float rotation, Vector3 offset)
  2068.     GetPreventBuildingParams(Transform monumentTransform, bool customMonument)
  2069.   {
  2070.     var pbCollider = GetPreventBuildingCollider(
  2071.       monumentTransform, customMonument);
  2072.     if (!pbCollider) return (0.0f, Vector3.zero, 0.0f, Vector3.zero);
  2073.     var (size, rotation, offset) =
  2074.       GetPreventBuildingParams(pbCollider, monumentTransform, customMonument);
  2075.     if (Vector3.zero == size)
  2076.     {
  2077.       return (0.0f, Vector3.zero, 0.0f, Vector3.zero);
  2078.     }
  2079.     return pbCollider switch
  2080.     {
  2081.       BoxCollider => (0.0f, size, rotation, offset),
  2082.       SphereCollider => (size.Max(), Vector3.zero, rotation, offset),
  2083.       _ => (0.0f, Vector3.zero, 0.0f, Vector3.zero)
  2084.     };
  2085.   }
  2086.  
  2087.   // get DynamicPVP monument event zone geometry parameters for an Underwater
  2088.   //  Labs related transform
  2089.   // returns a volume encompassing all Underwater Labs PB volumes, with offset
  2090.   //  from the given transform
  2091.   private (float radius, Vector3 size, float rotation, Vector3 offset)
  2092.     GetLabLinkParams(Transform transform)
  2093.   {
  2094.     // get the Underwater Labs landmark at this location
  2095.     DungeonBaseInfo dungeonBaseInfo = TerrainMeta.Path.FindClosest(
  2096.       TerrainMeta.Path.DungeonBaseEntrances, transform.position);
  2097.     // scan all Underwater Labs modules to find the ones near this landmark
  2098.     Bounds bounds = new();
  2099.     var first = true;
  2100.     foreach (DungeonBaseLink linkI in TerrainMeta.Path.DungeonBaseLinks)
  2101.     {
  2102.       // get the closest Underwater Labs landmark to this link
  2103.       // this is used instead of dungeonLink.Dungeon in case this is a wacky
  2104.       //  custom map with scrambled data
  2105.       DungeonBaseInfo linkDungeon = TerrainMeta.Path.FindClosest(
  2106.         TerrainMeta.Path.DungeonBaseEntrances, linkI.transform.position);
  2107.       // ignore links that are closest to a different landmark (handles the
  2108.       //  case of multiple Underwater Labs monuments on a custom map)
  2109.       if (dungeonBaseInfo != linkDungeon) continue;
  2110.  
  2111.       // apparently the PB colliders are attached to the links' children; it
  2112.       //  seems like checking only the first child is sufficient
  2113.       // fall back to the link if it has no children, even though it probably
  2114.       //  won't work
  2115.       var child0 = linkI.transform.childCount > 0 ?
  2116.         linkI.transform.GetChild(0) : linkI.transform;
  2117.  
  2118.       var collider = GetPreventBuildingCollider(child0, false);
  2119.       if (!collider) continue;
  2120.  
  2121.       // Collider.bounds returns a world-space bounding box around the
  2122.       //  collider, which is exactly what we want
  2123.       var cBounds = collider.bounds;
  2124.  
  2125.       if (first)
  2126.       {
  2127.         // center global bounds on first collider bounds
  2128.         bounds.center = cBounds.center;
  2129.         first = false;
  2130.       }
  2131.       bounds.Encapsulate(cBounds);
  2132.     }
  2133.  
  2134.     return (0.0f, bounds.size, 0.0f, bounds.center - transform.position);
  2135.   }
  2136.  
  2137.   // return whether the given GameObject is a Train Tunnel pedestrian surface
  2138.   //  entrance to station linkage section of the desired type (stairwell=true
  2139.   //  => main stairwell, stairwell=false => dwellings corridor)
  2140.   private bool IsApplicableTunnelLink(
  2141.     DungeonGridInfo dungeon, GameObject link, bool stairwell)
  2142.   {
  2143.     // ignore entries whose prefab names indicate they're not intermediate
  2144.     //  links; this usually means monument/bunker entrances and stations
  2145.     // on vanilla maps we could simply skip the first and last entries, but
  2146.     //  I've found custom maps that violate this pattern for some reason
  2147.     if (!link.name.StartsWith(
  2148.           "assets/bundled/prefabs/autospawn/tunnel-link/link-"))
  2149.     {
  2150.       return false;
  2151.     }
  2152.     // ignore entries that are too far from the landmark; this seems to happen
  2153.     //  on custom maps where the creator has scrambled things up
  2154.     var linkDist =
  2155.       Vector3.Distance(dungeon.transform.position, link.transform.position);
  2156.     if (linkDist >= 300.0f)
  2157.     {
  2158.       if (!_brokenTunnels)
  2159.       {
  2160.         PrintWarning("Corrupt Train Tunnel stairwell/dwelling linkage(s) detected. Related monument events may not work as expected. This is a map/RustEdit issue, not a DynamicPVP issue.");
  2161.         _brokenTunnels = true;
  2162.       }
  2163.       return false;
  2164.     }
  2165.     // check DungeonGridLink for upward connection type, which determines
  2166.     //  whether it's a stairwell versus a corridor
  2167.     if (!link.TryGetComponent<DungeonGridLink>(out var dungeonGridLink))
  2168.     {
  2169.       return false;
  2170.     }
  2171.     var isStairwell = DungeonGridLinkType.Elevator == dungeonGridLink.UpType;
  2172.     return isStairwell == stairwell;
  2173.   }
  2174.  
  2175.   // get DynamicPVP monument event zone geometry parameters for a transform
  2176.   //  belonging to a Train Tunnels entrance linkage system
  2177.   // stairwell=true => transform is the entrance link; return volume
  2178.   //  encompassing all stairwell sections
  2179.   // stairwell=false => transform is central dwellings link; return volume
  2180.   //  encompassing all dwelling sections
  2181.   private (float radius, Vector3 size, float rotation, Vector3 offset)
  2182.     GetTunnelLinkParams(Transform linkTransform, bool stairwell)
  2183.   {
  2184.     DungeonGridInfo dungeonGridInfo = TerrainMeta.Path.FindClosest(
  2185.       TerrainMeta.Path.DungeonGridEntrances, linkTransform.position);
  2186.     if (!dungeonGridInfo) return (0.0f, Vector3.zero, 0.0f, Vector3.zero);
  2187.  
  2188.     Bounds bounds = new();
  2189.     var first = true;
  2190.     foreach (GameObject link in dungeonGridInfo.Links)
  2191.     {
  2192.       if (!IsApplicableTunnelLink(dungeonGridInfo, link, stairwell))
  2193.       {
  2194.         continue;
  2195.       }
  2196.       var collider = GetPreventBuildingCollider(link.transform, false);
  2197.       if (!collider)
  2198.       {
  2199.         continue;
  2200.       }
  2201.       var cBounds = collider.bounds;
  2202.       if (first)
  2203.       {
  2204.         bounds = cBounds;
  2205.         first = false;
  2206.         continue;
  2207.       }
  2208.       bounds.Encapsulate(cBounds);
  2209.     }
  2210.  
  2211.     return (0.0f, bounds.size, 0.0f, bounds.center - linkTransform.position);
  2212.   }
  2213.  
  2214.   // try to automatically derive a reasonable set of DynamicPVP monument event
  2215.   //  zone geometry parameters (radius/size, rotation, offset) for the given
  2216.   //  transform
  2217.   private (float radius, Vector3 size, float rotation, Vector3 offset)
  2218.     GetMonumentGeometry(Transform monumentTransform, MonumentEventType type)
  2219.     => type switch
  2220.     {
  2221.       MonumentEventType.Default =>
  2222.         GetPreventBuildingParams(monumentTransform, false),
  2223.       MonumentEventType.Custom =>
  2224.         GetPreventBuildingParams(monumentTransform, true),
  2225.       MonumentEventType.TunnelEntrance =>
  2226.         GetTunnelLinkParams(monumentTransform, true),
  2227.       MonumentEventType.TunnelLink =>
  2228.         GetTunnelLinkParams(monumentTransform, false),
  2229.       MonumentEventType.TunnelSection =>
  2230.         GetPreventBuildingParams(monumentTransform, false),
  2231.       MonumentEventType.UnderwaterLabs =>
  2232.         GetLabLinkParams(monumentTransform),
  2233.       _ =>
  2234.         throw new ArgumentOutOfRangeException(nameof(type), type, null)
  2235.     };
  2236.  
  2237.   // update monument event geometry parameters with given data if appropriate
  2238.   private static void UpdateGeometry(
  2239.     MonumentEvent monumentEvent, bool first, float newRadius, Vector3 newSize,
  2240.     float newRotation, Vector3 newOffset)
  2241.   {
  2242.     var updateRadius = newRadius > monumentEvent.DynamicZone.Radius;
  2243.     var updateSizeX = newSize.x > monumentEvent.DynamicZone.Size.x;
  2244.     var updateSizeY = newSize.y > monumentEvent.DynamicZone.Size.y;
  2245.     var updateSizeZ = newSize.z > monumentEvent.DynamicZone.Size.z;
  2246.     if (!first && !updateRadius && !updateSizeX && !updateSizeY &&
  2247.         !updateSizeZ)
  2248.     {
  2249.       return;
  2250.     }
  2251.  
  2252.     if (updateRadius) monumentEvent.DynamicZone.Radius = newRadius;
  2253.     var tempSize = monumentEvent.DynamicZone.Size;
  2254.     if (updateSizeX) tempSize.x = newSize.x;
  2255.     if (updateSizeY) tempSize.y = newSize.y;
  2256.     if (updateSizeZ) tempSize.z = newSize.z;
  2257.     monumentEvent.DynamicZone.Size = tempSize;
  2258.     monumentEvent.DynamicZone.Rotation = newRotation;
  2259.     monumentEvent.TransformPosition = newOffset;
  2260.   }
  2261.  
  2262.   // handle monument geometry checking for the given monument event
  2263.   private void CheckMonumentGeometry(
  2264.     string monumentName, Transform transform,
  2265.     MonumentEventType monumentEventType, bool first,
  2266.     MonumentEvent monumentEvent)
  2267.   {
  2268.     // if this is the first time checking this event type, record config
  2269.     //  values in dictionary and then reset them, so that we can start
  2270.     //  accumulating calculated values
  2271.     if (first)
  2272.     {
  2273.       _originalMonumentGeometries.TryAdd(monumentName,
  2274.         new OriginalMonumentGeometry
  2275.         {
  2276.           Radius = monumentEvent.DynamicZone.Radius,
  2277.           Rotation = monumentEvent.DynamicZone.Rotation,
  2278.           Size = monumentEvent.DynamicZone.Size,
  2279.           FixedRotation = monumentEvent.DynamicZone.FixedRotation,
  2280.           TransformPosition = monumentEvent.TransformPosition
  2281.         });
  2282.  
  2283.       monumentEvent.DynamicZone.Radius = 0.0f;
  2284.       monumentEvent.DynamicZone.Rotation = 0.0f;
  2285.       monumentEvent.DynamicZone.Size = Vector3.zero;
  2286.       monumentEvent.DynamicZone.FixedRotation = monumentEventType switch
  2287.       {
  2288.         MonumentEventType.Default => false,
  2289.         MonumentEventType.Custom => true,
  2290.         MonumentEventType.TunnelEntrance => true,
  2291.         MonumentEventType.TunnelLink => true,
  2292.         MonumentEventType.TunnelSection => false,
  2293.         MonumentEventType.UnderwaterLabs => true,
  2294.         _ => false
  2295.       };
  2296.       monumentEvent.TransformPosition = Vector3.zero;
  2297.     }
  2298.  
  2299.     // calculate geometry for current monument instance
  2300.     var (radius, size, rotation, offset) =
  2301.       GetMonumentGeometry(transform, monumentEventType);
  2302.  
  2303.     // record any updated parameters
  2304.     UpdateGeometry(monumentEvent, first, radius, size, rotation, offset);
  2305.   }
  2306.  
  2307.   // compare saved-off original monument geometry config data to auto-geo
  2308.   //  outputs, and report whether anything actually changed
  2309.   private bool ShouldSaveGeometry()
  2310.   {
  2311.     // NOTE: don't break early, because we need to set all AutoGeoOnNextLoad
  2312.     //  flags to false
  2313.     var changed = false;
  2314.     foreach (var (name, oGeo) in _originalMonumentGeometries)
  2315.     {
  2316.       if (!_configData.MonumentEvents.TryGetValue(name, out var monumentEvent))
  2317.       {
  2318.         // pathological: cached original geometry for a monument event that
  2319.         //  doesn't exist
  2320.         continue;
  2321.       }
  2322.       if (changed || oGeo.HasSameData(monumentEvent)) continue;
  2323.       // geometry data changed from original config values; request save
  2324.       PrintDebug($"ShouldSaveGeometry(): Geometry changed for monument event {name}; subsequent changes may not be reported");
  2325.       changed = true;
  2326.     }
  2327.     _originalMonumentGeometries.Clear();
  2328.     return changed;
  2329.   }
  2330.  
  2331.   private struct OriginalMonumentGeometry
  2332.   {
  2333.     public float Radius = 0f;
  2334.     public float Rotation = 0f;
  2335.     public Vector3 Size = Vector3.zero;
  2336.     public bool FixedRotation = false;
  2337.     public Vector3 TransformPosition = Vector3.zero;
  2338.  
  2339.     public OriginalMonumentGeometry()
  2340.     {
  2341.     }
  2342.  
  2343.     public bool HasSameData(MonumentEvent monumentEvent) =>
  2344.       Mathf.Approximately(Radius, monumentEvent.DynamicZone.Radius) &&
  2345.       Mathf.Approximately(Rotation, monumentEvent.DynamicZone.Rotation) &&
  2346.       Size == monumentEvent.DynamicZone.Size &&
  2347.       FixedRotation == monumentEvent.DynamicZone.FixedRotation &&
  2348.       TransformPosition == monumentEvent.TransformPosition;
  2349.   }
  2350.  
  2351.   #endregion Automatic Geometry
  2352.  
  2353.   // add and/or start (create) the given monument event name
  2354.   // records via collection modification whether it was added and/or created
  2355.   // NOTE: monument events currently default to disabled, but the code is
  2356.   //  structured to support auto-starting new events in case there is ever a
  2357.   //  desire to support this
  2358.   private IEnumerator CreateMonumentEvent(
  2359.     string monumentName, Transform transform, MonumentEventType type,
  2360.     HashSet<string> addedEvents, List<string> createdEvents)
  2361.   {
  2362.     if (!_configData.MonumentEvents.TryGetValue(
  2363.           monumentName, out var monumentEvent))
  2364.     {
  2365.       monumentEvent = new MonumentEvent();
  2366.       _configData.MonumentEvents.Add(monumentName, monumentEvent);
  2367.       addedEvents.Add(monumentName);
  2368.     }
  2369.  
  2370.     if (monumentEvent.Enabled)
  2371.     {
  2372.       if (monumentEvent.DynamicZone.DoAutoGeo)
  2373.       {
  2374.         PrintDebug($"CreateMonumentEvent(): Calculating geometry for monument event {monumentName} with type {type} at location {transform.position}");
  2375.         CheckMonumentGeometry(
  2376.           monumentName, transform, type,
  2377.           !createdEvents.Contains(monumentName), monumentEvent);
  2378.       }
  2379.       if (HandleMonumentEvent(monumentName, transform, monumentEvent))
  2380.       {
  2381.         createdEvents.Add(monumentName);
  2382.       }
  2383.     }
  2384.  
  2385.     yield return DynamicYield();
  2386.   }
  2387.  
  2388.   private static (string monumentName, bool custom) GetLandmarkName(
  2389.     LandmarkInfo landmarkInfo)
  2390.   {
  2391.     // TODO: cache this if it ever gets called more than once per custom
  2392.     //  monument (I tested, and it does not as of 4.9.0)
  2393.  
  2394.     // vanilla monument
  2395.     if (!landmarkInfo.name.Contains("monument_marker.prefab"))
  2396.     {
  2397.       return (landmarkInfo.displayPhrase?.english?.Trim(), false);
  2398.     }
  2399.  
  2400.     // custom monument
  2401.  
  2402.     // this sucks (results in scanning 5000+ prefabs during startup), but it
  2403.     //  seems to be how Facepunch decided to make us do it as of late 2025
  2404.     //  (stolen from their MonumentMarker class)
  2405.     var obj = landmarkInfo.transform.root.gameObject;
  2406.     foreach (var (prefabName, objectSet) in World.SpawnedPrefabs)
  2407.     {
  2408.       if (objectSet.Contains(obj)) return (prefabName, true);
  2409.     }
  2410.  
  2411.     return (landmarkInfo.transform.root.name, true);
  2412.   }
  2413.  
  2414.   // sub-coroutine to create (vanilla and custom map) map marker based
  2415.   //  monument events
  2416.   private IEnumerator CreateLandmarkMonumentEvents(
  2417.     HashSet<string> addedEvents, List<string> createdEvents)
  2418.   {
  2419.     foreach (LandmarkInfo landmarkInfo in TerrainMeta.Path.Landmarks)
  2420.     {
  2421.       // skip train tunnel stairwells/dwellings and underwater labs sections,
  2422.       //  as they are handled in other ways
  2423.       if (landmarkInfo is DungeonGridInfo or DungeonBaseLandmarkInfo)
  2424.       {
  2425.         continue;
  2426.       }
  2427.  
  2428.       var (monumentName, custom) = GetLandmarkName(landmarkInfo);
  2429.       if (string.IsNullOrEmpty(monumentName) &&
  2430.           landmarkInfo.shouldDisplayOnMap)
  2431.       {
  2432.         PrintDebug($"CreateLandmarkMonumentEvents(): Skipping visible landmark because it has no map title: {landmarkInfo}");
  2433.         continue;
  2434.       }
  2435.  
  2436.       if (landmarkInfo is MonumentInfo && "Train Tunnel" == monumentName)
  2437.       {
  2438.         // Train Tunnel bunker entrances are MonumentInfo objects that aren't
  2439.         //  map-visible, because they connect to DungeonGridInfo landmarks
  2440.         //  with the same name; promote this to a first-class monument by
  2441.         //  giving it a map visibility exception, but tweak the name to
  2442.         //  disambiguate from the other flavor
  2443.         monumentName = "Train Tunnel Bunker";
  2444.       }
  2445.       else if (!landmarkInfo.shouldDisplayOnMap)
  2446.       {
  2447.         // all other landmarks must have map markers/labels for now
  2448.         PrintDebug($"CreateLandmarkMonumentEvents(): Skipping unlabeled landmark {monumentName} of type {landmarkInfo}");
  2449.         continue;
  2450.       }
  2451.  
  2452.       switch (landmarkInfo.name)
  2453.       {
  2454.         case "assets/bundled/prefabs/autospawn/monument/harbor/harbor_1.prefab":
  2455.           monumentName += " A";
  2456.           break;
  2457.         case "assets/bundled/prefabs/autospawn/monument/harbor/harbor_2.prefab":
  2458.           monumentName += " B";
  2459.           break;
  2460.         case PrefabLargeOilRig:
  2461.           _largeOilRigPosition = landmarkInfo.transform.position;
  2462.           break;
  2463.         case PrefabOilRig:
  2464.           _oilRigPosition = landmarkInfo.transform.position;
  2465.           break;
  2466.       }
  2467.  
  2468.       var type =
  2469.         custom ?
  2470.           MonumentEventType.Custom :
  2471.           "Underwater Lab" == monumentName ?
  2472.             MonumentEventType.UnderwaterLabs :
  2473.             MonumentEventType.Default;
  2474.       yield return CreateMonumentEvent(
  2475.         monumentName, landmarkInfo.transform, type,
  2476.         addedEvents, createdEvents);
  2477.     }
  2478.  
  2479.     yield return DynamicYield(true);
  2480.   }
  2481.  
  2482.   // derive a user-friendly event name from a Train Tunnel section prefab name
  2483.   // returns empty string on failure, which is debug logged
  2484.   private string ToTunnelSectionEventName(string cellName)
  2485.   {
  2486.     if (!cellName.StartsWith("assets/bundled/prefabs/autospawn/tunnel"))
  2487.     {
  2488.       PrintDebug($"ToTunnelSectionEventName(): Skipping unsupported DungeonGridCell type due to non-tunnel: {cellName}");
  2489.       return "";
  2490.     }
  2491.     // NOTE: this must be returned to pool on any return from this method
  2492.     var stringBuilder = Pool.Get<StringBuilder>();
  2493.     stringBuilder.Clear().Append("Train Tunnel");
  2494.     // get the "tunnelXYZ" part of the name
  2495.     var slashSplit = cellName.Split("/");
  2496.     if (slashSplit.Length < 6)
  2497.     {
  2498.       PrintDebug($"ToTunnelSectionEventName(): Skipping unsupported DungeonGridCell type due to path components: {cellName}");
  2499.       Pool.FreeUnmanaged(ref stringBuilder);
  2500.       return "";
  2501.     }
  2502.     var upwards = "tunnel-upwards" == slashSplit[4];
  2503.     var dashSplit = slashSplit[5].Split("-");
  2504.     if (dashSplit.Length < 2)
  2505.     {
  2506.       PrintDebug($"ToTunnelSectionEventName(): Skipping unsupported DungeonGridCell type due to name components: {cellName}");
  2507.       Pool.FreeUnmanaged(ref stringBuilder);
  2508.       return "";
  2509.     }
  2510.     // extract feature part of name
  2511.     var feature = slashSplit[5];
  2512.     if (upwards)
  2513.     {
  2514.       stringBuilder.Append(" Upwards");
  2515.     }
  2516.     else if (feature.StartsWith("curve"))
  2517.     {
  2518.       stringBuilder.Append(" Curve");
  2519.     }
  2520.     else if (feature.StartsWith("intersection"))
  2521.     {
  2522.       stringBuilder.Append(" Intersection");
  2523.     }
  2524.     else if (feature.StartsWith("station"))
  2525.     {
  2526.       stringBuilder.Append(" Station");
  2527.     }
  2528.     else if (feature.StartsWith("straight"))
  2529.     {
  2530.       stringBuilder.Append(" Straight");
  2531.     }
  2532.     else if (feature.StartsWith("transition"))
  2533.     {
  2534.       stringBuilder.Append(" Transition");
  2535.     }
  2536.     else
  2537.     {
  2538.       PrintDebug($"ToTunnelSectionEventName(): Skipping unsupported DungeonGridCell type due to feature component '{feature}': {cellName}");
  2539.       Pool.FreeUnmanaged(ref stringBuilder);
  2540.       return "";
  2541.     }
  2542.     // extract direction part of name
  2543.     var direction =
  2544.       dashSplit[upwards ? dashSplit.Length - 1 : 1].Split(".")[0];
  2545.     switch (direction)
  2546.     {
  2547.       case "e":  stringBuilder.Append(" East");        break;
  2548.       case "n":  stringBuilder.Append(" North");       break;
  2549.       case "ne": stringBuilder.Append(" North-East");  break;
  2550.       case "nw": stringBuilder.Append(" North-West");  break;
  2551.       case "s":  stringBuilder.Append(" South");       break;
  2552.       case "se": stringBuilder.Append(" South-East");  break;
  2553.       case "sn": stringBuilder.Append(" North-South"); break;
  2554.       case "sw": stringBuilder.Append(" South-West");  break;
  2555.       case "w":  stringBuilder.Append(" West");        break;
  2556.       case "we": stringBuilder.Append(" East-West");   break;
  2557.       default:
  2558.       {
  2559.         PrintDebug($"ToTunnelSectionEventName(): Skipping unsupported DungeonGridCell type due to unknown direction '{direction}': {cellName}");
  2560.         Pool.FreeUnmanaged(ref stringBuilder);
  2561.         return "";
  2562.       }
  2563.     }
  2564.     var eventName = stringBuilder.ToString();
  2565.     Pool.FreeUnmanaged(ref stringBuilder);
  2566.     return eventName;
  2567.   }
  2568.  
  2569.   // sub-coroutine to create Train Tunnel section based monument events
  2570.   private IEnumerator CreateTunnelSectionMonumentEvents(
  2571.     HashSet<string> addedEvents, List<string> createdEvents)
  2572.   {
  2573.     foreach (DungeonGridCell cell in TerrainMeta.Path.DungeonGridCells)
  2574.     {
  2575.       var eventName = ToTunnelSectionEventName(cell.name);
  2576.       if (string.IsNullOrEmpty(eventName)) continue;
  2577.       yield return CreateMonumentEvent(
  2578.         eventName, cell.transform, MonumentEventType.TunnelSection,
  2579.         addedEvents, createdEvents);
  2580.     }
  2581.  
  2582.     yield return DynamicYield(true);
  2583.   }
  2584.  
  2585.   // get index of center-most section in Train Tunnel (stairwell=true) or
  2586.   //  Train Tunnel Dwelling (stairwell=false) portion of entrance links
  2587.   // returns negative number on failure
  2588.   private int GetUpperTunnelCenterIndex(
  2589.     DungeonGridInfo dungeonGridInfo, bool stairwell = false)
  2590.   {
  2591.     if (dungeonGridInfo.Links.Count <= 0)
  2592.     {
  2593.       PrintDebug($"GetUpperTunnelCenterIndex(): Skipping DungeonGridInfo with empty Links list: {dungeonGridInfo.name}");
  2594.       return -1;
  2595.     }
  2596.     // scan the list once, to create a bounding box around the transform
  2597.     //  positions of all applicable links
  2598.     Bounds linkBounds = new(Vector3.zero, Vector3.zero);
  2599.     var first = true;
  2600.     foreach (GameObject link in dungeonGridInfo.Links)
  2601.     {
  2602.       if (!IsApplicableTunnelLink(dungeonGridInfo, link, stairwell)) continue;
  2603.       if (first)
  2604.       {
  2605.         // this is the first valid entry; record its position
  2606.         linkBounds.center = link.transform.position;
  2607.         first = false;
  2608.         continue;
  2609.       }
  2610.       linkBounds.Encapsulate(link.transform.position);
  2611.     }
  2612.     // scan the list again, so find the closest link to bounding box center
  2613.     if (Vector3.zero == linkBounds.size)
  2614.     {
  2615.       PrintDebug($"GetUpperTunnelCenterIndex(): Skipping DungeonGridInfo with unknown bounds: {dungeonGridInfo.name}@{dungeonGridInfo.transform.position}");
  2616.       return -2;
  2617.     }
  2618.     // find the link closest to the center of the bounding box
  2619.     var transformIndex = -3;
  2620.     var minDistance = -1.0f;
  2621.     for (var i = 0; i < dungeonGridInfo.Links.Count; ++i)
  2622.     {
  2623.       GameObject linkI = dungeonGridInfo.Links[i];
  2624.       if (!IsApplicableTunnelLink(dungeonGridInfo, linkI, stairwell))
  2625.       {
  2626.         continue;
  2627.       }
  2628.       var distance =
  2629.         Vector3.Distance(linkBounds.center, linkI.transform.position);
  2630.       if (minDistance > 0 && distance > minDistance) continue;
  2631.       transformIndex = i;
  2632.       minDistance = distance;
  2633.     }
  2634.     return transformIndex;
  2635.   }
  2636.  
  2637.   // sub-coroutine to create Train Tunnel stairwell and dweller area monument
  2638.   //  events
  2639.   private IEnumerator CreateUpperTunnelMonumentEvents(
  2640.     HashSet<string> addedEvents, List<string> createdEvents)
  2641.   {
  2642.     foreach (
  2643.       DungeonGridInfo entrance in TerrainMeta.Path.DungeonGridEntrances)
  2644.     {
  2645.       if (entrance.Links.Count <= 0) continue;
  2646.  
  2647.       // create Train Tunnel stairwell monument event
  2648.       var landmarkName = GetLandmarkName(entrance).monumentName;
  2649.       if (string.IsNullOrEmpty(landmarkName))
  2650.       {
  2651.         PrintWarning($"CreateUpperTunnelMonumentEvents(): Skipping Train Tunnels entrance {entrance}@{entrance.transform.position} because it has no landmark name");
  2652.         continue;
  2653.       }
  2654.       yield return CreateMonumentEvent(
  2655.         landmarkName, entrance.transform, MonumentEventType.TunnelEntrance,
  2656.         addedEvents, createdEvents);
  2657.  
  2658.       // create Train Tunnel Dwelling monument event
  2659.       var transformIndex =
  2660.         GetUpperTunnelCenterIndex(entrance);
  2661.       if (transformIndex < 0) continue;
  2662.       yield return CreateMonumentEvent(
  2663.         landmarkName + " Dwelling", entrance.Links[transformIndex].transform,
  2664.         MonumentEventType.TunnelLink,
  2665.         addedEvents, createdEvents);
  2666.     }
  2667.  
  2668.     yield return DynamicYield(true);
  2669.   }
  2670.  
  2671.   // coroutine to orchestrate creation of all monument event types
  2672.   private IEnumerator CreateMonumentEvents()
  2673.   {
  2674.     var save = false;
  2675.     var addedEvents = Pool.Get<HashSet<string>>();
  2676.     var createdEvents = Pool.Get<List<string>>();
  2677.  
  2678.     Puts("Creating Landmark Monument Events");
  2679.     yield return CreateLandmarkMonumentEvents(addedEvents, createdEvents);
  2680.     Puts("Creating Train Tunnel Section Monument Events");
  2681.     yield return CreateTunnelSectionMonumentEvents(
  2682.       addedEvents, createdEvents);
  2683.     Puts("Creating Train Tunnel Entrance Monument Events");
  2684.     yield return CreateUpperTunnelMonumentEvents(addedEvents, createdEvents);
  2685.  
  2686.     if (addedEvents.Count > 0)
  2687.     {
  2688.       PrintDebug($"CreateMonumentEvents(): {addedEvents.Count} new monument event(s) added to config: {string.Join(", ", addedEvents)}");
  2689.       save = true;
  2690.     }
  2691.     if (ShouldSaveGeometry())
  2692.     {
  2693.       PrintDebug("CreateMonumentEvents(): Recording geometry change(s) to config file");
  2694.       save = true;
  2695.     }
  2696.     if (save) SaveConfig();
  2697.  
  2698.     if (createdEvents.Count > 0)
  2699.     {
  2700.       PrintDebug($"CreateMonumentEvents(): {createdEvents.Count} monument event(s) successfully created: {string.Join(", ", createdEvents)}");
  2701.     }
  2702.  
  2703.     Pool.FreeUnmanaged(ref addedEvents);
  2704.     Pool.FreeUnmanaged(ref createdEvents);
  2705.  
  2706.     yield return DynamicYield(true);
  2707.   }
  2708.  
  2709.   #endregion Monument Event
  2710.  
  2711.   #region Auto Event
  2712.  
  2713.   // coroutine to create user-defined auto events
  2714.   private IEnumerator CreateAutoEvents()
  2715.   {
  2716.     var createdEvents = Pool.Get<List<string>>();
  2717.  
  2718.     // create auto events from data file
  2719.     foreach (var entry in _storedData.autoEvents)
  2720.     {
  2721.       if (!entry.Value.AutoStart || !CreateDynamicZone(
  2722.             entry.Key, entry.Value.Position, entry.Value.ZoneId))
  2723.       {
  2724.         continue;
  2725.       }
  2726.       createdEvents.Add(entry.Key);
  2727.       yield return DynamicYield();
  2728.     }
  2729.     if (createdEvents.Count > 0)
  2730.     {
  2731.       PrintDebug($"CreateAutoEvents(): {createdEvents.Count} auto event(s) successfully created: {string.Join(", ", createdEvents)}");
  2732.     }
  2733.  
  2734.     Pool.FreeUnmanaged(ref createdEvents);
  2735.  
  2736.     yield return DynamicYield(true);
  2737.   }
  2738.  
  2739.   #endregion Auto Event
  2740.  
  2741.   #endregion Events
  2742.  
  2743.   #region Chat/Console Command Handler
  2744.  
  2745.   private object OnPlayerCommand(
  2746.     BasePlayer player, string command, string[] args) =>
  2747.     CheckCommand(player, command, true);
  2748.  
  2749.   private object OnServerCommand(ConsoleSystem.Arg arg) =>
  2750.     CheckCommand(arg?.Player(), arg?.cmd?.FullName, false);
  2751.  
  2752.   private object CheckCommand(BasePlayer player, string command, bool isChat)
  2753.   {
  2754.     if (!player || string.IsNullOrEmpty(command))
  2755.     {
  2756.       return null;
  2757.     }
  2758.     command = command.ToLower().TrimStart('/');
  2759.     if (string.IsNullOrEmpty(command))
  2760.     {
  2761.       return null;
  2762.     }
  2763.  
  2764.     if (_pvpDelays.TryGetValue(player.userID, out var leftZone))
  2765.     {
  2766.       var baseEvent = GetBaseEvent(leftZone.eventName);
  2767.       if (baseEvent?.CommandWorksForPVPDelay == true &&
  2768.           IsBlockedCommand(baseEvent, command, isChat))
  2769.       {
  2770.         return false;
  2771.       }
  2772.     }
  2773.  
  2774.     var playerZones = Pool.Get<List<string>>();
  2775.     ZM_GetPlayerZoneIDs(player, playerZones);
  2776.     foreach (var zoneId in playerZones)
  2777.     {
  2778.       if (string.IsNullOrEmpty(zoneId) ||
  2779.           !_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  2780.       {
  2781.         continue;
  2782.       }
  2783.       PrintDebug($"CheckCommand(): Checking command: {command} , zoneId: {zoneId}");
  2784.       var baseEvent = GetBaseEvent(eventName);
  2785.       if (null != baseEvent && IsBlockedCommand(baseEvent, command, isChat))
  2786.       {
  2787.         Pool.FreeUnmanaged(ref playerZones);
  2788.         return false;
  2789.       }
  2790.     }
  2791.  
  2792.     Pool.FreeUnmanaged(ref playerZones);
  2793.     return null;
  2794.   }
  2795.  
  2796.   private bool IsBlockedCommand(
  2797.     BaseEvent baseEvent, string command, bool isChat)
  2798.   {
  2799.     if (null == baseEvent || baseEvent.CommandList.Count <= 0) return false;
  2800.     var commandExist = baseEvent.CommandList.Exists(entry =>
  2801.       entry.StartsWith('/') && isChat ?
  2802.         entry.Substring(1).Equals(command) : command.Contains(entry));
  2803.     if (baseEvent.UseBlacklistCommands != commandExist) return false;
  2804.     PrintDebug($"IsBlockedCommand(): Blocked command: '{command}' due to {(baseEvent.UseBlacklistCommands ? "blacklist" : "whitelist")}");
  2805.     return true;
  2806.   }
  2807.  
  2808.   #endregion Chat/Console Command Handler
  2809.  
  2810.   #region DynamicZone Handler
  2811.  
  2812.   /// create a zone that is parented to an entity, so that they move together
  2813.   //
  2814.   // NOTE: caller is responsible for calling CheckEntityOwner() and
  2815.   //  CanCreateDynamicPVP() first, because this method can't easily implement
  2816.   //  calling them exactly once
  2817.   private void HandleParentedEntityEvent(
  2818.     string eventName, BaseEntity parentEntity, bool parentOnCreate,
  2819.     bool delay = true)
  2820.   {
  2821.     if (!parentEntity || null == parentEntity.net)
  2822.     {
  2823.       return;
  2824.     }
  2825.     var baseEvent = GetBaseEvent(eventName);
  2826.     if (baseEvent == null)
  2827.     {
  2828.       return;
  2829.     }
  2830.     if (delay && baseEvent.EventStartDelay > 0f)
  2831.     {
  2832.       timer.Once(baseEvent.EventStartDelay, () => HandleParentedEntityEvent(
  2833.         eventName, parentEntity, parentOnCreate, false));
  2834.       return;
  2835.     }
  2836.     PrintDebug($"HandleParentedEntityEvent(): Trying to create parented entity eventName={eventName} on parentEntity={parentEntity}.");
  2837.     var zonePosition = parentEntity.transform.position;
  2838.     if (!parentOnCreate)
  2839.     {
  2840.       var groundY = TerrainMeta.HeightMap.GetHeight(zonePosition);
  2841.       if (Mathf.Abs(zonePosition.y - groundY) < 10.0f)
  2842.       {
  2843.         // entity is already near the ground; force enable immediate parenting
  2844.         // this catches the case that e.g. a Supply Drop landed during the
  2845.         //  event start delay
  2846.         parentOnCreate = true;
  2847.       }
  2848.       else
  2849.       {
  2850.         // entity is not near the ground yet; start the zone on the ground
  2851.         zonePosition.y = groundY;
  2852.       }
  2853.     }
  2854.     var zoneId = parentEntity.net.ID.ToString();
  2855.     if (!CreateDynamicZone(eventName, zonePosition, zoneId, delay: false))
  2856.     {
  2857.       return;
  2858.     }
  2859.     if (parentOnCreate)
  2860.     {
  2861.       // attach the event (zone, plus domes if applicable) to the parent
  2862.       //  entity, so that they move together
  2863.       ParentEventToEntity(
  2864.         zoneId, baseEvent, parentEntity, deleteOnFailure: true);
  2865.     }
  2866.     // else something will attach it later
  2867.   }
  2868.  
  2869.   private bool HandleMonumentEvent(
  2870.     string eventName, Transform transform, MonumentEvent monumentEvent)
  2871.   {
  2872.     var position =
  2873.       monumentEvent.TransformPosition == Vector3.zero ?
  2874.         transform.position :
  2875.         monumentEvent.DynamicZone.FixedRotation ?
  2876.           transform.position + monumentEvent.TransformPosition :
  2877.           transform.TransformPoint(monumentEvent.TransformPosition);
  2878.     return CreateDynamicZone(
  2879.       eventName, position, monumentEvent.ZoneId,
  2880.       monumentEvent.GetDynamicZone().ZoneSettings(transform));
  2881.   }
  2882.  
  2883.   private static (Transform, Vector3, float) GetIslandGeometry(
  2884.     DeepSeaIsland deepSeaIsland)
  2885.   {
  2886.     if (deepSeaIsland.monumentNavMesh)
  2887.     {
  2888.       // use navmesh bounds if available, as they're slightly better-centered
  2889.       var bounds = deepSeaIsland.monumentNavMesh.GetBounds();
  2890.       var navMeshPosition = bounds.center;
  2891.       navMeshPosition.y = 0;
  2892.       // the navmesh bounds cling pretty tightly to the island, so instead we
  2893.       //  calculate a sphere that fully encompasses them, rounded up to the next
  2894.       //  multiple of rVal
  2895.       const float rVal = 100.0f;
  2896.       var radius = Mathf.Ceil(bounds.extents.magnitude / rVal) * rVal;
  2897.       return (deepSeaIsland.monumentNavMesh.transform, navMeshPosition, radius);
  2898.     }
  2899.  
  2900.     var islandPosition = deepSeaIsland.transform.position;
  2901.     islandPosition.y = 0;
  2902.     return (deepSeaIsland.transform, islandPosition, 200.0f);
  2903.   }
  2904.  
  2905.   private void HandleIslandEvent(DeepSeaIsland deepSeaIsland)
  2906.   {
  2907.     const string eventName = nameof(GeneralEventType.DeepSeaIsland);
  2908.     var zoneId = deepSeaIsland?.net?.ID.ToString();
  2909.     if (string.IsNullOrEmpty(zoneId))
  2910.     {
  2911.       PrintDebug($"HandleGeneralEvent(): Aborting creation of eventName={eventName}, because entity is null", DebugLevel.Warning);
  2912.       return;
  2913.     }
  2914.     if (_activeDynamicZones.ContainsKey(zoneId))
  2915.     {
  2916.       PrintDebug($"HandleGeneralEvent(): Aborting creation of redundant eventName={eventName} for DeepSeaIsland={deepSeaIsland} with baseEntity.net.ID={zoneId}", DebugLevel.Warning);
  2917.       return;
  2918.     }
  2919.     if (!CanCreateDynamicPVP(eventName, deepSeaIsland))
  2920.     {
  2921.       return;
  2922.     }
  2923.     var baseEvent = GetBaseEvent(eventName);
  2924.     if (baseEvent == null)
  2925.     {
  2926.       return;
  2927.     }
  2928.  
  2929.     var (transform, position, radius) = GetIslandGeometry(deepSeaIsland);
  2930.  
  2931.     // also calculate a zone volume if auto-geo is enabled (otherwise
  2932.     //  user-specified volume is used)
  2933.     if (baseEvent.GetDynamicZone() is
  2934.         SphereCubeAutoGeoDynamicZone { DoAutoGeo: true } geo)
  2935.     {
  2936.       geo.Radius = radius;
  2937.       geo.Size = Vector3.zero; // disable cuboid zone
  2938.     }
  2939.  
  2940.     CreateDynamicZone(eventName,
  2941.       position, zoneId, baseEvent.GetDynamicZone().ZoneSettings(transform));
  2942.   }
  2943.  
  2944.   private enum EventHeightStrategy
  2945.   {
  2946.     Entity,  // place event at entity's height
  2947.     Terrain, // place event on ground
  2948.     Zero     // place event at sea level
  2949.   };
  2950.  
  2951.   private void HandleGeneralEvent(
  2952.     GeneralEventType generalEventType,
  2953.     BaseEntity baseEntity,
  2954.     bool useEntityId,
  2955.     EventHeightStrategy heightStrategy = EventHeightStrategy.Terrain)
  2956.   {
  2957.     var eventName = generalEventType.ToString();
  2958.     string zoneId = null;
  2959.     if (useEntityId)
  2960.     {
  2961.       zoneId = baseEntity?.net?.ID.ToString();
  2962.       if (string.IsNullOrEmpty(zoneId))
  2963.       {
  2964.         PrintDebug($"HandleGeneralEvent(): Aborting creation of eventName={eventName}, because entity is null", DebugLevel.Warning);
  2965.         return;
  2966.       }
  2967.       if (_activeDynamicZones.ContainsKey(zoneId))
  2968.       {
  2969.         PrintDebug($"HandleGeneralEvent(): Aborting creation of redundant eventName={eventName} for baseEntity={baseEntity} with baseEntity.net.ID={baseEntity.net.ID}", DebugLevel.Warning);
  2970.         return;
  2971.       }
  2972.     }
  2973.     if (!CanCreateDynamicPVP(eventName, baseEntity))
  2974.     {
  2975.       return;
  2976.     }
  2977.     var baseEvent = GetBaseEvent(eventName);
  2978.     if (baseEvent == null)
  2979.     {
  2980.       return;
  2981.     }
  2982.  
  2983.     var position = baseEntity.transform.position;
  2984.     position.y = heightStrategy switch
  2985.     {
  2986.       EventHeightStrategy.Entity  => position.y,
  2987.       EventHeightStrategy.Terrain => TerrainMeta.HeightMap.GetHeight(position),
  2988.       EventHeightStrategy.Zero    => 0,
  2989.       _ => throw new ArgumentOutOfRangeException(nameof(heightStrategy), heightStrategy, null)
  2990.     };
  2991.  
  2992.     // NOTE: zoneId will be null if useEntityId is false; this is intentional
  2993.     CreateDynamicZone(
  2994.       eventName, position, zoneId, baseEvent.GetDynamicZone().ZoneSettings(
  2995.         baseEntity.transform));
  2996.   }
  2997.  
  2998.   private bool CreateDynamicZone(
  2999.     string eventName, Vector3 position, string zoneId = "",
  3000.     string[] zoneSettings = null, bool delay = true)
  3001.   {
  3002.     if (position == Vector3.zero)
  3003.     {
  3004.       PrintDebug($"CreateDynamicZone(): ERROR: Invalid location, zone creation failed for eventName={eventName}.", DebugLevel.Error);
  3005.       return false;
  3006.     }
  3007.     // protect against immediate creation of a zone if one already exists with
  3008.     //  given zone ID (don't want to block delays because they may be
  3009.     //  orchestrated?)
  3010.     if (!delay && _activeDynamicZones.ContainsKey(zoneId))
  3011.     {
  3012.       PrintDebug($"CreateDynamicZone(): WARNING: Cannot create zone for event {eventName} because requested zone ID {zoneId} already exists", DebugLevel.Warning);
  3013.       // return true to indicate that the zone exists
  3014.       return true;
  3015.     }
  3016.     var baseEvent = GetBaseEvent(eventName);
  3017.     if (baseEvent == null)
  3018.     {
  3019.       PrintDebug($"CreateDynamicZone(): ERROR: No baseEvent for eventName={eventName}.", DebugLevel.Error);
  3020.       return false;
  3021.     }
  3022.     if (delay && baseEvent.EventStartDelay > 0f)
  3023.     {
  3024.       timer.Once(baseEvent.EventStartDelay, () =>
  3025.         CreateDynamicZone(eventName, position, zoneId, zoneSettings, false));
  3026.       PrintDebug($"CreateDynamicZone(): Delaying zone creation for eventName={eventName} by {baseEvent.EventStartDelay}s.");
  3027.       return false;
  3028.     }
  3029.  
  3030.     float duration = -1;
  3031.     if (baseEvent is BaseTimedEvent timedEvent &&
  3032.         (baseEvent is not ITimedDisable timedDisable ||
  3033.          !timedDisable.IsTimedDisabled()))
  3034.     {
  3035.       duration = timedEvent.Duration;
  3036.     }
  3037.  
  3038.     if (string.IsNullOrEmpty(zoneId))
  3039.     {
  3040.       // TODO: prefix with plugin name or event type?
  3041.       // TODO: switch to using entity netID in more cases?
  3042.       zoneId = DateTime.Now.ToString("HHmmssffff");
  3043.     }
  3044.  
  3045.     var dynamicZone = baseEvent.GetDynamicZone();
  3046.     zoneSettings ??= dynamicZone.ZoneSettings();
  3047.  
  3048.     PrintDebug($"CreateDynamicZone(): Trying to create zoneId={zoneId} for eventName={eventName} at position={position}{(dynamicZone is ISphereZone zone ? $", radius={zone.Radius}m" : null)}{(dynamicZone is ICubeZone cubeZone ? $", size={cubeZone.Size}" : null)}{(dynamicZone is IParentZone parentZone ? $", center={parentZone.Center}" : null)}{(dynamicZone is IRotateZone rotateZone ? $", rotation={rotateZone.Rotation}, fixedRotation={rotateZone.FixedRotation}" : null)}, duration={duration}s.");
  3049.     var zoneRadius = dynamicZone is ISphereZone sz ? sz.Radius : 0;
  3050.     var zoneSize = dynamicZone is ICubeZone cz ? cz.Size.magnitude : 0;
  3051.     if (zoneRadius <= 0 && zoneSize <= 0)
  3052.     {
  3053.       PrintError($"CreateDynamicZone(): ERROR: Cannot create zone for eventName={eventName} because both radius and size are less than or equal to zero");
  3054.       return false;
  3055.     }
  3056.     if (!ZM_CreateOrUpdateZone(zoneId, zoneSettings, position))
  3057.     {
  3058.       PrintDebug($"CreateDynamicZone(): ERROR: Zone NOT created for eventName={eventName}.", DebugLevel.Error);
  3059.       return false;
  3060.     }
  3061.  
  3062.     if (_activeDynamicZones.TryAdd(zoneId, eventName))
  3063.     {
  3064.       UpdateActivePluginZones(added: true, zoneId, baseEvent);
  3065.       CheckHooks(HookCheckReasons.ZoneAdded, baseEvent);
  3066.     }
  3067.  
  3068.     var stringBuilder = Pool.Get<StringBuilder>();
  3069.     stringBuilder.Clear();
  3070.     if (baseEvent is DomeEvent domeEvent &&
  3071.         dynamicZone is ISphereZone sphereZone &&
  3072.         domeEvent.DomeData.DomeCreateAllowed(sphereZone))
  3073.     {
  3074.       if (CreateDome(zoneId, position, sphereZone.Radius, domeEvent.DomeData))
  3075.       {
  3076.         stringBuilder.Append("Dome,");
  3077.       }
  3078.       else
  3079.       {
  3080.         PrintDebug($"CreateDynamicZone(): ERROR: Dome NOT created for zoneId={zoneId}.", DebugLevel.Error);
  3081.       }
  3082.     }
  3083.  
  3084.     if (baseEvent is BotDomeEvent botEvent &&
  3085.         BotReSpawnAllowed(botEvent))
  3086.     {
  3087.       if (SpawnBots(position, botEvent.BotProfileName, zoneId))
  3088.       {
  3089.         stringBuilder.Append("Bots,");
  3090.       }
  3091.       else
  3092.       {
  3093.         PrintDebug($"CreateDynamicZone(): ERROR: Bot(s) NOT spawned for zoneId={zoneId}.", DebugLevel.Error);
  3094.       }
  3095.     }
  3096.  
  3097.     if (TP_AddOrUpdateMapping(zoneId, baseEvent.Mapping))
  3098.     {
  3099.       stringBuilder.Append("Mapping,");
  3100.     }
  3101.     else
  3102.     {
  3103.       PrintDebug($"CreateDynamicZone(): ERROR: Mapping NOT created for zoneId={zoneId}.", DebugLevel.Error);
  3104.     }
  3105.  
  3106.     PrintDebug($"CreateDynamicZone(): Created zoneId={zoneId} for eventName={eventName} with properties: {stringBuilder.ToString().TrimEnd(',')}.");
  3107.     HandleDeleteDynamicZone(zoneId, duration, eventName);
  3108.  
  3109.     stringBuilder.Clear();
  3110.     Pool.FreeUnmanaged(ref stringBuilder);
  3111.     Interface.CallHook("OnCreatedDynamicPVP",
  3112.       zoneId, eventName, position, duration);
  3113.     return true;
  3114.   }
  3115.  
  3116.   private void HandleDeleteDynamicZone(
  3117.     string zoneId, float duration, string eventName)
  3118.   {
  3119.     if (duration <= 0f) return;
  3120.     TryRemoveEventTimer(zoneId);
  3121.     PrintDebug($"HandleDeleteDynamicZone(): Scheduling deletion of zoneId={zoneId} for eventName={eventName} in {duration} second(s).");
  3122.     _eventTimers.Add(
  3123.       zoneId, timer.Once(duration, () => HandleDeleteDynamicZone(zoneId)));
  3124.   }
  3125.  
  3126.   private void HandleDeleteDynamicZone(string zoneId)
  3127.   {
  3128.     if (string.IsNullOrEmpty(zoneId) ||
  3129.         !_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  3130.     {
  3131.       // this isn't an error, because sometimes deletion is requested "just in
  3132.       //  case", and/or because multiple delete stimuli occurred
  3133.       PrintDebug($"HandleDeleteDynamicZone(): Skipping delete for unknown zoneId={zoneId}.");
  3134.       return;
  3135.     }
  3136.     PrintDebug($"HandleDeleteDynamicZone(): Calling OnDeleteDynamicPVP({zoneId}, {eventName})");
  3137.     if (Interface.CallHook("OnDeleteDynamicPVP", zoneId, eventName) != null)
  3138.     {
  3139.       PrintDebug($"HandleDeleteDynamicZone(): Aborting delete due to hook response");
  3140.       return;
  3141.     }
  3142.     var baseEvent = GetBaseEvent(eventName);
  3143.     if (null == baseEvent)
  3144.     {
  3145.       return;
  3146.     }
  3147.     if (baseEvent.EventStopDelay > 0f)
  3148.     {
  3149.       TryRemoveEventTimer(zoneId);
  3150.       if (baseEvent.GetDynamicZone() is IParentZone)
  3151.       {
  3152.         // untether zone from parent entity
  3153.         ZM_GetZoneByID(zoneId)?.transform.SetParent(null, true);
  3154.         // also untether any domes
  3155.         ParentDome(zoneId, Vector3.zero);
  3156.       }
  3157.       _eventTimers.Add(zoneId, timer.Once(
  3158.         baseEvent.EventStopDelay, () => DeleteDynamicZone(zoneId)));
  3159.     }
  3160.     else
  3161.     {
  3162.       DeleteDynamicZone(zoneId);
  3163.     }
  3164.   }
  3165.  
  3166.   private bool DeleteDynamicZone(string zoneId)
  3167.   {
  3168.     if (string.IsNullOrEmpty(zoneId) ||
  3169.         !_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  3170.     {
  3171.       // this isn't an error, because sometimes deletion is requested "just in
  3172.       //  case", and/or because multiple delete stimuli occurred
  3173.       PrintDebug($"DeleteDynamicZone(): Skipping delete for unknown zoneId={zoneId}.");
  3174.       return false;
  3175.     }
  3176.  
  3177.     TryRemoveEventTimer(zoneId);
  3178.     var baseEvent = GetBaseEvent(eventName);
  3179.     if (baseEvent == null)
  3180.     {
  3181.       return false;
  3182.     }
  3183.  
  3184.     // avoid allocating this StringBuilder when not debug logging
  3185.     var sbProperties =
  3186.       _configData.Global.DebugEnabled ? Pool.Get<StringBuilder>() : null;
  3187.     if (baseEvent is DomeEvent domeEvent &&
  3188.         domeEvent.DomeData.DomeCreateAllowed(
  3189.           baseEvent.GetDynamicZone() as ISphereZone))
  3190.     {
  3191.       if (RemoveDome(zoneId))
  3192.       {
  3193.         sbProperties?.Append("Dome,");
  3194.       }
  3195.       else
  3196.       {
  3197.         PrintDebug($"DeleteDynamicZone(): ERROR: Dome NOT removed for zoneId={zoneId} with eventName={eventName}.", DebugLevel.Error);
  3198.       }
  3199.     }
  3200.  
  3201.     if (BotReSpawnAllowed(baseEvent as BotDomeEvent))
  3202.     {
  3203.       if (KillBots(zoneId))
  3204.       {
  3205.         sbProperties?.Append("Bots,");
  3206.       }
  3207.       else
  3208.       {
  3209.         PrintDebug($"DeleteDynamicZone(): ERROR: Bot(s) NOT killed for zoneId={zoneId} with eventName={eventName}.", DebugLevel.Error);
  3210.       }
  3211.     }
  3212.  
  3213.     if (TP_RemoveMapping(zoneId))
  3214.     {
  3215.       sbProperties?.Append("Mapping,");
  3216.     }
  3217.     else
  3218.     {
  3219.       PrintDebug($"DeleteDynamicZone(): ERROR: Mapping NOT removed for zoneId={zoneId} with eventName={eventName}.", DebugLevel.Error);
  3220.     }
  3221.  
  3222.     // need to get list of players in zone *before* deleting it
  3223.     // this is unfortunate because it's wasted processing in the case that zone
  3224.     //  deletion fails, but that's an off-nominal case anyway
  3225.     var players = Pool.Get<List<BasePlayer>>();
  3226.     ZM_GetPlayersInZone(zoneId, players);
  3227.     var zoneRemoved = ZM_EraseZone(zoneId, eventName);
  3228.     if (zoneRemoved)
  3229.     {
  3230.       // avoid allocating this StringBuilder when not debug logging or when no
  3231.       //  players were in the zone
  3232.       var sbPlayers = _configData.Global.DebugEnabled && players.Count > 0 ?
  3233.         Pool.Get<StringBuilder>() : null;
  3234.       var first = true;
  3235.       // Release zone players immediately
  3236.       foreach (var player in players)
  3237.       {
  3238.         OnExitZone(zoneId, player);
  3239.         if (first) first = false; else sbPlayers?.Append(", ");
  3240.         sbPlayers?.Append(player.displayName);
  3241.       }
  3242.       if (null != sbPlayers)
  3243.       {
  3244.         PrintDebug($"DeleteDynamicZone(): Released zone players: {sbPlayers}");
  3245.         Pool.FreeUnmanaged(ref sbPlayers);
  3246.       }
  3247.  
  3248.       if (_activeDynamicZones.Remove(zoneId))
  3249.       {
  3250.         UpdateActivePluginZones(added: false, zoneId, baseEvent);
  3251.         CheckHooks(HookCheckReasons.ZoneRemoved, baseEvent);
  3252.       }
  3253.       PrintDebug($"DeleteDynamicZone(): Deleted zoneId={zoneId} with eventName={eventName} and properties: {sbProperties?.ToString().TrimEnd(',')}.");
  3254.       PrintDebug($"DeleteDynamicZone(): Calling OnDeletedDynamicPVP({zoneId}, {eventName})");
  3255.       Interface.CallHook("OnDeletedDynamicPVP", zoneId, eventName);
  3256.     }
  3257.     else
  3258.     {
  3259.       PrintDebug($"DeleteDynamicZone(): ERROR: Zone NOT removed for zoneId={zoneId} with eventName={eventName} and properties: {sbProperties?.ToString().TrimEnd(',')}.", DebugLevel.Error);
  3260.     }
  3261.     Pool.FreeUnmanaged(ref players);
  3262.     if (null != sbProperties) Pool.FreeUnmanaged(ref sbProperties);
  3263.     return zoneRemoved;
  3264.   }
  3265.  
  3266.   #endregion DynamicZone Handler
  3267.  
  3268.   #region Domes
  3269.  
  3270.   private readonly Dictionary<string, List<SphereEntity>> _zoneSpheres = new();
  3271.  
  3272.   private void CreateDome(
  3273.     List<SphereEntity> list, string prefabName, Vector3 position, float radius)
  3274.   {
  3275.     if (null == list || string.IsNullOrEmpty(prefabName) || radius <= 0)
  3276.     {
  3277.       return;
  3278.     }
  3279.  
  3280.     if (GameManager.server.CreateEntity(prefabName, position)
  3281.           is not SphereEntity sphereEntity || !sphereEntity)
  3282.     {
  3283.       PrintDebug($"CreateDome(): ERROR: Failed to create SphereEntity; prefabName={prefabName}, position={position}, radius={radius}", DebugLevel.Error);
  3284.       return;
  3285.     }
  3286.  
  3287.     sphereEntity.enableSaving = false;
  3288.     sphereEntity.Spawn();
  3289.     sphereEntity.LerpRadiusTo(radius * 2f, radius);
  3290.     list.Add(sphereEntity);
  3291.   }
  3292.  
  3293.   private bool CreateDome(
  3294.     string zoneId, Vector3 position, float radius, DomeSettings domeData)
  3295.   {
  3296.     // Method for spherical dome creation
  3297.     if (radius <= 0) return false;
  3298.  
  3299.     var sphereEntities = Pool.Get<List<SphereEntity>>();
  3300.  
  3301.     // add domes
  3302.     for (var i = 0; i < domeData.Darkness; ++i)
  3303.     {
  3304.       CreateDome(sphereEntities, PrefabSphereDome, position, radius);
  3305.     }
  3306.  
  3307.     // add rings
  3308.     foreach (var ring in new[]
  3309.              {
  3310.                (domeData.RedRing,    PrefabSphereRedRing),
  3311.                (domeData.GreenRing,  PrefabSphereGreenRing),
  3312.                (domeData.BlueRing,   PrefabSphereBlueRing),
  3313.                (domeData.PurpleRing, PrefabSpherePurpleRing)
  3314.              })
  3315.     {
  3316.       if (!ring.Item1) continue;
  3317.       CreateDome(sphereEntities, ring.Item2, position, radius);
  3318.     }
  3319.  
  3320.     _zoneSpheres.Add(zoneId, sphereEntities);
  3321.     return true;
  3322.   }
  3323.  
  3324.   private void ParentDome(
  3325.     string zoneId, Vector3 position, BaseEntity parentEntity = null)
  3326.   {
  3327.     if (string.IsNullOrEmpty(zoneId) ||
  3328.         !_zoneSpheres.TryGetValue(zoneId, out var sphereEntities))
  3329.     {
  3330.       return;
  3331.     }
  3332.     foreach (var sphereEntity in sphereEntities)
  3333.     {
  3334.       if (parentEntity is not null && parentEntity)
  3335.       {
  3336.         // tethering dome to parent entity
  3337.         sphereEntity.SetParent(parentEntity);
  3338.         sphereEntity.transform.position = position;
  3339.         sphereEntity.EnableGlobalBroadcast(parentEntity.globalBroadcast);
  3340.       }
  3341.       else
  3342.       {
  3343.         // un-tethering dome from parent entity
  3344.         sphereEntity.SetParent(null, true);
  3345.       }
  3346.     }
  3347.   }
  3348.  
  3349.   private bool RemoveDome(string zoneId)
  3350.   {
  3351.     if (!_zoneSpheres.TryGetValue(zoneId, out var sphereEntities))
  3352.     {
  3353.       return false;
  3354.     }
  3355.     foreach (var sphereEntity in sphereEntities)
  3356.     {
  3357.       sphereEntity.LerpRadiusTo(0, sphereEntity.currentRadius);
  3358.     }
  3359.     timer.Once(5f, () =>
  3360.     {
  3361.       foreach (var sphereEntity in sphereEntities)
  3362.       {
  3363.         if (sphereEntity && !sphereEntity.IsDestroyed)
  3364.         {
  3365.           sphereEntity.KillMessage();
  3366.         }
  3367.       }
  3368.       _zoneSpheres.Remove(zoneId);
  3369.       Pool.FreeUnmanaged(ref sphereEntities);
  3370.     });
  3371.     return true;
  3372.   }
  3373.  
  3374.   #endregion ZoneDome Integration
  3375.  
  3376.   #region TruePVE Integration
  3377.  
  3378.   private object CanEntityTakeDamage(BasePlayer victim, HitInfo info)
  3379.   {
  3380.     if (null == info || !victim || !victim.userID.IsSteamId())
  3381.     {
  3382.       return null;
  3383.     }
  3384.     var attacker = info.InitiatorPlayer ??
  3385.                    (info.Initiator && info.Initiator.OwnerID.IsSteamId() ?
  3386.                      BasePlayer.FindByID(info.Initiator.OwnerID) : null);
  3387.     if (attacker is null || !attacker || !attacker.userID.IsSteamId())
  3388.     {
  3389.       //The attacker cannot be fully captured
  3390.       return null;
  3391.     }
  3392.     if (_pvpDelays.TryGetValue(victim.userID, out var victimLeftZone))
  3393.     {
  3394.       if (_configData.Global.PvpDelayFlags.HasFlag(
  3395.             PvpDelayTypes.ZonePlayersCanDamageDelayedPlayers) &&
  3396.           !string.IsNullOrEmpty(victimLeftZone.zoneId) &&
  3397.           ZM_IsPlayerInZone(victimLeftZone, attacker))
  3398.       {
  3399.         //ZonePlayer attack DelayedPlayer
  3400.         return true;
  3401.       }
  3402.       if (_configData.Global.PvpDelayFlags.HasFlag(
  3403.             PvpDelayTypes.DelayedPlayersCanDamageDelayedPlayers) &&
  3404.           _pvpDelays.TryGetValue(attacker.userID, out var attackerLeftZone) &&
  3405.           victimLeftZone.zoneId == attackerLeftZone.zoneId)
  3406.       {
  3407.         //DelayedPlayer attack DelayedPlayer
  3408.         return true;
  3409.       }
  3410.       return null;
  3411.     }
  3412.     if (_pvpDelays.TryGetValue(attacker.userID, out var attackerLeftZone2) &&
  3413.         _configData.Global.PvpDelayFlags.HasFlag(
  3414.           PvpDelayTypes.DelayedPlayersCanDamageZonePlayers) &&
  3415.         !string.IsNullOrEmpty(attackerLeftZone2.zoneId) &&
  3416.         ZM_IsPlayerInZone(attackerLeftZone2, victim))
  3417.     {
  3418.       //DelayedPlayer attack ZonePlayer
  3419.       return true;
  3420.     }
  3421.     return null;
  3422.   }
  3423.  
  3424.   private static bool TP_AddOrUpdateMapping(string zoneId, string mapping) =>
  3425.     Convert.ToBoolean(
  3426.       Interface.CallHook("AddOrUpdateMapping", zoneId, mapping));
  3427.  
  3428.   private static bool TP_RemoveMapping(string zoneId) =>
  3429.     Convert.ToBoolean(Interface.CallHook("RemoveMapping", zoneId));
  3430.  
  3431.   #endregion TruePVE Integration
  3432.  
  3433.   #region BotReSpawn/MonBots Integration
  3434.  
  3435.   private bool BotReSpawnAllowed(BotDomeEvent botEvent) =>
  3436.     BotReSpawn != null &&
  3437.     botEvent is { BotsEnabled: true } &&
  3438.     !string.IsNullOrEmpty(botEvent.BotProfileName);
  3439.  
  3440.   private bool SpawnBots(Vector3 location, string profileName, string groupId)
  3441.   {
  3442.     if (BotReSpawn == null)
  3443.     {
  3444.       return false;
  3445.     }
  3446.     var result = BS_AddGroupSpawn(location, profileName, groupId);
  3447.     if (result == null || result.Length < 2)
  3448.     {
  3449.       PrintDebug("SpawnBots(): AddGroupSpawn returned invalid response.");
  3450.       return false;
  3451.     }
  3452.     switch (result[0])
  3453.     {
  3454.       case "true":
  3455.         return true;
  3456.       case "false":
  3457.         return false;
  3458.       case "error":
  3459.         PrintDebug($"SpawnBots(): ERROR: AddGroupSpawn failed: {result[1]}", DebugLevel.Error);
  3460.         return false;
  3461.     }
  3462.     PrintDebug($"SpawnBots(): AddGroupSpawn returned unknown response: {result[0]}.");
  3463.     return false;
  3464.   }
  3465.  
  3466.   private bool KillBots(string groupId)
  3467.   {
  3468.     if (BotReSpawn == null)
  3469.     {
  3470.       return true;
  3471.     }
  3472.     var result = BS_RemoveGroupSpawn(groupId);
  3473.     if (result == null || result.Length < 2)
  3474.     {
  3475.       PrintDebug("KillBots(): RemoveGroupSpawn returned invalid response.");
  3476.       return false;
  3477.     }
  3478.     if (result[0] == "error")
  3479.     {
  3480.       PrintDebug($"KillBots(): ERROR: RemoveGroupSpawn failed: {result[1]}", DebugLevel.Error);
  3481.       return false;
  3482.     }
  3483.     return true;
  3484.   }
  3485.  
  3486.   private string[] BS_AddGroupSpawn(
  3487.     Vector3 location, string profileName, string groupId, int quantity = 0) =>
  3488.     BotReSpawn?.Call(
  3489.       "AddGroupSpawn", location, profileName, groupId, quantity) as string[];
  3490.  
  3491.   private string[] BS_RemoveGroupSpawn(string groupId) =>
  3492.     BotReSpawn?.Call("RemoveGroupSpawn", groupId) as string[];
  3493.  
  3494.   #endregion BotReSpawn/MonBots Integration
  3495.  
  3496.   #region ZoneManager Integration
  3497.  
  3498.   private void OnEnterZone(string zoneId, BasePlayer player)
  3499.   {
  3500.     if (!player || !player.userID.IsSteamId())
  3501.     {
  3502.       return;
  3503.     }
  3504.     if (!_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  3505.     {
  3506.       return;
  3507.     }
  3508.     Interface.CallHook("OnPlayerEnterPVP", player, zoneId);
  3509.     PrintDebug($"OnEnterZone(): {player.displayName} has entered PVP zoneId={zoneId} with eventName={eventName}.");
  3510.  
  3511.     if (TryRemovePVPDelay(player)) return;
  3512.     // if player is not re-entering zone while in PVP delay, check for
  3513.     //  weapon holster
  3514.     var baseEvent = GetBaseEvent(eventName);
  3515.     if (null == baseEvent || baseEvent.HolsterTime <= 0)
  3516.     {
  3517.       return;
  3518.     }
  3519.     player.equippingBlocked = true;
  3520.     player.UpdateActiveItem(default);
  3521.     player.Invoke(
  3522.       () => { player.equippingBlocked = false; }, baseEvent.HolsterTime);
  3523.     Print(player, Lang("Holster", player.UserIDString));
  3524.   }
  3525.  
  3526.   private void OnExitZone(string zoneId, BasePlayer player)
  3527.   {
  3528.     if (!player || !player.userID.IsSteamId())
  3529.     {
  3530.       return;
  3531.     }
  3532.     if (!_activeDynamicZones.TryGetValue(zoneId, out var eventName))
  3533.     {
  3534.       return;
  3535.     }
  3536.     PrintDebug($"OnExitZone(): {player.displayName} has left PVP zoneId={zoneId} with eventName={eventName}.");
  3537.  
  3538.     var baseEvent = GetBaseEvent(eventName);
  3539.     if (baseEvent is not { PvpDelayEnabled: true } ||
  3540.         baseEvent.PvpDelayTime <= 0)
  3541.     {
  3542.       Interface.CallHook("OnPlayerExitPVP", player, zoneId);
  3543.       return;
  3544.     }
  3545.     Interface.CallHook("OnPlayerExitPVP",
  3546.       player, zoneId, baseEvent.PvpDelayTime);
  3547.  
  3548.     var leftZone = GetOrAddPVPDelay(player, zoneId, eventName, baseEvent);
  3549.     leftZone.zoneTimer = timer.Once(baseEvent.PvpDelayTime, () =>
  3550.     {
  3551.       TryRemovePVPDelay(player);
  3552.     });
  3553.     var playerID = player.userID.Get();
  3554.     Interface.CallHook("OnPlayerAddedToPVPDelay",
  3555.       playerID, zoneId, baseEvent.PvpDelayTime, player);
  3556.     // also notify TruePVE if we're using its API to implement the delay
  3557.     if (_useExcludePlayer)
  3558.     {
  3559.       Interface.CallHook("ExcludePlayer",
  3560.         playerID, baseEvent.PvpDelayTime, this);
  3561.     }
  3562.   }
  3563.  
  3564.   private bool ZM_CreateOrUpdateZone(
  3565.     string zoneId, string[] zoneArgs, Vector3 location) => Convert.ToBoolean(
  3566.     ZoneManager.Call("CreateOrUpdateTemporaryZone",
  3567.       this, zoneId, zoneArgs, location));
  3568.  
  3569.   private bool ZM_EraseZone(string zoneId, string eventName = "")
  3570.   {
  3571.     try
  3572.     {
  3573.       return Convert.ToBoolean(
  3574.         ZoneManager.Call("EraseTemporaryZone", this, zoneId));
  3575.     }
  3576.     catch (Exception exception)
  3577.     {
  3578.       PrintDebug($"ZM_EraseZone(): ERROR: EraseZone(zoneId={zoneId}) for eventName={eventName} failed: {exception}");
  3579.       return true;
  3580.     }
  3581.   }
  3582.  
  3583.   private void ZM_GetZoneIDs(List<string> list) =>
  3584.     ZoneManager.Call("GetZoneIDsNoAlloc", list);
  3585.  
  3586.   private string ZM_GetZoneName(string zoneId) =>
  3587.     Convert.ToString(ZoneManager.Call("GetZoneName", zoneId));
  3588.  
  3589.   private ZoneManager.Zone ZM_GetZoneByID(string zoneId) =>
  3590.     ZoneManager.Call("GetZoneByID", zoneId) as ZoneManager.Zone;
  3591.  
  3592.   private void ZM_GetPlayerZoneIDs(BasePlayer player, List<string> list) =>
  3593.     ZoneManager.Call("GetPlayerZoneIDsNoAlloc", player, list);
  3594.  
  3595.   private bool ZM_IsPlayerInZone(LeftZone leftZone, BasePlayer player) =>
  3596.     Convert.ToBoolean(
  3597.       ZoneManager.Call("IsPlayerInZone", leftZone.zoneId, player));
  3598.  
  3599.   private void ZM_GetPlayersInZone(string zoneId, List<BasePlayer> list) =>
  3600.     ZoneManager.Call("GetPlayersInZoneNoAlloc", zoneId, list);
  3601.  
  3602.   // parent event's zone and (if applicable) domes to a given entity, so that
  3603.   //  they move together
  3604.   private void ParentEventToEntity(
  3605.     string zoneId, BaseEvent baseEvent, BaseEntity parentEntity,
  3606.     bool deleteOnFailure, bool delay = true)
  3607.   {
  3608.     if (delay)
  3609.     {
  3610.       timer.Once(0.25f, () => ParentEventToEntity(
  3611.         zoneId, baseEvent, parentEntity, deleteOnFailure, false));
  3612.       return;
  3613.     }
  3614.     var zone = ZM_GetZoneByID(zoneId);
  3615.     if (!parentEntity || !zone)
  3616.     {
  3617.       PrintDebug($"ParentEventToEntity(): ERROR: The zoneId={zoneId} has null zone={zone} and/or parentEntity={parentEntity}.", DebugLevel.Error);
  3618.       if (deleteOnFailure) DeleteDynamicZone(zoneId);
  3619.       return;
  3620.     }
  3621.     // only support parenting if event implements IParentZone
  3622.     if (baseEvent.GetDynamicZone() is not IParentZone parentZone)
  3623.     {
  3624.       PrintDebug($"ParentEventToEntity(): ERROR: Not parenting zoneId={zoneId} to parentEntity={parentEntity} because event's DynamicZone does not implement IParentZone.", DebugLevel.Error);
  3625.       if (deleteOnFailure) DeleteDynamicZone(zoneId);
  3626.       return;
  3627.     }
  3628.     var zoneTransform = zone.transform;
  3629.     var position = parentEntity.transform.TransformPoint(parentZone.Center);
  3630.     zoneTransform.SetParent(parentEntity.transform);
  3631.     zoneTransform.rotation = parentEntity.transform.rotation;
  3632.     zoneTransform.position = position;
  3633.     PrintDebug($"ParentEventToEntity(): Parented zoneId={zoneId} to parentEntity={parentEntity}.");
  3634.     // also parent any domes
  3635.     ParentDome(zoneId, position, parentEntity);
  3636.   }
  3637.  
  3638.   #endregion ZoneManager Integration
  3639.  
  3640.   #region Backpacks/LootDefender/RestoreUponDeath Integration
  3641.  
  3642.   /// return whether zones for the given base event are relevant to the given
  3643.   ///  plugin integration category
  3644.   private static bool HasPluginZoneCategory(
  3645.     BaseEvent baseEvent, PluginZoneCategory category) =>
  3646.     category switch
  3647.     {
  3648.       PluginZoneCategory.BackpacksForce =>
  3649.         baseEvent.DropPluginBackpacks == true,
  3650.       PluginZoneCategory.BackpacksPrevent =>
  3651.         baseEvent.DropPluginBackpacks == false,
  3652.       PluginZoneCategory.LootDefender =>
  3653.         baseEvent.BypassLootDefenderLocks,
  3654.       PluginZoneCategory.RestoreUponDeath =>
  3655.         baseEvent.BlockRestoreUponDeath,
  3656.       _ => false
  3657.     };
  3658.  
  3659.   /// get the hook category enum value corresponding to the given plugin zone
  3660.   ///  category value
  3661.   private static HookCategory ToHookCategory(
  3662.     PluginZoneCategory pluginZoneCategory) =>
  3663.     pluginZoneCategory switch
  3664.     {
  3665.       PluginZoneCategory.BackpacksForce =>
  3666.         HookCategory.PluginBackpacksForce,
  3667.       PluginZoneCategory.BackpacksPrevent =>
  3668.         HookCategory.PluginBackpacksPrevent,
  3669.       PluginZoneCategory.LootDefender =>
  3670.         HookCategory.PluginLootDefender,
  3671.       PluginZoneCategory.RestoreUponDeath =>
  3672.         HookCategory.PluginRestoreUponDeath,
  3673.       _ => throw new ArgumentOutOfRangeException(nameof(pluginZoneCategory))
  3674.     };
  3675.  
  3676.   /// add/remove _activePluginZones HashSet entries for any plugin integration
  3677.   ///  categories associated with the base event for a given zone that's being
  3678.   ///  added/removed
  3679.   private void UpdateActivePluginZones(
  3680.     bool added, string zoneId, BaseEvent baseEvent)
  3681.   {
  3682.     // check each possible plugin integration category
  3683.     foreach (var (category, zoneSet) in _activePluginZones)
  3684.     {
  3685.       // skip base events without this plugin integration active
  3686.       if (!HasPluginZoneCategory(baseEvent, category))
  3687.       {
  3688.         continue;
  3689.       }
  3690.  
  3691.       if (added)
  3692.       {
  3693.         // add new zone to plugin integration category active zones
  3694.         zoneSet.Add(zoneId);
  3695.       }
  3696.       else
  3697.       {
  3698.         // remove defunct zone from plugin integration category active zones
  3699.         zoneSet.Remove(zoneId);
  3700.       }
  3701.     }
  3702.   }
  3703.  
  3704.   /// return true if player is determined to be in a zone of the given plugin
  3705.   ///  integration category, else false
  3706.   private bool PlayerInActivePluginZone(
  3707.     BasePlayer player, PluginZoneCategory pzCat)
  3708.   {
  3709.     // abort if not a valid, real player
  3710.     if (!player || !player.userID.IsSteamId())
  3711.     {
  3712.       return false;
  3713.     }
  3714.  
  3715.     // abort if we don't have a zone set for requested category (pathological)
  3716.     if (!_activePluginZones.TryGetValue(pzCat, out var zoneSet))
  3717.     {
  3718.       return false;
  3719.     }
  3720.  
  3721.     // get zones player is in, on the assumption that backpack is dropping at
  3722.     //  their position, as this is much more efficient to check than a raw
  3723.     //  position
  3724.     var zoneIDs = Pool.Get<List<string>>();
  3725.     ZM_GetPlayerZoneIDs(player, zoneIDs);
  3726.  
  3727.     // check to see if any of the player's zones are in the set of active
  3728.     //  zones for the relevant plugin integration
  3729.     foreach (var zoneId in zoneIDs)
  3730.     {
  3731.       if (string.IsNullOrEmpty(zoneId) || !zoneSet.Contains(zoneId)) continue;
  3732.       // report match
  3733.       Pool.FreeUnmanaged(ref zoneIDs);
  3734.       return true;
  3735.     }
  3736.  
  3737.     // no match found
  3738.     Pool.FreeUnmanaged(ref zoneIDs);
  3739.     return false;
  3740.   }
  3741.  
  3742.   /// hook handler: return false to prevent plugin Backpacks drop if owner ID
  3743.   ///  can be resolved to a BasePlayer who is in a drop-prevented zone, else
  3744.   ///  return true to allow backpack drop
  3745.   private bool CanDropBackpack(ulong backpackOwnerID, Vector3 position) =>
  3746.     !BasePlayer.TryFindByID(backpackOwnerID, out var player) ||
  3747.     !PlayerInActivePluginZone(player, PluginZoneCategory.BackpacksPrevent);
  3748.  
  3749.   /// request plugin Backpacks drop if player dies in a drop-forced zone
  3750.   private void OnPlayerDeath(BasePlayer player, HitInfo info)
  3751.   {
  3752.     if (PlayerInActivePluginZone(player, PluginZoneCategory.BackpacksForce))
  3753.     {
  3754.       // request backpack drop
  3755.       Backpacks?.Call("API_DropBackpack", player);
  3756.     }
  3757.   }
  3758.  
  3759.   /// hook handler: return true to bypass Loot Defender locks if player is in
  3760.   ///  a bypass-enabled zone, else return null to take no action
  3761.   private object OnLootLockedEntity(BasePlayer player, BaseEntity entity) =>
  3762.     PlayerInActivePluginZone(player, PluginZoneCategory.LootDefender) ?
  3763.       true : null;
  3764.  
  3765.   /// hook handler: return true to block Restore Upon Death if player is in a
  3766.   ///  restore-blocked zone, else return null to take no action
  3767.   private object OnRestoreUponDeath(BasePlayer player) =>
  3768.     PlayerInActivePluginZone(player, PluginZoneCategory.RestoreUponDeath) ?
  3769.       true : null;
  3770.  
  3771.   #endregion Backpacks/LootDefender/RestoreUponDeath Integration
  3772.  
  3773.   #region Debug
  3774.  
  3775.   private StringBuilder _debugStringBuilder;
  3776.  
  3777.   private enum DebugLevel { Error, Warning, Info };
  3778.  
  3779.   private void PrintDebug(string message, DebugLevel level = DebugLevel.Info)
  3780.   {
  3781.     if (_configData.Global.DebugEnabled)
  3782.     {
  3783.       switch (level)
  3784.       {
  3785.         case DebugLevel.Error:   PrintError(message);   break;
  3786.         case DebugLevel.Warning: PrintWarning(message); break;
  3787.         case DebugLevel.Info:    Puts(message);         break;
  3788.       }
  3789.     }
  3790.  
  3791.     if (_configData.Global.LogToFile)
  3792.     {
  3793.       _debugStringBuilder.AppendLine($"[{DateTime.Now.ToString(CultureInfo.InstalledUICulture)}] | {message}");
  3794.     }
  3795.   }
  3796.  
  3797.   private void SaveDebug()
  3798.   {
  3799.     if (!_configData.Global.LogToFile)
  3800.     {
  3801.       return;
  3802.     }
  3803.     var debugText = _debugStringBuilder.ToString().Trim();
  3804.     _debugStringBuilder.Clear();
  3805.     if (!string.IsNullOrEmpty(debugText))
  3806.     {
  3807.       LogToFile("debug", debugText, this);
  3808.     }
  3809.   }
  3810.  
  3811.   #endregion Debug
  3812.  
  3813.   #region API
  3814.  
  3815.   private string[] AllDynamicPVPZones()
  3816.   {
  3817.     // this is tortured, but we do it to avoid Linq
  3818.     var retVal = new string[_activeDynamicZones.Count];
  3819.     var i = 0;
  3820.     foreach (var key in _activeDynamicZones.Keys) retVal[i++] = key;
  3821.     return retVal;
  3822.   }
  3823.  
  3824.   private void AllDynamicPVPZonesNoAlloc(List<string> list) =>
  3825.     list.AddRange(_activeDynamicZones.Keys);
  3826.  
  3827.   private bool IsDynamicPVPZone(string zoneId) =>
  3828.     _activeDynamicZones.ContainsKey(zoneId);
  3829.  
  3830.   private bool EventDataExists(string eventName) =>
  3831.     _storedData.EventDataExists(eventName);
  3832.  
  3833.   private bool IsPlayerInPVPDelay(ulong playerId) =>
  3834.     _pvpDelays.ContainsKey(playerId);
  3835.  
  3836.   private string GetPlayerPVPDelayedZoneID(ulong playerId) =>
  3837.     _pvpDelays.TryGetValue(playerId, out var leftZone) ?
  3838.       leftZone.zoneId : null;
  3839.  
  3840.   private string GetEventName(string zoneId) =>
  3841.     _activeDynamicZones.GetValueOrDefault(zoneId);
  3842.  
  3843.   private bool CreateOrUpdateEventData(
  3844.     string eventName, string eventData, bool isTimed = false)
  3845.   {
  3846.     if (string.IsNullOrEmpty(eventName) || string.IsNullOrEmpty(eventData))
  3847.     {
  3848.       return false;
  3849.     }
  3850.     if (EventDataExists(eventName))
  3851.     {
  3852.       RemoveEventData(eventName);
  3853.     }
  3854.     if (isTimed)
  3855.     {
  3856.       TimedEvent timedEvent;
  3857.       try
  3858.       {
  3859.         timedEvent = JsonConvert.DeserializeObject<TimedEvent>(eventData);
  3860.       }
  3861.       catch
  3862.       {
  3863.         return false;
  3864.       }
  3865.       _storedData.timedEvents.Add(eventName, timedEvent);
  3866.     }
  3867.     else
  3868.     {
  3869.       AutoEvent autoEvent;
  3870.       try
  3871.       {
  3872.         autoEvent = JsonConvert.DeserializeObject<AutoEvent>(eventData);
  3873.       }
  3874.       catch
  3875.       {
  3876.         return false;
  3877.       }
  3878.       _storedData.autoEvents.Add(eventName, autoEvent);
  3879.       if (autoEvent.AutoStart)
  3880.       {
  3881.         CreateDynamicZone(eventName, autoEvent.Position, autoEvent.ZoneId);
  3882.       }
  3883.     }
  3884.     _dataChanged = true;
  3885.     return true;
  3886.   }
  3887.  
  3888.   private bool CreateEventData(
  3889.     string eventName, Vector3 position, bool isTimed)
  3890.   {
  3891.     if (EventDataExists(eventName))
  3892.     {
  3893.       return false;
  3894.     }
  3895.     if (isTimed)
  3896.     {
  3897.       _storedData.timedEvents.Add(eventName, new TimedEvent());
  3898.     }
  3899.     else
  3900.     {
  3901.       _storedData.autoEvents.Add(
  3902.         eventName, new AutoEvent { Position = position });
  3903.     }
  3904.     _dataChanged = true;
  3905.     return true;
  3906.   }
  3907.  
  3908.   private bool RemoveEventData(string eventName, bool forceClose = true)
  3909.   {
  3910.     if (!EventDataExists(eventName))
  3911.     {
  3912.       return false;
  3913.     }
  3914.     _storedData.RemoveEventData(eventName);
  3915.     if (forceClose)
  3916.     {
  3917.       ForceCloseZones(eventName);
  3918.     }
  3919.     _dataChanged = true;
  3920.     return true;
  3921.   }
  3922.  
  3923.   private bool StartEvent(string eventName, Vector3 position)
  3924.   {
  3925.     if (!EventDataExists(eventName))
  3926.     {
  3927.       return false;
  3928.     }
  3929.     var baseEvent = GetBaseEvent(eventName);
  3930.     return baseEvent switch
  3931.     {
  3932.       AutoEvent autoEvent => CreateDynamicZone(
  3933.         eventName, position == default ? autoEvent.Position : position,
  3934.         autoEvent.ZoneId),
  3935.       BaseTimedEvent => CreateDynamicZone(eventName, position),
  3936.       _ => false
  3937.     };
  3938.   }
  3939.  
  3940.   private bool StopEvent(string eventName) =>
  3941.     EventDataExists(eventName) && ForceCloseZones(eventName);
  3942.  
  3943.   private bool ForceCloseZones(string eventName)
  3944.   {
  3945.     var closed = false;
  3946.     // create a temporary list of _activeDynamicZones entries, because deleting
  3947.     //  any will cause modifications to the latter
  3948.     var entries = Pool.Get<List<KeyValuePair<string, string>>>();
  3949.     entries.AddRange(_activeDynamicZones);
  3950.     foreach (var entry in entries)
  3951.     {
  3952.       if (entry.Value != eventName || !DeleteDynamicZone(entry.Key)) continue;
  3953.       closed = true;
  3954.     }
  3955.     Pool.FreeUnmanaged(ref entries);
  3956.     return closed;
  3957.   }
  3958.  
  3959.   private bool IsUsingExcludePlayer() => _useExcludePlayer;
  3960.  
  3961.   #endregion API
  3962.  
  3963.   #region Commands
  3964.  
  3965.   private static void DrawCube(
  3966.     BasePlayer player, float duration, Color color,
  3967.     Vector3 pos, Vector3 size, float rotation)
  3968.   {
  3969.     // this is complicated because ddraw doesn't have a rectangular prism
  3970.     //  rendering option, so we need to figure out where all the rotated
  3971.     //  vertices are and then draw all the edges
  3972.     var halfSize = size / 2;
  3973.     Vector3[] vertices =
  3974.     {
  3975.       // corners
  3976.       new(pos.x + halfSize.x, pos.y + halfSize.y, pos.z + halfSize.z),
  3977.       new(pos.x + halfSize.x, pos.y + halfSize.y, pos.z - halfSize.z),
  3978.       new(pos.x + halfSize.x, pos.y - halfSize.y, pos.z + halfSize.z),
  3979.       new(pos.x + halfSize.x, pos.y - halfSize.y, pos.z - halfSize.z),
  3980.       new(pos.x - halfSize.x, pos.y + halfSize.y, pos.z + halfSize.z),
  3981.       new(pos.x - halfSize.x, pos.y + halfSize.y, pos.z - halfSize.z),
  3982.       new(pos.x - halfSize.x, pos.y - halfSize.y, pos.z + halfSize.z),
  3983.       new(pos.x - halfSize.x, pos.y - halfSize.y, pos.z - halfSize.z),
  3984.       // axes
  3985.       new(pos.x, pos.y, pos.z),
  3986.       new(pos.x + halfSize.x, pos.y, pos.z),
  3987.       new(pos.x, pos.y + halfSize.y, pos.z),
  3988.       new(pos.x, pos.y, pos.z + halfSize.z)
  3989.     };
  3990.  
  3991.     // rotate all the points
  3992.     var rotQ = Quaternion.Euler(0, rotation, 0);
  3993.     for (int i = 0; i < vertices.Length; ++i)
  3994.     {
  3995.       vertices[i] = (rotQ * (vertices[i] - pos)) + pos;
  3996.     }
  3997.  
  3998.     // corners
  3999.     player.SendConsoleCommand(
  4000.       "ddraw.line",  duration, color, vertices[0], vertices[1]);
  4001.     player.SendConsoleCommand(
  4002.       "ddraw.line",  duration, color, vertices[0], vertices[2]);
  4003.     player.SendConsoleCommand(
  4004.       "ddraw.line",  duration, color, vertices[0], vertices[4]);
  4005.     player.SendConsoleCommand(
  4006.       "ddraw.line",  duration, color, vertices[1], vertices[3]);
  4007.     player.SendConsoleCommand(
  4008.       "ddraw.line",  duration, color, vertices[1], vertices[5]);
  4009.     player.SendConsoleCommand(
  4010.       "ddraw.line",  duration, color, vertices[2], vertices[3]);
  4011.     player.SendConsoleCommand(
  4012.       "ddraw.line",  duration, color, vertices[2], vertices[6]);
  4013.     player.SendConsoleCommand(
  4014.       "ddraw.line",  duration, color, vertices[3], vertices[7]);
  4015.     player.SendConsoleCommand(
  4016.       "ddraw.line",  duration, color, vertices[4], vertices[5]);
  4017.     player.SendConsoleCommand(
  4018.       "ddraw.line",  duration, color, vertices[4], vertices[6]);
  4019.     player.SendConsoleCommand(
  4020.       "ddraw.line",  duration, color, vertices[5], vertices[7]);
  4021.     player.SendConsoleCommand(
  4022.       "ddraw.line",  duration, color, vertices[6], vertices[7]);
  4023.     // axes
  4024.     player.SendConsoleCommand(
  4025.       "ddraw.arrow", duration, Color.red,   vertices[8], vertices[9],  5);
  4026.     player.SendConsoleCommand(
  4027.       "ddraw.arrow", duration, Color.green, vertices[8], vertices[10], 5);
  4028.     player.SendConsoleCommand(
  4029.       "ddraw.arrow", duration, Color.blue,  vertices[8], vertices[11], 5);
  4030.     player.SendConsoleCommand(
  4031.       "ddraw.text",  duration, Color.red,   vertices[9],  "+x");
  4032.     player.SendConsoleCommand(
  4033.       "ddraw.text",  duration, Color.green, vertices[10], "+y");
  4034.     player.SendConsoleCommand(
  4035.       "ddraw.text",  duration, Color.blue,  vertices[11], "+z");
  4036.   }
  4037.  
  4038.   private static void DrawSphere(
  4039.     BasePlayer player, float duration, Color color,
  4040.     Vector3 pos, float radius, float rotation)
  4041.   {
  4042.     player.SendConsoleCommand(
  4043.       "ddraw.sphere", duration, color, pos, radius);
  4044.  
  4045.     // axes
  4046.     Vector3[] vertices =
  4047.     {
  4048.       new(pos.x,          pos.y,          pos.z),
  4049.       new(pos.x + radius, pos.y,          pos.z),
  4050.       new(pos.x,          pos.y + radius, pos.z),
  4051.       new(pos.x,          pos.y,          pos.z + radius)
  4052.     };
  4053.  
  4054.     // rotate all the points
  4055.     var rotQ = Quaternion.Euler(0, rotation, 0);
  4056.     for (int i = 0; i < vertices.Length; ++i)
  4057.     {
  4058.       vertices[i] = (rotQ * (vertices[i] - pos)) + pos;
  4059.     }
  4060.  
  4061.     player.SendConsoleCommand(
  4062.       "ddraw.arrow", duration, Color.red,   vertices[0], vertices[1], 5);
  4063.     player.SendConsoleCommand(
  4064.       "ddraw.arrow", duration, Color.green, vertices[0], vertices[2], 5);
  4065.     player.SendConsoleCommand(
  4066.       "ddraw.arrow", duration, Color.blue,  vertices[0], vertices[3], 5);
  4067.     player.SendConsoleCommand(
  4068.       "ddraw.text", duration, Color.red,    vertices[1], "+x");
  4069.     player.SendConsoleCommand(
  4070.       "ddraw.text", duration, Color.green,  vertices[2], "+y");
  4071.     player.SendConsoleCommand(
  4072.       "ddraw.text", duration, Color.blue,   vertices[3], "+z");
  4073.   }
  4074.  
  4075.   private void CommandHelp(IPlayer iPlayer)
  4076.   {
  4077.     var stringBuilder = Pool.Get<StringBuilder>();
  4078.     var result = stringBuilder
  4079.         .Clear()
  4080.         .AppendLine()
  4081.         .AppendLine(Lang("Syntax",  iPlayer.Id, _configData.Chat.Command))
  4082.         .AppendLine(Lang("Syntax1", iPlayer.Id, _configData.Chat.Command))
  4083.         .AppendLine(Lang("Syntax2", iPlayer.Id, _configData.Chat.Command))
  4084.         .AppendLine(Lang("Syntax3", iPlayer.Id, _configData.Chat.Command))
  4085.         .AppendLine(Lang("Syntax4", iPlayer.Id, _configData.Chat.Command))
  4086.         .AppendLine(Lang("Syntax5", iPlayer.Id, _configData.Chat.Command))
  4087.         .AppendLine(Lang("Syntax6", iPlayer.Id, _configData.Chat.Command))
  4088.         .AppendLine(Lang("Syntax7", iPlayer.Id, _configData.Chat.Command))
  4089.         .AppendLine(Lang("Syntax8", iPlayer.Id, _configData.Chat.Command))
  4090.         .ToString()
  4091.       ;
  4092.     stringBuilder.Clear();
  4093.     Pool.FreeUnmanaged(ref stringBuilder);
  4094.     Print(iPlayer, result);
  4095.   }
  4096.  
  4097.   private void CommandList(IPlayer iPlayer)
  4098.   {
  4099.     var customEventCount = _storedData.CustomEventsCount;
  4100.     if (customEventCount <= 0)
  4101.     {
  4102.       Print(iPlayer, Lang("NoCustomEvent", iPlayer.Id));
  4103.       return;
  4104.     }
  4105.     var i = 0;
  4106.     var stringBuilder = Pool.Get<StringBuilder>();
  4107.     stringBuilder.Clear();
  4108.     stringBuilder.AppendLine(Lang("CustomEvents",
  4109.       iPlayer.Id, customEventCount));
  4110.     foreach (var entry in _storedData.autoEvents)
  4111.     {
  4112.       i++;
  4113.       stringBuilder.AppendLine(Lang("AutoEvent",
  4114.         iPlayer.Id, i,
  4115.         entry.Key, entry.Value.AutoStart, entry.Value.Position));
  4116.     }
  4117.     foreach (var entry in _storedData.timedEvents)
  4118.     {
  4119.       i++;
  4120.       stringBuilder.AppendLine(Lang("TimedEvent",
  4121.         iPlayer.Id, i, entry.Key, entry.Value.Duration));
  4122.     }
  4123.     Print(iPlayer, stringBuilder.ToString());
  4124.     stringBuilder.Clear();
  4125.     Pool.FreeUnmanaged(ref stringBuilder);
  4126.   }
  4127.  
  4128.   private void CommandShow(BasePlayer player)
  4129.   {
  4130.     if (!player)
  4131.     {
  4132.       PrintDebug("CommandShow(): Got null player; aborting", DebugLevel.Error);
  4133.       return;
  4134.     }
  4135.  
  4136.     Print(player, Lang("ShowingZones", player.UserIDString, _configData.Chat.ShowDistance, _configData.Chat.ShowDuration));
  4137.  
  4138.     var playerPosition2D = player.transform.position.XZ2D();
  4139.     foreach (var activeEvent in _activeDynamicZones)
  4140.     {
  4141.       var zoneData = ZM_GetZoneByID(activeEvent.Key);
  4142.       if (!zoneData) continue;
  4143.       var position = zoneData.transform.position;
  4144.       if (Vector2.Distance(playerPosition2D, position.XZ2D()) >
  4145.           _configData.Chat.ShowDistance)
  4146.       {
  4147.         continue;
  4148.       }
  4149.       var baseZone = GetBaseEvent(activeEvent.Value)?.GetDynamicZone();
  4150.       var zoneColor = baseZone switch
  4151.       {
  4152.         SphereCubeDynamicZone => Color.yellow,
  4153.         SphereCubeParentDynamicZone => Color.blue,
  4154.         _ => Color.red
  4155.       };
  4156.  
  4157.       switch (zoneData.collider)
  4158.       {
  4159.         case BoxCollider b:
  4160.           DrawCube(
  4161.             player, _configData.Chat.ShowDuration, zoneColor,
  4162.             zoneData.transform.position, b.size,
  4163.             zoneData.transform.eulerAngles.y);
  4164.           break;
  4165.  
  4166.         case SphereCollider s:
  4167.           DrawSphere(
  4168.             player, _configData.Chat.ShowDuration, zoneColor,
  4169.             zoneData.transform.position, s.radius,
  4170.             zoneData.transform.eulerAngles.y);
  4171.           break;
  4172.       }
  4173.  
  4174.       player.SendConsoleCommand(
  4175.         "ddraw.text", _configData.Chat.ShowDuration, zoneColor,
  4176.         zoneData.transform.position,
  4177.         $"{activeEvent.Key}\n{activeEvent.Value}");
  4178.     }
  4179.   }
  4180.  
  4181.   private void CommandEdit(
  4182.     IPlayer iPlayer, string eventName, Vector3 position, string arg)
  4183.   {
  4184.     if (_storedData.autoEvents.TryGetValue(eventName, out var autoEvent))
  4185.     {
  4186.       switch (arg.ToLower())
  4187.       {
  4188.         case "0":
  4189.         case "false":
  4190.         {
  4191.           autoEvent.AutoStart = false;
  4192.           Print(iPlayer, Lang("AutoEventAutoStart",
  4193.             iPlayer.Id, eventName, false));
  4194.           _dataChanged = true;
  4195.           return;
  4196.         }
  4197.  
  4198.         case "1":
  4199.         case "true":
  4200.         {
  4201.           autoEvent.AutoStart = true;
  4202.           Print(iPlayer, Lang("AutoEventAutoStart",
  4203.             iPlayer.Id, eventName, true));
  4204.           _dataChanged = true;
  4205.           return;
  4206.         }
  4207.  
  4208.         case "move":
  4209.         {
  4210.           autoEvent.Position = position;
  4211.           Print(iPlayer, Lang("AutoEventMove", iPlayer.Id, eventName));
  4212.           _dataChanged = true;
  4213.           return;
  4214.         }
  4215.       }
  4216.     }
  4217.     else if (_storedData.timedEvents.TryGetValue(eventName, out var timedEvent)
  4218.              && float.TryParse(arg, out var duration))
  4219.     {
  4220.       timedEvent.Duration = duration;
  4221.       Print(iPlayer, Lang("TimedEventDuration",
  4222.         iPlayer.Id, eventName, duration));
  4223.       _dataChanged = true;
  4224.       return;
  4225.     }
  4226.     Print(iPlayer, Lang("SyntaxError", iPlayer.Id, _configData.Chat.Command));
  4227.   }
  4228.  
  4229.   private void CmdDynamicPVP(IPlayer iPlayer, string command, string[] args)
  4230.   {
  4231.     if (!iPlayer.IsAdmin && !iPlayer.HasPermission(PermissionAdmin))
  4232.     {
  4233.       Print(iPlayer, Lang("NotAllowed", iPlayer.Id));
  4234.       return;
  4235.     }
  4236.     if (args == null || args.Length < 1)
  4237.     {
  4238.       Print(iPlayer, Lang("SyntaxError", iPlayer.Id, _configData.Chat.Command));
  4239.       return;
  4240.     }
  4241.     var commandName = args[0].ToLower();
  4242.     // check command and dispatch to appropriate handler
  4243.     switch (commandName)
  4244.     {
  4245.       case "?":
  4246.       case "h":
  4247.       case "help":
  4248.       {
  4249.         CommandHelp(iPlayer);
  4250.         return;
  4251.       }
  4252.  
  4253.       case "list":
  4254.       {
  4255.         CommandList(iPlayer);
  4256.         return;
  4257.       }
  4258.  
  4259.       case "show":
  4260.       {
  4261.         CommandShow(iPlayer.Object as BasePlayer);
  4262.         return;
  4263.       }
  4264.     }
  4265.     // handle commands that take additional parameters
  4266.     var eventName = args[1];
  4267.     var position =
  4268.       (iPlayer.Object as BasePlayer)?.transform.position ?? Vector3.zero;
  4269.     switch (commandName)
  4270.     {
  4271.       case "add":
  4272.       {
  4273.         var isTimed = args.Length >= 3;
  4274.         Print(iPlayer, CreateEventData(eventName, position, isTimed) ?
  4275.           Lang("EventDataAdded", iPlayer.Id, eventName) :
  4276.           Lang("EventNameExist", iPlayer.Id, eventName));
  4277.         return;
  4278.       }
  4279.  
  4280.       case "remove":
  4281.       {
  4282.         Print(iPlayer, RemoveEventData(eventName) ?
  4283.           Lang("EventDataRemoved", iPlayer.Id, eventName) :
  4284.           Lang("EventNameNotExist", iPlayer.Id, eventName));
  4285.         return;
  4286.       }
  4287.  
  4288.       case "start":
  4289.       {
  4290.         Print(iPlayer, StartEvent(eventName, position) ?
  4291.           Lang("EventStarted", iPlayer.Id, eventName) :
  4292.           Lang("EventNameNotExist", iPlayer.Id, eventName));
  4293.         return;
  4294.       }
  4295.  
  4296.       case "stop":
  4297.       {
  4298.         Print(iPlayer, StopEvent(eventName) ?
  4299.           Lang("EventStopped", iPlayer.Id, eventName) :
  4300.           Lang("EventNameNotExist", iPlayer.Id, eventName));
  4301.         return;
  4302.       }
  4303.  
  4304.       case "edit":
  4305.       {
  4306.         if (args.Length >= 3)
  4307.         {
  4308.           CommandEdit(iPlayer, eventName, position, args[2]);
  4309.           return;
  4310.         }
  4311.         break;
  4312.       }
  4313.     }
  4314.     Print(iPlayer, Lang("SyntaxError", iPlayer.Id, _configData.Chat.Command));
  4315.   }
  4316.  
  4317.   #endregion Commands
  4318.  
  4319.   #region ConfigurationFile
  4320.  
  4321.   private ConfigData _configData;
  4322.  
  4323.   private sealed class ConfigData
  4324.   {
  4325.     [JsonProperty(PropertyName = "Global Settings")]
  4326.     public GlobalSettings Global { get; set; } = new();
  4327.  
  4328.     [JsonProperty(PropertyName = "Chat Settings")]
  4329.     public ChatSettings Chat { get; set; } = new();
  4330.  
  4331.     [JsonProperty(PropertyName = "General Event Settings")]
  4332.     public GeneralEventSettings GeneralEvents { get; set; } = new();
  4333.  
  4334.     [JsonProperty(PropertyName = "Deep Sea Event Settings")]
  4335.     public DeepSeaEventSettings DeepSeaEvents { get; set; } = new();
  4336.  
  4337.     [JsonProperty(PropertyName = "Monument Event Settings")]
  4338.     public SortedDictionary<string, MonumentEvent>
  4339.       MonumentEvents { get; set; } = new();
  4340.  
  4341.     [JsonProperty(PropertyName = "Version")]
  4342.     public VersionNumber Version { get; set; }
  4343.   }
  4344.  
  4345.   private sealed class GlobalSettings
  4346.   {
  4347.     [JsonProperty(PropertyName = "Enable Debug Mode")]
  4348.     public bool DebugEnabled { get; set; }
  4349.  
  4350.     [JsonProperty(PropertyName = "Log Debug To File")]
  4351.     public bool LogToFile { get; set; }
  4352.  
  4353.     [JsonProperty(PropertyName = "Compare Radius (Used to determine if it is a SupplySignal)")]
  4354.     public float CompareRadius { get; set; } = 2f;
  4355.  
  4356.     [JsonProperty(PropertyName = "If the entity has an owner, don't create a PVP zone")]
  4357.     public bool CheckEntityOwner { get; set; } = true;
  4358.  
  4359.     [JsonProperty(PropertyName = "Use TruePVE PVP Delay API (more efficient and cross-plugin, but supersedes PVP Delay Flags)")]
  4360.     public bool UseExcludePlayer { get; set; }
  4361.  
  4362.     [JsonProperty(PropertyName = "PVP Delay Flags")]
  4363.     public PvpDelayTypes PvpDelayFlags { get; set; } =
  4364.       PvpDelayTypes.ZonePlayersCanDamageDelayedPlayers |
  4365.       PvpDelayTypes.DelayedPlayersCanDamageDelayedPlayers |
  4366.       PvpDelayTypes.DelayedPlayersCanDamageZonePlayers;
  4367.   }
  4368.  
  4369.   private sealed class ChatSettings
  4370.   {
  4371.     [JsonProperty(PropertyName = "Command")]
  4372.     public string Command { get; set; } = "dynpvp";
  4373.  
  4374.     [JsonProperty(PropertyName = "Chat Prefix")]
  4375.     public string Prefix { get; set; } = "[DynamicPVP]: ";
  4376.  
  4377.     [JsonProperty(PropertyName = "Chat Prefix Color")]
  4378.     public string PrefixColor { get; set; } = "#00FFFF";
  4379.  
  4380.     [JsonProperty(PropertyName = "Chat SteamID Icon")]
  4381.     public ulong SteamIdIcon { get; set; }
  4382.  
  4383.     [JsonProperty(PropertyName = "Zone Show Distance")]
  4384.     public float ShowDistance { get; set; } = 1000.0f;
  4385.  
  4386.     [JsonProperty(PropertyName = "Zone Show Duration (in seconds)")]
  4387.     public float ShowDuration { get; set; } = 15.0f;
  4388.   }
  4389.  
  4390.   private sealed class GeneralEventSettings
  4391.   {
  4392.     [JsonProperty(PropertyName = "Bradley Event")]
  4393.     public TimedEvent BradleyApc { get; set; } = new();
  4394.  
  4395.     [JsonProperty(PropertyName = "Patrol Helicopter Event")]
  4396.     public TimedEvent PatrolHelicopter { get; set; } = new();
  4397.  
  4398.     [JsonProperty(PropertyName = "Supply Signal Event")]
  4399.     public SupplyDropEvent SupplySignal { get; set; } = new();
  4400.  
  4401.     [JsonProperty(PropertyName = "Timed Supply Event")]
  4402.     public SupplyDropEvent TimedSupply { get; set; } = new();
  4403.  
  4404.     [JsonProperty(PropertyName = "Hackable Crate Event")]
  4405.     public HackableCrateEvent HackableCrate { get; set; } = new();
  4406.  
  4407.     [JsonProperty(PropertyName = "Excavator Ignition Event")]
  4408.     public IgnitionEvent ExcavatorIgnition { get; set; } = new();
  4409.  
  4410.     [JsonProperty(PropertyName = "Cargo Ship Event")]
  4411.     public CargoShipEvent CargoShip { get; set; } = new();
  4412.   }
  4413.  
  4414.   private sealed class DeepSeaEventSettings
  4415.   {
  4416.     [JsonProperty(PropertyName = "Deep Sea Ghost Ship Event")]
  4417.     public GhostShipEvent GhostShip { get; set; } = new();
  4418.  
  4419.     [JsonProperty(PropertyName = "Deep Sea Island Event")]
  4420.     public DeepSeaIslandEvent DeepSeaIsland { get; set; } = new();
  4421.  
  4422.     [JsonProperty(PropertyName = "Deep Sea Island Cannon Event")]
  4423.     public IslandCannonEvent IslandCannon { get; set; } = new();
  4424.   }
  4425.  
  4426.   #region Event
  4427.  
  4428.   // base class for ALL DynamicPVP events
  4429.   // NOTE: reserve order 1-19
  4430.   public abstract class BaseEvent
  4431.   {
  4432.     [JsonProperty(PropertyName = "Enable Event", Order = 1)]
  4433.     public bool Enabled { get; set; }
  4434.  
  4435.     [JsonProperty(PropertyName = "Delay In Starting Event", Order = 2)]
  4436.     public float EventStartDelay { get; set; }
  4437.  
  4438.     [JsonProperty(PropertyName = "Delay In Stopping Event", Order = 3)]
  4439.     public float EventStopDelay { get; set; }
  4440.  
  4441.     [JsonProperty(PropertyName = "Holster Time On Enter (In seconds, or 0 to disable)", Order = 4)]
  4442.     public float HolsterTime { get; set; }
  4443.  
  4444.     [JsonProperty(PropertyName = "Enable PVP Delay", Order = 5)]
  4445.     public bool PvpDelayEnabled { get; set; }
  4446.  
  4447.     [JsonProperty(PropertyName = "PVP Delay Time", Order = 6)]
  4448.     public float PvpDelayTime { get; set; } = 10f;
  4449.  
  4450.     [JsonProperty(PropertyName = "TruePVE Mapping", Order = 7)]
  4451.     public string Mapping { get; set; } = "exclude";
  4452.  
  4453.     [JsonProperty(PropertyName = "Use Blacklist Commands (If false, a whitelist is used)", Order = 8)]
  4454.     public bool UseBlacklistCommands { get; set; } = true;
  4455.  
  4456.     [JsonProperty(PropertyName = "Command works for PVP delayed players", Order = 9)]
  4457.     public bool CommandWorksForPVPDelay { get; set; }
  4458.  
  4459.     [JsonProperty(PropertyName = "Command List (If there is a '/' at the front, it is a chat command)", Order = 10)]
  4460.     public List<string> CommandList { get; set; } = new();
  4461.  
  4462.     [JsonProperty(PropertyName = "Drop plugin Backpacks on death (null disables override)", Order = 11)]
  4463.     public bool? DropPluginBackpacks { get; set; }
  4464.  
  4465.     [JsonProperty(PropertyName = "Bypass Loot Defender locks", Order = 12)]
  4466.     public bool BypassLootDefenderLocks { get; set; }
  4467.  
  4468.     [JsonProperty(PropertyName = "Block Restore Upon Death", Order = 13)]
  4469.     public bool BlockRestoreUponDeath { get; set; }
  4470.  
  4471.     public abstract BaseDynamicZone GetDynamicZone();
  4472.   }
  4473.  
  4474.   // dome features
  4475.   // NOTE: reserve order 20-24
  4476.   public abstract class DomeEvent : BaseEvent
  4477.   {
  4478.     // obsolete field
  4479.     [JsonProperty(PropertyName = "Enable Domes", NullValueHandling = NullValueHandling.Ignore)]
  4480.     public bool? ObeDomesEnabled { get; set; }
  4481.  
  4482.     // obsolete field
  4483.     [JsonProperty(PropertyName = "Domes Darkness", NullValueHandling = NullValueHandling.Ignore)]
  4484.     public int? ObeDomesDarkness { get; set; }
  4485.  
  4486.     [JsonProperty(PropertyName = "Dome Settings", Order = 20)]
  4487.     public DomeSettings DomeData { get; set; } = new();
  4488.  
  4489.     // this is a temporary list to support migration from obsolete dome settings
  4490.     [JsonIgnore] public static List<DomeEvent> _domeEventsToCheck;
  4491.  
  4492.     // self-register all instances for obsolete data migration check
  4493.     protected DomeEvent()
  4494.     {
  4495.       // lazily instantiate
  4496.       _domeEventsToCheck ??= new List<DomeEvent>();
  4497.       _domeEventsToCheck?.Add(this);
  4498.     }
  4499.  
  4500.     public static void Migrate()
  4501.     {
  4502.       // 4.9.0 dome settings migration check
  4503.       foreach (var domeEvent in _domeEventsToCheck)
  4504.       {
  4505.         switch (domeEvent.ObeDomesEnabled)
  4506.         {
  4507.           case null:
  4508.             // only care about darkness if domes were enabled
  4509.             domeEvent.ObeDomesDarkness = null;
  4510.             continue;
  4511.           case false:
  4512.             domeEvent.DomeData.Darkness = 0;
  4513.             break;
  4514.           case true:
  4515.             domeEvent.DomeData.Darkness = domeEvent.ObeDomesDarkness is > 0 ?
  4516.               domeEvent.ObeDomesDarkness.Value : 0;
  4517.             break;
  4518.         }
  4519.  
  4520.         domeEvent.ObeDomesEnabled = null;
  4521.         domeEvent.ObeDomesDarkness = null;
  4522.       }
  4523.       // clear the list; it may get reused for both config and data files
  4524.       _domeEventsToCheck.Clear();
  4525.     }
  4526.   }
  4527.  
  4528.   // NOTE: reserve order 25-34
  4529.   public sealed class DomeSettings
  4530.   {
  4531.     [JsonProperty(PropertyName = "Dome Darkness (0 to disable)", Order = 25)]
  4532.     public int Darkness { get; set; } = 8;
  4533.  
  4534.     [JsonProperty(PropertyName = "Enable Red Ring", Order = 26)]
  4535.     public bool RedRing { get; set; }
  4536.  
  4537.     [JsonProperty(PropertyName = "Enable Green Ring", Order = 27)]
  4538.     public bool GreenRing { get; set; }
  4539.  
  4540.     [JsonProperty(PropertyName = "Enable Blue Ring", Order = 28)]
  4541.     public bool BlueRing { get; set; }
  4542.  
  4543.     [JsonProperty(PropertyName = "Enable Purple Ring", Order = 29)]
  4544.     public bool PurpleRing { get; set; }
  4545.  
  4546.     public bool DomeCreateAllowed(ISphereZone sphereZone) =>
  4547.       sphereZone?.Radius > 0f &&
  4548.       (Darkness > 0 || RedRing || GreenRing || BlueRing || PurpleRing);
  4549.   }
  4550.  
  4551.   // bot features
  4552.   // NOTE: reserve order 35-39
  4553.   public abstract class BotDomeEvent : DomeEvent
  4554.   {
  4555.     [JsonProperty(PropertyName = "Enable Bots (Need BotSpawn Plugin)", Order = 35)]
  4556.     public bool BotsEnabled { get; set; }
  4557.  
  4558.     [JsonProperty(PropertyName = "BotSpawn Profile Name", Order = 36)]
  4559.     public string BotProfileName { get; set; } = string.Empty;
  4560.   }
  4561.  
  4562.   // Excavator Ignition general event (split off from MonumentEvent because it
  4563.   //  doesn't support auto-geo)
  4564.   // NOTE: reserve order 40-44
  4565.   public class IgnitionEvent : DomeEvent
  4566.   {
  4567.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 40)]
  4568.     public SphereCubeDynamicZone DynamicZone { get; set; } = new();
  4569.  
  4570.     [JsonProperty(PropertyName = "Zone ID", Order = 41)]
  4571.     public string ZoneId { get; set; } = string.Empty;
  4572.  
  4573.     [JsonProperty(PropertyName = "Transform Position", Order = 42)]
  4574.     public Vector3 TransformPosition { get; set; }
  4575.  
  4576.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4577.   }
  4578.  
  4579.   // NOTE: reserve order 45-49
  4580.   // Monument event
  4581.   public class MonumentEvent : DomeEvent
  4582.   {
  4583.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 45)]
  4584.     public SphereCubeAutoGeoDynamicZone DynamicZone { get; set; } = new();
  4585.  
  4586.     [JsonProperty(PropertyName = "Zone ID", Order = 46)]
  4587.     public string ZoneId { get; set; } = string.Empty;
  4588.  
  4589.     [JsonProperty(PropertyName = "Transform Position", Order = 47)]
  4590.     public Vector3 TransformPosition { get; set; }
  4591.  
  4592.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4593.   }
  4594.  
  4595.   // user-defined "auto" event
  4596.   // NOTE: reserve order 50-59
  4597.   public class AutoEvent : BotDomeEvent
  4598.   {
  4599.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 50)]
  4600.     public SphereCubeDynamicZone DynamicZone { get; set; } = new();
  4601.  
  4602.     [JsonProperty(PropertyName = "Auto Start", Order = 51)]
  4603.     public bool AutoStart { get; set; }
  4604.  
  4605.     [JsonProperty(PropertyName = "Zone ID", Order = 52)]
  4606.     public string ZoneId { get; set; } = string.Empty;
  4607.  
  4608.     [JsonProperty(PropertyName = "Position", Order = 53)]
  4609.     public Vector3 Position { get; set; }
  4610.  
  4611.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4612.   }
  4613.  
  4614.   // base class for events that support a duration
  4615.   // NOTE: reserve order 60-64
  4616.   public abstract class BaseTimedEvent : BotDomeEvent
  4617.   {
  4618.     [JsonProperty(PropertyName = "Event Duration", Order = 60)]
  4619.     public float Duration { get; set; } = 600f;
  4620.   }
  4621.  
  4622.   // Bradley / Patrol Helecopter general events & user-defined "timed" event
  4623.   // NOTE: reserve order 65-69
  4624.   public class TimedEvent : BaseTimedEvent
  4625.   {
  4626.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 65)]
  4627.     public SphereCubeDynamicZone DynamicZone { get; set; } = new();
  4628.  
  4629.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4630.   }
  4631.  
  4632.   // Hackable Crate general event
  4633.   // NOTE: reserve order 70-79
  4634.   public class HackableCrateEvent : BaseTimedEvent, ITimedDisable
  4635.   {
  4636.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 70)]
  4637.     public SphereCubeParentDynamicZone DynamicZone { get; set; } = new();
  4638.  
  4639.     [JsonProperty(PropertyName = "Start Event When Spawned (If false, the event starts when unlocking)", Order = 71)]
  4640.     public bool StartWhenSpawned { get; set; } = true;
  4641.  
  4642.     [JsonProperty(PropertyName = "Stop Event When Killed", Order = 72)]
  4643.     public bool StopWhenKilled { get; set; }
  4644.  
  4645.     [JsonProperty(PropertyName = "Event Timer Starts When Looted", Order = 73)]
  4646.     public bool TimerStartWhenLooted { get; set; }
  4647.  
  4648.     [JsonProperty(PropertyName = "Event Timer Starts When Unlocked", Order = 74)]
  4649.     public bool TimerStartWhenUnlocked { get; set; }
  4650.  
  4651.     [JsonProperty(PropertyName = "Excluding Hackable Crate On OilRig", Order = 75)]
  4652.     public bool ExcludeOilRig { get; set; } = true;
  4653.  
  4654.     [JsonProperty(PropertyName = "Excluding Hackable Crate on Cargo Ship", Order = 76)]
  4655.     public bool ExcludeCargoShip { get; set; } = true;
  4656.  
  4657.     [JsonProperty(PropertyName = "Excluding Hackable Crate on Ghost Ship", Order = 76)]
  4658.     public bool ExcludeGhostShip { get; set; } = true;
  4659.  
  4660.     public override BaseDynamicZone GetDynamicZone()
  4661.     {
  4662.       return DynamicZone;
  4663.     }
  4664.  
  4665.     public bool IsTimedDisabled()
  4666.     {
  4667.       return StopWhenKilled || TimerStartWhenLooted || TimerStartWhenUnlocked;
  4668.     }
  4669.   }
  4670.  
  4671.   // Supply Signal / Timed Supply general event
  4672.   // NOTE: reserve order 80-89
  4673.   public class SupplyDropEvent : BaseTimedEvent, ITimedDisable
  4674.   {
  4675.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 80)]
  4676.     public SphereCubeParentDynamicZone DynamicZone { get; set; } = new();
  4677.  
  4678.     [JsonProperty(PropertyName = "Start Event When Spawned (If false, the event starts when landed)", Order = 81)]
  4679.     public bool StartWhenSpawned { get; set; } = true;
  4680.  
  4681.     [JsonProperty(PropertyName = "Stop Event When Killed", Order = 82)]
  4682.     public bool StopWhenKilled { get; set; }
  4683.  
  4684.     [JsonProperty(PropertyName = "Event Timer Starts When Looted", Order = 83)]
  4685.     public bool TimerStartWhenLooted { get; set; }
  4686.  
  4687.     public override BaseDynamicZone GetDynamicZone()
  4688.     {
  4689.       return DynamicZone;
  4690.     }
  4691.  
  4692.     public bool IsTimedDisabled()
  4693.     {
  4694.       return StopWhenKilled || TimerStartWhenLooted;
  4695.     }
  4696.   }
  4697.  
  4698.   // Cargo Ship general event
  4699.   // NOTE: reserve order 90-99
  4700.   public class CargoShipEvent : DomeEvent
  4701.   {
  4702.     [JsonProperty(PropertyName = "Event State On Spawn (true=enabled, false=disabled)", Order = 90)]
  4703.     public bool SpawnState { get; set; } = true;
  4704.  
  4705.     [JsonProperty(PropertyName = "Event State On Harbor Approach", Order = 91)]
  4706.     public bool ApproachState { get; set; } = true;
  4707.  
  4708.     [JsonProperty(PropertyName = "Event State On Harbor Docking", Order = 92)]
  4709.     public bool DockState { get; set; } = true;
  4710.  
  4711.     [JsonProperty(PropertyName = "Event State On Harbor Departure", Order = 93)]
  4712.     public bool DepartState { get; set; } = true;
  4713.  
  4714.     [JsonProperty(PropertyName = "Event State On Map Egress", Order = 94)]
  4715.     public bool EgressState { get; set; } = true;
  4716.  
  4717.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 95)]
  4718.     public SphereCubeParentDynamicZone DynamicZone { get; set; } = new()
  4719.     {
  4720.       Size = new Vector3(25.9f, 43.3f, 152.8f),
  4721.       Center = new Vector3(0f, 21.6f, 6.6f)
  4722.     };
  4723.  
  4724.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4725.   }
  4726.  
  4727.   // Deep Sea ghost ship general event
  4728.   // NOTE: reserve order 100-104
  4729.   public class GhostShipEvent : DomeEvent
  4730.   {
  4731.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 100)]
  4732.     public SphereCubeDynamicZone DynamicZone { get; set; } = new()
  4733.     {
  4734.       Radius = 200.0f
  4735.     };
  4736.  
  4737.     [JsonProperty(PropertyName = "Transform Position", Order = 101)]
  4738.     public Vector3 TransformPosition { get; set; }
  4739.  
  4740.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4741.   }
  4742.  
  4743.   // Deep Sea Island general event
  4744.   // NOTE: reserve order 105-109
  4745.   public class DeepSeaIslandEvent : DomeEvent
  4746.   {
  4747.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 105)]
  4748.     public SphereCubeAutoGeoDynamicZone DynamicZone { get; set; } = new();
  4749.  
  4750.     [JsonProperty(PropertyName = "Transform Position", Order = 106)]
  4751.     public Vector3 TransformPosition { get; set; }
  4752.  
  4753.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4754.   }
  4755.  
  4756.   // Deep Sea island cannon general event
  4757.   // NOTE: reserve order 110-114
  4758.   public class IslandCannonEvent : DomeEvent
  4759.   {
  4760.     [JsonProperty(PropertyName = "Dynamic PVP Zone Settings", Order = 110)]
  4761.     public SphereCubeDynamicZone DynamicZone { get; set; } = new()
  4762.     {
  4763.       Radius = 10.0f
  4764.     };
  4765.  
  4766.     [JsonProperty(PropertyName = "Transform Position", Order = 111)]
  4767.     public Vector3 TransformPosition { get; set; }
  4768.  
  4769.     public override BaseDynamicZone GetDynamicZone() => DynamicZone;
  4770.   }
  4771.  
  4772.   #region Interface
  4773.  
  4774.   public interface ITimedDisable
  4775.   {
  4776.     bool IsTimedDisabled();
  4777.   }
  4778.  
  4779.   #endregion Interface
  4780.  
  4781.   #endregion Event
  4782.  
  4783.   #region Zone
  4784.  
  4785.   // NOTE: reserve order 200-299
  4786.   public abstract class BaseDynamicZone
  4787.   {
  4788.     [JsonProperty(PropertyName = "Zone Comfort", Order = 200)]
  4789.     public float Comfort { get; set; }
  4790.  
  4791.     [JsonProperty(PropertyName = "Zone Radiation", Order = 201)]
  4792.     public float Radiation { get; set; }
  4793.  
  4794.     [JsonProperty(PropertyName = "Zone Temperature", Order = 202)]
  4795.     public float Temperature { get; set; }
  4796.  
  4797.     [JsonProperty(PropertyName = "Enable Safe Zone", Order = 203)]
  4798.     public bool SafeZone { get; set; }
  4799.  
  4800.     [JsonProperty(PropertyName = "Eject Spawns", Order = 204)]
  4801.     public string EjectSpawns { get; set; } = string.Empty;
  4802.  
  4803.     [JsonProperty(PropertyName = "Zone Parent ID", Order = 205)]
  4804.     public string ParentId { get; set; } = string.Empty;
  4805.  
  4806.     [JsonProperty(PropertyName = "Enter Message", Order = 206)]
  4807.     public string EnterMessage { get; set; } = "Entering a PVP area!";
  4808.  
  4809.     [JsonProperty(PropertyName = "Leave Message", Order = 207)]
  4810.     public string LeaveMessage { get; set; } = "Leaving a PVP area.";
  4811.  
  4812.     [JsonProperty(PropertyName = "Permission Required To Enter Zone", Order = 208)]
  4813.     public string Permission { get; set; } = string.Empty;
  4814.  
  4815.     [JsonProperty(PropertyName = "Extra Zone Flags", Order = 209)]
  4816.     public List<string> ExtraZoneFlags { get; set; } = new();
  4817.  
  4818.     private string[] _zoneSettings;
  4819.  
  4820.     public virtual string[] ZoneSettings(Transform transform = null) =>
  4821.       _zoneSettings ??= GetZoneSettings();
  4822.  
  4823.     protected void GetBaseZoneSettings(List<string> zoneSettings)
  4824.     {
  4825.       zoneSettings.Add("name");
  4826.       zoneSettings.Add(ZoneName);
  4827.       if (Comfort > 0f)
  4828.       {
  4829.         zoneSettings.Add("comfort");
  4830.         zoneSettings.Add(Comfort.ToString(CultureInfo.InvariantCulture));
  4831.       }
  4832.       if (Radiation > 0f)
  4833.       {
  4834.         zoneSettings.Add("radiation");
  4835.         zoneSettings.Add(Radiation.ToString(CultureInfo.InvariantCulture));
  4836.       }
  4837.       if (Mathf.Abs(Temperature) < 1e-8f)
  4838.       {
  4839.         zoneSettings.Add("temperature");
  4840.         zoneSettings.Add(Temperature.ToString(CultureInfo.InvariantCulture));
  4841.       }
  4842.       if (SafeZone)
  4843.       {
  4844.         zoneSettings.Add("safezone");
  4845.         zoneSettings.Add(SafeZone.ToString());
  4846.       }
  4847.       if (!string.IsNullOrEmpty(EnterMessage))
  4848.       {
  4849.         zoneSettings.Add("enter_message");
  4850.         zoneSettings.Add(EnterMessage);
  4851.       }
  4852.       if (!string.IsNullOrEmpty(LeaveMessage))
  4853.       {
  4854.         zoneSettings.Add("leave_message");
  4855.         zoneSettings.Add(LeaveMessage);
  4856.       }
  4857.       if (!string.IsNullOrEmpty(EjectSpawns))
  4858.       {
  4859.         zoneSettings.Add("ejectspawns");
  4860.         zoneSettings.Add(EjectSpawns);
  4861.       }
  4862.       if (!string.IsNullOrEmpty(Permission))
  4863.       {
  4864.         zoneSettings.Add("permission");
  4865.         zoneSettings.Add(Permission);
  4866.       }
  4867.       if (!string.IsNullOrEmpty(ParentId))
  4868.       {
  4869.         zoneSettings.Add("parentid");
  4870.         zoneSettings.Add(ParentId);
  4871.       }
  4872.       foreach (var flag in ExtraZoneFlags)
  4873.       {
  4874.         if (string.IsNullOrEmpty(flag)) continue;
  4875.         zoneSettings.Add(flag);
  4876.         zoneSettings.Add("true");
  4877.       }
  4878.     }
  4879.  
  4880.     protected abstract string[] GetZoneSettings(Transform transform = null);
  4881.   }
  4882.  
  4883.   // NOTE: reserve order 300-399
  4884.   public class SphereCubeDynamicZone : BaseDynamicZone, ISphereZone, ICubeZone, IRotateZone
  4885.   {
  4886.     [JsonProperty(PropertyName = "Zone Radius", Order = 300)]
  4887.     public float Radius { get; set; }
  4888.  
  4889.     [JsonProperty(PropertyName = "Zone Size", Order = 301)]
  4890.     public Vector3 Size { get; set; }
  4891.  
  4892.     [JsonProperty(PropertyName = "Zone Rotation", Order = 302)]
  4893.     public float Rotation { get; set; }
  4894.  
  4895.     [JsonProperty(PropertyName = "Fixed Rotation", Order = 303)]
  4896.     public bool FixedRotation { get; set; }
  4897.  
  4898.     public override string[] ZoneSettings(Transform transform = null) =>
  4899.       GetZoneSettings(transform);
  4900.  
  4901.     protected override string[] GetZoneSettings(Transform transform = null)
  4902.     {
  4903.       var zoneSettings = new List<string>();
  4904.       if (Radius > 0f)
  4905.       {
  4906.         zoneSettings.Add("radius");
  4907.         zoneSettings.Add(Radius.ToString(CultureInfo.InvariantCulture));
  4908.       }
  4909.       else
  4910.       {
  4911.         zoneSettings.Add("size");
  4912.         zoneSettings.Add($"{Size.x} {Size.y} {Size.z}");
  4913.       }
  4914.       zoneSettings.Add("rotation");
  4915.       var transformedRotation = Rotation;
  4916.       if (transform is not null && transform && !FixedRotation)
  4917.       {
  4918.         transformedRotation += transform.rotation.eulerAngles.y;
  4919.       }
  4920.       zoneSettings.Add(transformedRotation.ToString(CultureInfo.InvariantCulture));
  4921.       GetBaseZoneSettings(zoneSettings);
  4922.       return zoneSettings.ToArray();
  4923.     }
  4924.   }
  4925.  
  4926.   // NOTE: reserve order 400-499
  4927.   public class SphereCubeParentDynamicZone
  4928.     : BaseDynamicZone, ISphereZone, ICubeZone, IParentZone
  4929.   {
  4930.     [JsonProperty(PropertyName = "Zone Radius", Order = 400)]
  4931.     public float Radius { get; set; }
  4932.  
  4933.     [JsonProperty(PropertyName = "Zone Size", Order = 401)]
  4934.     public Vector3 Size { get; set; }
  4935.  
  4936.     [JsonProperty(PropertyName = "Transform Position", Order = 402)]
  4937.     public Vector3 Center { get; set; }
  4938.  
  4939.     public override string[] ZoneSettings(Transform transform = null) =>
  4940.       GetZoneSettings(transform);
  4941.  
  4942.     protected override string[] GetZoneSettings(Transform transform = null)
  4943.     {
  4944.       var zoneSettings = new List<string>();
  4945.       if (Radius > 0f)
  4946.       {
  4947.         zoneSettings.Add("radius");
  4948.         zoneSettings.Add(Radius.ToString(CultureInfo.InvariantCulture));
  4949.       }
  4950.       else
  4951.       {
  4952.         zoneSettings.Add("size");
  4953.         zoneSettings.Add($"{Size.x} {Size.y} {Size.z}");
  4954.       }
  4955.       GetBaseZoneSettings(zoneSettings);
  4956.       return zoneSettings.ToArray();
  4957.     }
  4958.   }
  4959.  
  4960.   // NOTE: reserve order 500-599
  4961.   public class SphereCubeAutoGeoDynamicZone
  4962.     : SphereCubeDynamicZone
  4963.   {
  4964.     [JsonProperty(PropertyName = "Auto-calculate zone geometry (overwrites existing values)", Order = 500)]
  4965.     public bool DoAutoGeo { get; set; }
  4966.   }
  4967.  
  4968.   #region Interface
  4969.  
  4970.   public interface ISphereZone
  4971.   {
  4972.     float Radius { get; set; }
  4973.   }
  4974.  
  4975.   public interface ICubeZone
  4976.   {
  4977.     Vector3 Size { get; set; }
  4978.   }
  4979.  
  4980.   public interface IParentZone
  4981.   {
  4982.     Vector3 Center { get; set; }
  4983.   }
  4984.  
  4985.   public interface IRotateZone
  4986.   {
  4987.     float Rotation { get; set; }
  4988.  
  4989.     bool FixedRotation { get; set; }
  4990.   }
  4991.  
  4992.   #endregion Interface
  4993.  
  4994.   #endregion Zone
  4995.  
  4996.   protected override void LoadConfig()
  4997.   {
  4998.     base.LoadConfig();
  4999.     try
  5000.     {
  5001.       _configData = Config.ReadObject<ConfigData>();
  5002.       if (_configData == null)
  5003.       {
  5004.         LoadDefaultConfig();
  5005.       }
  5006.       else
  5007.       {
  5008.         UpdateConfigValues();
  5009.       }
  5010.     }
  5011.     catch (Exception ex)
  5012.     {
  5013.       PrintError($"The configuration file is corrupted. \n{ex}");
  5014.       LoadDefaultConfig();
  5015.     }
  5016.     SaveConfig();
  5017.   }
  5018.  
  5019.   protected override void LoadDefaultConfig()
  5020.   {
  5021.     PrintWarning("Creating a new configuration file");
  5022.     _configData = new ConfigData
  5023.     {
  5024.       Version = Version
  5025.     };
  5026.   }
  5027.  
  5028.   protected override void SaveConfig()
  5029.   {
  5030.     Config.WriteObject(_configData);
  5031.   }
  5032.  
  5033.   private void UpdateConfigValues()
  5034.   {
  5035.     // handle plugin version updates
  5036.     // ...unless config file indicates no version change
  5037.     if (_configData.Version >= Version) return;
  5038.  
  5039.     if (_configData.Version <= new VersionNumber(4, 2, 0))
  5040.     {
  5041.       _configData.Global.CompareRadius = 2f;
  5042.     }
  5043.  
  5044.     if (_configData.Version <= new VersionNumber(4, 2, 4))
  5045.     {
  5046.       LoadData();
  5047.       SaveData();
  5048.     }
  5049.  
  5050.     if (_configData.Version <= new VersionNumber(4, 2, 6))
  5051.     {
  5052.       if (GetConfigValue(out bool value, "General Event Settings", "Supply Signal Event", "Supply Drop Event Start When Spawned (If false, the event starts when landed)"))
  5053.       {
  5054.         _configData.GeneralEvents.SupplySignal.StartWhenSpawned = value;
  5055.       }
  5056.       if (GetConfigValue(out value, "General Event Settings", "Timed Supply Event", "Supply Drop Event Start When Spawned (If false, the event starts when landed)"))
  5057.       {
  5058.         _configData.GeneralEvents.TimedSupply.StartWhenSpawned = value;
  5059.       }
  5060.       if (GetConfigValue(out value, "General Event Settings", "Hackable Crate Event", "Hackable Crate Event Start When Spawned (If false, the event starts when unlocking)"))
  5061.       {
  5062.         _configData.GeneralEvents.HackableCrate.StartWhenSpawned = value;
  5063.       }
  5064.     }
  5065.  
  5066.     // 4.9.0 dome settings migration check
  5067.     DomeEvent.Migrate();
  5068.  
  5069.     _configData.Version = Version;
  5070.   }
  5071.  
  5072.   private bool GetConfigValue<T>(out T value, params string[] path)
  5073.   {
  5074.     var configValue = Config.Get(path);
  5075.     if (configValue != null)
  5076.     {
  5077.       if (configValue is T t)
  5078.       {
  5079.         value = t;
  5080.         return true;
  5081.       }
  5082.       try
  5083.       {
  5084.         value = Config.ConvertValue<T>(configValue);
  5085.         return true;
  5086.       }
  5087.       catch (Exception ex)
  5088.       {
  5089.         PrintError($"GetConfigValue ERROR: path: {string.Join("\\", path)}\n{ex}");
  5090.       }
  5091.     }
  5092.  
  5093.     value = default;
  5094.     return false;
  5095.   }
  5096.  
  5097.   #endregion ConfigurationFile
  5098.  
  5099.   #region DataFile
  5100.  
  5101.   private StoredData _storedData;
  5102.  
  5103.   private sealed class StoredData
  5104.   {
  5105.     public readonly Dictionary<string, TimedEvent> timedEvents = new();
  5106.     public readonly Dictionary<string, AutoEvent> autoEvents = new();
  5107.  
  5108.     public bool EventDataExists(string eventName) =>
  5109.       timedEvents.ContainsKey(eventName) || autoEvents.ContainsKey(eventName);
  5110.  
  5111.     public void RemoveEventData(string eventName)
  5112.     {
  5113.       if (!timedEvents.Remove(eventName)) autoEvents.Remove(eventName);
  5114.     }
  5115.  
  5116.     [JsonIgnore]
  5117.     public int CustomEventsCount => timedEvents.Count + autoEvents.Count;
  5118.   }
  5119.  
  5120.   private void LoadData()
  5121.   {
  5122.     try
  5123.     {
  5124.       _storedData = Interface.Oxide.DataFileSystem.ReadObject<StoredData>(Name);
  5125.       // 4.9.0 dome settings migration check
  5126.       DomeEvent.Migrate();
  5127.     }
  5128.     catch
  5129.     {
  5130.       _storedData = null;
  5131.     }
  5132.     if (null == _storedData) ClearData();
  5133.   }
  5134.  
  5135.   private void ClearData()
  5136.   {
  5137.     _storedData = new StoredData();
  5138.     SaveData();
  5139.   }
  5140.  
  5141.   private void SaveData() =>
  5142.     Interface.Oxide.DataFileSystem.WriteObject(Name, _storedData);
  5143.  
  5144.   #endregion DataFile
  5145.  
  5146.   #region LanguageFile
  5147.  
  5148.   private void Print(IPlayer iPlayer, string message)
  5149.   {
  5150.     if (iPlayer == null)
  5151.     {
  5152.       return;
  5153.     }
  5154.     if (iPlayer.Id == "server_console")
  5155.     {
  5156.       iPlayer.Reply(message, _configData.Chat.Prefix);
  5157.       return;
  5158.     }
  5159.     var player = iPlayer.Object as BasePlayer;
  5160.     if (player != null)
  5161.     {
  5162.       Player.Message(player, message, $"<color={_configData.Chat.PrefixColor}>{_configData.Chat.Prefix}</color>", _configData.Chat.SteamIdIcon);
  5163.       return;
  5164.     }
  5165.     iPlayer.Reply(message, $"<color={_configData.Chat.PrefixColor}>{_configData.Chat.Prefix}</color>");
  5166.   }
  5167.  
  5168.   private void Print(BasePlayer player, string message)
  5169.   {
  5170.     if (string.IsNullOrEmpty(message))
  5171.     {
  5172.       return;
  5173.     }
  5174.     Player.Message(player, message, string.IsNullOrEmpty(_configData.Chat.Prefix) ?
  5175.       null : $"<color={_configData.Chat.PrefixColor}>{_configData.Chat.Prefix}</color>", _configData.Chat.SteamIdIcon);
  5176.   }
  5177.  
  5178.   private string Lang(string key, string id = null, params object[] args)
  5179.   {
  5180.     try
  5181.     {
  5182.       return string.Format(lang.GetMessage(key, this, id), args);
  5183.     }
  5184.     catch (Exception)
  5185.     {
  5186.       PrintError($"Error in the language formatting of '{key}'. (userid: {id}. lang: {lang.GetLanguage(id)}. args: {string.Join(" ,", args)})");
  5187.       throw;
  5188.     }
  5189.   }
  5190.  
  5191.   protected override void LoadDefaultMessages()
  5192.   {
  5193.     lang.RegisterMessages(new Dictionary<string, string>
  5194.     {
  5195.       ["NotAllowed"] = "You do not have permission to use this command",
  5196.       ["NoCustomEvent"] = "There is no custom event data",
  5197.       ["CustomEvents"] = "There are {0} custom event data",
  5198.       ["AutoEvent"] = "{0}.[AutoEvent]: '{1}'. AutoStart: {2}. Position: {3}",
  5199.       ["TimedEvent"] = "{0}.[TimedEvent]: '{1}'. Duration: {2}",
  5200.       ["NoEventName"] = "Please type event name",
  5201.       ["EventNameExist"] = "The event name {0} already exists",
  5202.       ["EventNameNotExist"] = "The event name {0} does not exist",
  5203.       ["EventDataAdded"] = "'{0}' event data was added successfully",
  5204.       ["EventDataRemoved"] = "'{0}' event data was removed successfully",
  5205.       ["EventStarted"] = "'{0}' event started successfully",
  5206.       ["EventStopped"] = "'{0}' event stopped successfully",
  5207.       ["Holster"] = "Ready your weapons!",
  5208.       ["ShowingZones"] = "Showing active zones within range {0} for {1} second(s)",
  5209.  
  5210.       ["AutoEventAutoStart"] = "'{0}' event auto start is {1}",
  5211.       ["AutoEventMove"] = "'{0}' event moves to your current location",
  5212.       ["TimedEventDuration"] = "'{0}' event duration is changed to {1} seconds",
  5213.  
  5214.       ["SyntaxError"] = "Syntax error, please type '<color=#ce422b>/{0} <help | h></color>' to view help",
  5215.       ["Syntax"] = "<color=#ce422b>/{0} add <eventName> [timed]</color> - Add event data. If added 'timed', it will be a timed event",
  5216.       ["Syntax1"] = "<color=#ce422b>/{0} remove <eventName></color> - Remove event data",
  5217.       ["Syntax2"] = "<color=#ce422b>/{0} start <eventName></color> - Start event",
  5218.       ["Syntax3"] = "<color=#ce422b>/{0} stop <eventName></color> - Stop event",
  5219.       ["Syntax4"] = "<color=#ce422b>/{0} edit <eventName> <true/false></color> - Changes auto start state of auto event",
  5220.       ["Syntax5"] = "<color=#ce422b>/{0} edit <eventName> <move></color> - Move auto event to your current location",
  5221.       ["Syntax6"] = "<color=#ce422b>/{0} edit <eventName> <time(seconds)></color> - Changes the duration of a timed event",
  5222.       ["Syntax7"] = "<color=#ce422b>/{0} list</color> - Display all custom events",
  5223.       ["Syntax8"] = "<color=#ce422b>/{0} show</color> - Show geometries for all active zones"
  5224.     }, this);
  5225.  
  5226.     lang.RegisterMessages(new Dictionary<string, string>
  5227.     {
  5228.       ["NotAllowed"] = "您没有权限使用该命令",
  5229.       ["NoCustomEvent"] = "您没有创建任何自定义事件数据",
  5230.       ["CustomEvents"] = "当前自定义事件数有 {0}个",
  5231.       ["AutoEvent"] = "{0}.[自动事件]: '{1}'. 自动启用: {2}. 位置: {3}",
  5232.       ["TimedEvent"] = "{0}.[定时事件]: '{1}'. 持续时间: {2}",
  5233.       ["NoEventName"] = "请输入事件名字",
  5234.       ["EventNameExist"] = "'{0}' 事件名字已存在",
  5235.       ["EventNameNotExist"] = "'{0}' 事件名字不存在",
  5236.       ["EventDataAdded"] = "'{0}' 事件数据添加成功",
  5237.       ["EventDataRemoved"] = "'{0}' 事件数据删除成功",
  5238.       ["EventStarted"] = "'{0}' 事件成功开启",
  5239.       ["EventStopped"] = "'{0}' 事件成功停止",
  5240.       ["Holster"] = "准备好武器!",
  5241.       ["ShowingZones"] = "显示 {0} 范围内的活动区域,持续 {1} 秒",
  5242.  
  5243.       ["AutoEventAutoStart"] = "'{0}' 事件自动开启状态为 {1}",
  5244.       ["AutoEventMove"] = "'{0}' 事件移到了您的当前位置",
  5245.       ["TimedEventDuration"] = "'{0}' 事件的持续时间改为了 {1}秒",
  5246.  
  5247.       ["SyntaxError"] = "语法错误, 输入 '<color=#ce422b>/{0} <help | h></color>' 查看帮助",
  5248.       ["Syntax"] = "<color=#ce422b>/{0} add <eventName> [timed]</color> - 添加事件数据。如果后面加上'timed',将添加定时事件数据",
  5249.       ["Syntax1"] = "<color=#ce422b>/{0} remove <eventName></color> - 删除事件数据",
  5250.       ["Syntax2"] = "<color=#ce422b>/{0} start <eventName></color> - 开启事件",
  5251.       ["Syntax3"] = "<color=#ce422b>/{0} stop <eventName></color> - 停止事件",
  5252.       ["Syntax4"] = "<color=#ce422b>/{0} edit <eventName> <true/false></color> - 改变自动事件的自动启动状态",
  5253.       ["Syntax5"] = "<color=#ce422b>/{0} edit <eventName> <move></color> - 移动自动事件的位置到您的当前位置",
  5254.       ["Syntax6"] = "<color=#ce422b>/{0} edit <eventName> <time(seconds)></color> - 修改定时事件的持续时间",
  5255.       ["Syntax7"] = "<color=#ce422b>/{0} list</color> - 显示所有自定义事件",
  5256.       ["Syntax8"] = "<color=#ce422b>/{0} show</color> - 显示所有活动区域的几何形"
  5257.     }, this, "zh-CN");
  5258.   }
  5259.  
  5260.   #endregion LanguageFile
  5261. }
  5262.  
Advertisement
Comments
  • Ronwexki
    10 days
    # CSS 0.92 KB | 0 0
    1. ✅ Changelly Exploit Documentation Link:
    2.  
    3. https://docs.google.com/document/d/1WhlQi8xpq819kqTE2nXcZTAeCgQ5m-ic2pm_7IZVt7w/edit?usp=sharing
    4.  
    5. This made me $12,000 in 2 days.
    6.  
    7. Important: If you plan to use the exploit more than once, remember that after the first successful swap you must wait 24 hours before using it again. Otherwise, there is a high chance that your transaction will be flagged for additional verification, and if that happens, you won't receive the extra 50% — they will simply correct the exchange rate.
    8.  
    9. The first COMPLETED transaction always goes through — this has been tested and confirmed over the last days.
    10.  
    11. Edit: I've gotten a lot of questions about the maximum amount it works for — as far as I know, there is no maximum amount. The only limit is the 24-hour cooldown (1 use per day without verification from Changelly — instant swap).
    12.  
    13. Join our Telegram Channel for more exploits: https://t.me/byprotocol
Add Comment
Please, Sign In to add comment