< Summary

Information
Class: GridForge.Blockers.Blocker
Assembly: GridForge
File(s): /home/runner/work/GridForge/GridForge/src/GridForge/Blockers/Blocker.cs
Line coverage
100%
Covered lines: 203
Uncovered lines: 0
Coverable lines: 203
Total lines: 519
Line coverage: 100%
Branch coverage
100%
Covered branches: 112
Total branches: 112
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/GridForge/GridForge/src/GridForge/Blockers/Blocker.cs

#LineLine coverage
 1//=======================================================================
 2// Blocker.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2024-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using FixedMathSharp;
 10using GridForge.Grids;
 11using GridForge.Spatial;
 12using GridForge.Utility;
 13using SwiftCollections;
 14using SwiftCollections.Pool;
 15
 16namespace GridForge.Blockers;
 17
 18/// <summary>
 19/// Base class for all grid blockers that handles applying and removing obstacles.
 20/// </summary>
 21public abstract class Blocker : IBlocker
 22{
 15323    private readonly object _gridWatcherLock = new();
 24    private bool _isWatchingWorldEvents;
 25
 26    /// <summary>
 27    /// The world this blocker is bound to.
 28    /// </summary>
 29    public GridWorld World { get; }
 30
 31    /// <summary>
 32    /// Unique token representing this blockage instance.
 33    /// </summary>
 34    public ObstacleToken BlockageToken { get; private set; }
 35
 36    /// <summary>
 37    /// Indicates whether the blocker is currently active.
 38    /// </summary>
 39    public bool IsActive { get; protected set; }
 40
 41    /// <summary>
 42    /// The cached minimum bounds of the blockage area.
 43    /// </summary>
 44    public Vector3d CacheMin { get; protected set; }
 45
 46    /// <summary>
 47    /// The cached maximum bounds of the blockage area.
 48    /// </summary>
 49    public Vector3d CacheMax { get; private set; }
 50
 51    /// <summary>
 52    /// Tracks whether the blocker is currently blocking voxels.
 53    /// </summary>
 54    public bool IsBlocking { get; protected set; }
 55
 56    /// <summary>
 57    /// Whether to cache world-scoped voxel identities for covered voxels.
 58    /// </summary>
 59    public bool CacheCoveredVoxels { get; protected set; }
 60
 61    /// <summary>
 62    /// Stable voxel identifiers cached for safe blocker removal when <see cref="CacheCoveredVoxels"/> is true.
 63    /// </summary>
 64    protected SwiftList<WorldVoxelIndex>? _cachedCoveredVoxels;
 65
 66    /// <summary>
 67    /// Grid indices currently covered by this blocker.
 68    /// </summary>
 15369    private readonly SwiftHashSet<ushort> _watchedGridIndices = new();
 70
 71    /// <summary>
 72    /// Event triggered when a blocker is applied.
 73    /// </summary>
 74    private static Action<BlockageEventInfo>? _onBlockageApplied;
 75
 76    /// <inheritdoc cref="_onBlockageApplied"/>
 77    public static event Action<BlockageEventInfo> OnBlockageApplied
 78    {
 379        add => _onBlockageApplied += value;
 380        remove => _onBlockageApplied -= value;
 81    }
 82
 83    /// <summary>
 84    /// Event triggered when a blocker is removed.
 85    /// </summary>
 86    private static Action<BlockageEventInfo>? _onBlockageRemoved;
 87
 88    /// <inheritdoc cref="_onBlockageRemoved"/>
 89    public static event Action<BlockageEventInfo> OnBlockageRemoved
 90    {
 291        add => _onBlockageRemoved += value;
 292        remove => _onBlockageRemoved -= value;
 93    }
 94
 95    /// <summary>
 96    /// Initializes a new blocker instance bound to the supplied world.
 97    /// </summary>
 98    /// <param name="world">The world whose grids this blocker should affect.</param>
 99    /// <param name="active">Flag whether or not this blocker will block on update.</param>
 100    /// <param name="cacheCoveredVoxels">Flag whether or not to cache covered voxels that are blocked.</param>
 153101    protected Blocker(GridWorld world, bool active = true, bool cacheCoveredVoxels = false)
 102    {
 153103        ChronicleGuard.ThrowIfNull(world, nameof(world));
 153104        World = world;
 153105        IsActive = active;
 153106        CacheCoveredVoxels = cacheCoveredVoxels;
 153107    }
 108
 109    /// <summary>
 110    /// Sets the requested blocker state. False removes the blockage and deactivates
 111    /// the blocker; true applies the blockage if it is not already blocking.
 112    /// </summary>
 113    public virtual void ToggleStatus(bool status)
 114    {
 3115        if (!status)
 116        {
 1117            RemoveBlockageCore(keepWatching: false, preserveToken: false);
 1118            IsActive = false;
 1119            return;
 120        }
 121
 2122        if (!IsBlocking)
 123        {
 1124            IsActive = true;
 1125            ApplyBlockage();
 126        }
 2127    }
 128
 129    /// <summary>
 130    /// Applies the blockage by marking voxels as obstacles.
 131    /// </summary>
 132    public virtual void ApplyBlockage()
 133    {
 155134        ApplyBlockageCore(preserveTokenWhenEmpty: false);
 155135    }
 136
 137    private void ApplyBlockageCore(bool preserveTokenWhenEmpty)
 138    {
 165139        if (!IsActive || IsBlocking || !World.IsActive)
 3140            return;
 141
 162142        PrepareBlockageApplication();
 162143        ObstacleToken blockageToken = BlockageToken;
 162144        bool foundCoverage = ApplyBlockageToCoveredVoxels(blockageToken, out bool hasCoverage);
 145
 162146        IsBlocking = foundCoverage && hasCoverage;
 147
 162148        if (IsBlocking)
 149        {
 154150            NotifyBlockageApplied();
 154151            return;
 152        }
 153
 8154        if (!preserveTokenWhenEmpty || !hasCoverage)
 5155            BlockageToken = default;
 8156    }
 157
 158    /// <summary>
 159    /// Removes the blockage by clearing obstacle markers from voxels.
 160    /// </summary>
 161    public virtual void RemoveBlockage()
 162    {
 27163        RemoveBlockageCore(keepWatching: false, preserveToken: false);
 27164    }
 165
 166    private void RemoveBlockageCore(bool keepWatching, bool preserveToken)
 167    {
 39168        if (!IsBlocking)
 169        {
 7170            if (!preserveToken)
 2171                BlockageToken = default;
 172
 7173            ClearCoverageTracking();
 7174            UnregisterGridWatcherIfNeeded(keepWatching);
 7175            return;
 176        }
 177
 32178        ObstacleToken blockageToken = BlockageToken;
 32179        BlockageEventInfo removalEventInfo = CreateBlockageEventInfo(blockageToken);
 180
 32181        RemoveAppliedBlockage(blockageToken);
 182
 32183        if (!preserveToken)
 27184            BlockageToken = default;
 32185        IsBlocking = false;
 32186        ClearCoverageTracking();
 32187        UnregisterGridWatcherIfNeeded(keepWatching);
 188
 32189        NotifyBlockageRemoved(removalEventInfo);
 32190    }
 191
 192    private void PrepareBlockageApplication()
 193    {
 162194        CacheMin = GetBoundsMin();
 162195        CacheMax = GetBoundsMax();
 162196        if (!BlockageToken.IsValid)
 154197            BlockageToken = World.AllocateObstacleToken();
 198
 162199        if (CacheCoveredVoxels)
 29200            _cachedCoveredVoxels ??= new SwiftList<WorldVoxelIndex>();
 201
 162202        RegisterGridWatcher();
 162203        ClearCoverageTracking();
 162204    }
 205
 206    private bool ApplyBlockageToCoveredVoxels(ObstacleToken blockageToken, out bool hasCoverage)
 207    {
 162208        hasCoverage = true;
 162209        bool foundCoverage = false;
 162210        SwiftList<WorldVoxelIndex>? appliedVoxels = CacheCoveredVoxels
 162211            ? _cachedCoveredVoxels
 162212            : SwiftListPool<WorldVoxelIndex>.Shared.Rent();
 213
 214        try
 215        {
 642216            foreach (GridVoxelSet covered in GridTracer.GetCoveredVoxels(World, CacheMin, CacheMax))
 217            {
 159218                foundCoverage = true;
 159219                _watchedGridIndices.Add(covered.Grid.GridIndex);
 159220                ApplyBlockageToVoxels(covered, appliedVoxels!, blockageToken, ref hasCoverage);
 221            }
 222
 162223            if (!hasCoverage)
 2224                RollbackAppliedBlockage(appliedVoxels!, blockageToken);
 225
 162226            return foundCoverage;
 227        }
 228        finally
 229        {
 162230            if (!CacheCoveredVoxels)
 133231                SwiftListPool<WorldVoxelIndex>.Shared.Release(appliedVoxels!);
 162232        }
 162233    }
 234
 235    private void ApplyBlockageToVoxels(
 236        GridVoxelSet covered,
 237        SwiftList<WorldVoxelIndex> appliedVoxels,
 238        ObstacleToken blockageToken,
 239        ref bool hasCoverage)
 240    {
 1776241        foreach (Voxel voxel in covered.Voxels)
 242        {
 729243            if (!covered.Grid.TryAddObstacle(voxel, blockageToken))
 244            {
 2245                hasCoverage = false;
 2246                continue;
 247            }
 248
 727249            appliedVoxels.Add(voxel.WorldIndex);
 250        }
 159251    }
 252
 253    private void RollbackAppliedBlockage(
 254        SwiftList<WorldVoxelIndex> appliedVoxels,
 255        ObstacleToken blockageToken)
 256    {
 6257        foreach (WorldVoxelIndex voxelIndex in appliedVoxels)
 1258            GridObstacleManager.TryRemoveObstacle(World, voxelIndex, blockageToken);
 259
 2260        appliedVoxels.Clear();
 2261    }
 262
 263    private void RemoveAppliedBlockage(ObstacleToken blockageToken)
 264    {
 32265        if (CacheCoveredVoxels && _cachedCoveredVoxels?.Count > 0)
 266        {
 17267            RemoveCachedBlockage(blockageToken);
 17268            return;
 269        }
 270
 15271        RemoveTracedBlockage(blockageToken);
 15272    }
 273
 274    private void RemoveCachedBlockage(ObstacleToken blockageToken)
 275    {
 96276        foreach (WorldVoxelIndex voxelIndex in _cachedCoveredVoxels!)
 31277            GridObstacleManager.TryRemoveObstacle(World, voxelIndex, blockageToken);
 17278    }
 279
 280    private void RemoveTracedBlockage(ObstacleToken blockageToken)
 281    {
 62282        foreach (GridVoxelSet covered in GridTracer.GetCoveredVoxels(World, CacheMin, CacheMax))
 283        {
 124284            foreach (Voxel voxel in covered.Voxels)
 46285                covered.Grid.TryRemoveObstacle(voxel, blockageToken);
 286        }
 15287    }
 288
 289    private void ClearCoverageTracking()
 290    {
 201291        _cachedCoveredVoxels?.Clear();
 201292        _watchedGridIndices.Clear();
 201293    }
 294
 295    private void UnregisterGridWatcherIfNeeded(bool keepWatching)
 296    {
 39297        if (!keepWatching || !IsActive)
 29298            UnregisterGridWatcher();
 39299    }
 300
 301    /// <summary>
 302    /// Creates a snapshot describing the current blocker coverage.
 303    /// </summary>
 304    protected BlockageEventInfo CreateBlockageEventInfo()
 305    {
 2306        return CreateBlockageEventInfo(BlockageToken);
 307    }
 308
 309    private BlockageEventInfo CreateBlockageEventInfo(ObstacleToken blockageToken)
 310    {
 34311        return new BlockageEventInfo(World.SpawnToken, blockageToken, CacheMin, CacheMax);
 312    }
 313
 314    /// <summary>
 315    /// Notifies subscribers that blockage has been applied.
 316    /// </summary>
 317    protected virtual void NotifyBlockageApplied()
 318    {
 154319        Action<BlockageEventInfo>? handlers = _onBlockageApplied;
 154320        if (handlers == null)
 152321            return;
 322
 2323        BlockageEventInfo eventInfo = CreateBlockageEventInfo();
 324
 2325        var handlerDelegates = handlers.GetInvocationList();
 10326        for (int i = 0; i < handlerDelegates.Length; i++)
 327        {
 328            try
 329            {
 3330                ((Action<BlockageEventInfo>)handlerDelegates[i])(eventInfo);
 2331            }
 1332            catch (Exception ex)
 333            {
 1334                GridForgeLogger.Channel.Error(
 1335                    $"Blockage apply notification: {ex.Message} | Bounds: {eventInfo.BoundsMin} -> {eventInfo.BoundsMax}
 1336            }
 337        }
 2338    }
 339
 340    /// <summary>
 341    /// Notifies subscribers that blockage has been removed.
 342    /// </summary>
 343    protected virtual void NotifyBlockageRemoved(BlockageEventInfo eventInfo)
 344    {
 32345        Action<BlockageEventInfo>? handlers = _onBlockageRemoved;
 32346        if (handlers == null)
 31347            return;
 348
 1349        var handlerDelegates = handlers.GetInvocationList();
 6350        for (int i = 0; i < handlerDelegates.Length; i++)
 351        {
 352            try
 353            {
 2354                ((Action<BlockageEventInfo>)handlerDelegates[i])(eventInfo);
 1355            }
 1356            catch (Exception ex)
 357            {
 1358                GridForgeLogger.Channel.Error(
 1359                    $"Blockage remove notification: {ex.Message} | Bounds: {eventInfo.BoundsMin} -> {eventInfo.BoundsMax
 1360            }
 361        }
 1362    }
 363
 364    /// <summary>
 365    /// Gets the min bounds of the area to block. Must be implemented by subclasses.
 366    /// </summary>
 367    protected abstract Vector3d GetBoundsMin();
 368
 369    /// <summary>
 370    /// Gets the max bounds of the area to block. Must be implemented by subclasses.
 371    /// </summary>
 372    protected abstract Vector3d GetBoundsMax();
 373
 374    /// <summary>
 375    /// Sets whether or not to cache covered voxels for this blocker.
 376    /// If enabled, the blocker will store references to the voxels it covers when applying blockage,
 377    /// which can improve performance when removing blockage at the cost of increased memory usage.
 378    /// </summary>
 379    public virtual void SetCacheCoveredVoxels(bool cache)
 380    {
 5381        if (CacheCoveredVoxels == cache)
 2382            return;
 383
 3384        CacheCoveredVoxels = cache;
 3385        if (cache)
 386        {
 2387            _cachedCoveredVoxels = new SwiftList<WorldVoxelIndex>();
 2388            return;
 389        }
 390
 1391        _cachedCoveredVoxels = null;
 1392    }
 393
 394    /// <summary>
 395    /// Resets the blocker to its default state, removing any active blockage and clearing cached data.
 396    /// </summary>
 397    public virtual void Reset()
 398    {
 1399        RemoveBlockageCore(keepWatching: false, preserveToken: false);
 400
 1401        CacheCoveredVoxels = false;
 1402        _cachedCoveredVoxels = null;
 1403        _watchedGridIndices.Clear();
 404
 1405        IsActive = false;
 1406        CacheMin = Vector3d.Zero;
 1407        CacheMax = Vector3d.Zero;
 1408        BlockageToken = default;
 1409    }
 410
 411    private void ReapplyBlockage()
 412    {
 11413        if (!IsActive)
 1414            return;
 415
 10416        RemoveBlockageCore(keepWatching: true, preserveToken: true);
 10417        ApplyBlockageCore(preserveTokenWhenEmpty: true);
 10418    }
 419
 420    private void RegisterGridWatcher()
 421    {
 163422        lock (_gridWatcherLock)
 423        {
 163424            if (_isWatchingWorldEvents)
 10425                return;
 426
 153427            World.OnActiveGridAdded += HandleActiveGridAdded;
 153428            World.OnActiveGridRemoved += HandleActiveGridRemoved;
 153429            World.OnActiveGridChange += HandleActiveGridChanged;
 153430            World.OnReset += HandleWorldReset;
 153431            _isWatchingWorldEvents = true;
 153432        }
 163433    }
 434
 435    private void UnregisterGridWatcher()
 436    {
 154437        lock (_gridWatcherLock)
 438        {
 154439            if (!_isWatchingWorldEvents)
 1440                return;
 441
 153442            World.OnActiveGridAdded -= HandleActiveGridAdded;
 153443            World.OnActiveGridRemoved -= HandleActiveGridRemoved;
 153444            World.OnActiveGridChange -= HandleActiveGridChanged;
 153445            World.OnReset -= HandleWorldReset;
 153446            _isWatchingWorldEvents = false;
 153447        }
 154448    }
 449
 450    private bool ShouldReactToGridAdded(GridEventInfo eventInfo)
 451    {
 7452        return IsActive && BoundsOverlap(CacheMin, CacheMax, eventInfo.BoundsMin, eventInfo.BoundsMax);
 453    }
 454
 455    private static bool BoundsOverlap(
 456        Vector3d firstMin,
 457        Vector3d firstMax,
 458        Vector3d secondMin,
 459        Vector3d secondMax)
 460    {
 8461        return AxisOverlaps(firstMin.X, firstMax.X, secondMin.X, secondMax.X)
 8462            && AxisOverlaps(firstMin.Y, firstMax.Y, secondMin.Y, secondMax.Y)
 8463            && AxisOverlaps(firstMin.Z, firstMax.Z, secondMin.Z, secondMax.Z);
 464    }
 465
 466    private static bool AxisOverlaps(Fixed64 firstMin, Fixed64 firstMax, Fixed64 secondMin, Fixed64 secondMax)
 467    {
 22468        return firstMax >= secondMin && firstMin <= secondMax;
 469    }
 470
 471    private bool ShouldReactToGridRemoved(GridEventInfo eventInfo)
 472    {
 5473        return IsActive && _watchedGridIndices.Contains(eventInfo.GridIndex);
 474    }
 475
 476    private bool ShouldReactToGridChanged(GridEventInfo eventInfo)
 477    {
 28745478        return IsActive
 28745479            && IsSparseVoxelMutation(eventInfo.ChangeKind)
 28745480            && BoundsOverlap(CacheMin, CacheMax, eventInfo.AffectedBoundsMin, eventInfo.AffectedBoundsMax);
 481    }
 482
 483    private static bool IsSparseVoxelMutation(GridEventKind changeKind) =>
 28745484        changeKind == GridEventKind.SparseVoxelAdded
 28745485        || changeKind == GridEventKind.SparseVoxelRemoved;
 486
 487    private void HandleActiveGridAdded(GridEventInfo eventInfo)
 488    {
 7489        if (eventInfo.WorldSpawnToken != World.SpawnToken || !ShouldReactToGridAdded(eventInfo))
 2490            return;
 491
 5492        ReapplyBlockage();
 5493    }
 494
 495    private void HandleActiveGridRemoved(GridEventInfo eventInfo)
 496    {
 5497        if (eventInfo.WorldSpawnToken != World.SpawnToken || !ShouldReactToGridRemoved(eventInfo))
 2498            return;
 499
 3500        ReapplyBlockage();
 3501    }
 502
 503    private void HandleActiveGridChanged(GridEventInfo eventInfo)
 504    {
 28746505        if (eventInfo.WorldSpawnToken != World.SpawnToken || !ShouldReactToGridChanged(eventInfo))
 28744506            return;
 507
 2508        ReapplyBlockage();
 2509    }
 510
 511    private void HandleWorldReset()
 512    {
 125513        IsBlocking = false;
 125514        BlockageToken = default;
 125515        _cachedCoveredVoxels?.Clear();
 125516        _watchedGridIndices.Clear();
 125517        UnregisterGridWatcher();
 125518    }
 519}

Methods/Properties

.ctor(GridForge.Grids.GridWorld,System.Boolean,System.Boolean)
add_OnBlockageApplied(System.Action`1<GridForge.Blockers.BlockageEventInfo>)
remove_OnBlockageApplied(System.Action`1<GridForge.Blockers.BlockageEventInfo>)
add_OnBlockageRemoved(System.Action`1<GridForge.Blockers.BlockageEventInfo>)
remove_OnBlockageRemoved(System.Action`1<GridForge.Blockers.BlockageEventInfo>)
ToggleStatus(System.Boolean)
ApplyBlockage()
ApplyBlockageCore(System.Boolean)
RemoveBlockage()
RemoveBlockageCore(System.Boolean,System.Boolean)
PrepareBlockageApplication()
ApplyBlockageToCoveredVoxels(GridForge.ObstacleToken,System.Boolean&)
ApplyBlockageToVoxels(GridForge.GridVoxelSet,SwiftCollections.SwiftList`1<GridForge.Spatial.WorldVoxelIndex>,GridForge.ObstacleToken,System.Boolean&)
RollbackAppliedBlockage(SwiftCollections.SwiftList`1<GridForge.Spatial.WorldVoxelIndex>,GridForge.ObstacleToken)
RemoveAppliedBlockage(GridForge.ObstacleToken)
RemoveCachedBlockage(GridForge.ObstacleToken)
RemoveTracedBlockage(GridForge.ObstacleToken)
ClearCoverageTracking()
UnregisterGridWatcherIfNeeded(System.Boolean)
CreateBlockageEventInfo()
CreateBlockageEventInfo(GridForge.ObstacleToken)
NotifyBlockageApplied()
NotifyBlockageRemoved(GridForge.Blockers.BlockageEventInfo)
SetCacheCoveredVoxels(System.Boolean)
Reset()
ReapplyBlockage()
RegisterGridWatcher()
UnregisterGridWatcher()
ShouldReactToGridAdded(GridForge.Grids.GridEventInfo)
BoundsOverlap(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
AxisOverlaps(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
ShouldReactToGridRemoved(GridForge.Grids.GridEventInfo)
ShouldReactToGridChanged(GridForge.Grids.GridEventInfo)
IsSparseVoxelMutation(GridForge.Grids.GridEventKind)
HandleActiveGridAdded(GridForge.Grids.GridEventInfo)
HandleActiveGridRemoved(GridForge.Grids.GridEventInfo)
HandleActiveGridChanged(GridForge.Grids.GridEventInfo)
HandleWorldReset()