< Summary

Information
Class: GridForge.Grids.ScanCell
Assembly: GridForge
File(s): /home/runner/work/GridForge/GridForge/src/GridForge/Grids/Nodes/ScanCell.cs
Line coverage
100%
Covered lines: 135
Uncovered lines: 0
Coverable lines: 135
Total lines: 435
Line coverage: 100%
Branch coverage
100%
Covered branches: 124
Total branches: 124
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_IsOccupied()100%22100%
Initialize(...)100%11100%
Reset()100%88100%
AddOccupant(...)100%44100%
TryRemoveOccupant(...)100%1414100%
GetOccupants()100%66100%
GetConditionalOccupants()100%1414100%
AddOccupantsWithinRadiusTo(...)100%1010100%
AddOccupantsWithinRadius2dTo(...)100%1212100%
AddOccupantsWithinRadiusTo(...)100%1010100%
AddOccupantsWithinRadius2dTo(...)100%1414100%
OccupantPassesFilters(...)100%66100%
IsWithinSquaredRadius(...)100%11100%
TryGetTypedOccupantWithinRadius(...)100%44100%
GetOccupantsFor()100%66100%
TryGetOccupantAt(...)100%1414100%
GetHashCode()100%11100%

File(s)

/home/runner/work/GridForge/GridForge/src/GridForge/Grids/Nodes/ScanCell.cs

#LineLine coverage
 1//=======================================================================
 2// ScanCell.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 System.Collections.Generic;
 10using System.Threading;
 11using FixedMathSharp;
 12using GridForge.Spatial;
 13using SwiftCollections;
 14using SwiftCollections.Utility;
 15
 16namespace GridForge.Grids;
 17
 18
 19
 20/// <summary>
 21/// Represents a spatial partition within a grid, managing occupants at a finer granularity than grid voxels.
 22/// Handles efficient tracking, retrieval, and removal of occupants within a designated scan cell area.
 23/// </summary>
 24public class ScanCell
 25{
 26    #region Properties
 27
 28    /// <summary>
 29    /// The world-local index of the grid this scan cell belongs to.
 30    /// </summary>
 31    public ushort GridIndex { get; private set; }
 32
 33    /// <summary>
 34    /// The world that owns this scan cell through its parent grid.
 35    /// </summary>
 36    public GridWorld? World { get; private set; }
 37
 38    /// <summary>
 39    /// A unique identifier for this scan cell in the grid.
 40    /// </summary>
 41    public int CellKey { get; private set; }
 42
 43    /// <summary>
 44    /// Maps a <see cref="Voxel.WorldIndex"/> to a bucket of associated <see cref="IVoxelOccupant"/> instances.
 45    /// </summary>
 46    private SwiftDictionary<WorldVoxelIndex, SwiftSlotMap<OccupantEntry>>? _voxelOccupants;
 47
 48    private object? _occupantSyncRoot;
 49
 50    private static long s_occupantGenerationCounter;
 51
 52    /// <summary>
 53    /// The total number of occupants in this scan cell.
 54    /// </summary>
 55    public int CellOccupantCount { get; private set; }
 56
 57    /// <summary>
 58    /// Indicates whether this scan cell is currently allocated in the grid.
 59    /// </summary>
 60    public bool IsAllocated { get; private set; }
 61
 62    /// <summary>
 63    /// Determines whether this scan cell is occupied by any occupants.
 64    /// A scan cell is only considered occupied if it is allocated and contains at least one occupant.
 65    /// </summary>
 265966    public bool IsOccupied => IsAllocated && CellOccupantCount > 0;
 67
 68    #endregion
 69
 70    #region Initialization & Reset
 71
 72    /// <summary>
 73    /// Initializes the scan cell with its owning grid and unique cell key.
 74    /// </summary>
 75    internal void Initialize(VoxelGrid grid, int cellKey)
 76    {
 1090777        World = grid.World;
 1090778        GridIndex = grid.GridIndex;
 1090779        CellKey = cellKey;
 1090780        IsAllocated = true;
 1090781        Volatile.Write(ref _occupantSyncRoot, grid.OccupantSyncRoot);
 1090782    }
 83
 84    /// <summary>
 85    /// Resets the scan cell, clearing all occupants and returning memory to object pools.
 86    /// This effectively marks the scan cell as deallocated and removes all references.
 87    /// </summary>
 88    internal void Reset()
 89    {
 1090890        object? syncRoot = Interlocked.Exchange(ref _occupantSyncRoot, null);
 1090891        if (syncRoot == null)
 192            return;
 93
 1090794        lock (syncRoot)
 95        {
 1090796            if (_voxelOccupants != null)
 97            {
 90898                foreach (var kvp in _voxelOccupants)
 99                {
 284100                    SwiftSlotMap<OccupantEntry> bucket = kvp.Value;
 1786101                    foreach (OccupantEntry entry in bucket)
 609102                        GridOccupantManager.ForgetTrackedOccupancy(World, entry.Occupant, kvp.Key);
 103
 284104                    Pools.VoxelOccupantBucketPool.Release(bucket);
 105                }
 106
 170107                Pools.VoxelOccupantDictionaryPool.Release(_voxelOccupants);
 170108                _voxelOccupants = null;
 109            }
 110
 10907111            CellOccupantCount = 0;
 112
 10907113            World = null;
 10907114            GridIndex = ushort.MaxValue;
 10907115            CellKey = byte.MaxValue;
 116
 10907117            IsAllocated = false;
 10907118        }
 10907119    }
 120
 121    #endregion
 122
 123    #region Occupant Management
 124
 125    /// <summary>
 126    /// Adds an occupant to this scan cell and tracks its presence.
 127    /// </summary>
 128    /// <param name="index">The global index of the voxel where the occupant resides.</param>
 129    /// <param name="occupant">The occupant instance to add.</param>
 130    /// <returns>A generation-aware ticket for the occupant's bucket slot.</returns>
 131    internal OccupantTicket AddOccupant(WorldVoxelIndex index, IVoxelOccupant occupant)
 132    {
 773133        long generation = RuntimeIdentityAllocator.Allocate(ref s_occupantGenerationCounter);
 772134        _voxelOccupants ??= Pools.VoxelOccupantDictionaryPool.Rent();
 772135        if (!_voxelOccupants.TryGetValue(index, out SwiftSlotMap<OccupantEntry> bucket))
 136        {
 311137            bucket = Pools.VoxelOccupantBucketPool.Rent();
 311138            _voxelOccupants[index] = bucket;
 139        }
 140
 772141        int slot = bucket.Add(new OccupantEntry(occupant, generation));
 772142        CellOccupantCount++;
 772143        return new OccupantTicket(slot, generation);
 144    }
 145
 146    /// <summary>
 147    /// Removes an occupant from this scan cell.
 148    /// </summary>
 149    /// <param name="index">The global index of the voxel the occupant was assigned to.</param>
 150    /// <param name="ticket">The ticket assigned to the occupant instance from this scancell.</param>
 151    /// <returns>True if the occupant was successfully removed; otherwise, false.</returns>
 152    internal bool TryRemoveOccupant(
 153        WorldVoxelIndex index,
 154        OccupantTicket ticket)
 155    {
 168156        if (!IsOccupied)
 1157            return false;
 158
 167159        if (!_voxelOccupants!.TryGetValue(index, out var bucket))
 1160            return false;
 161
 166162        if (!ticket.IsValid
 166163            || !bucket.TryGetValue(ticket.Slot, out OccupantEntry entry)
 166164            || entry.Generation != ticket.Generation
 166165            || !bucket.TryRemoveAt(ticket.Slot))
 166        {
 3167            return false;
 168        }
 169
 170        // If the occupant was the last in its bucket, remove the entire bucket
 163171        if (bucket.Count == 0)
 172        {
 27173            _voxelOccupants.Remove(index);
 27174            Pools.VoxelOccupantBucketPool.Release(bucket);
 175        }
 176
 163177        CellOccupantCount--;
 178
 163179        return true;
 180    }
 181
 182    #endregion
 183
 184    #region Occupant Retrieval
 185
 186    /// <summary>
 187    /// Retrieves all occupants associated with this ScanCell.
 188    /// </summary>
 189    /// <returns>An enumerable of occupants within this scan cell.</returns>
 190    public IEnumerable<IVoxelOccupant> GetOccupants()
 191    {
 10192        if (_voxelOccupants == null)
 2193            yield break;
 194
 30195        foreach (SwiftSlotMap<OccupantEntry> bucket in _voxelOccupants.Values)
 196        {
 162197            foreach (OccupantEntry entry in bucket)
 74198                yield return entry.Occupant;
 199        }
 6200    }
 201
 202    /// <summary>
 203    /// Retrieves occupants whose group Ids match a given condition.
 204    /// </summary>
 205    public IEnumerable<IVoxelOccupant> GetConditionalOccupants(
 206        Func<IVoxelOccupant, bool>? occupantCondition = null,
 207        Func<byte, bool>? groupConditional = null)
 208    {
 9209        if (_voxelOccupants == null)
 1210            yield break;
 211
 212        // Loop through each voxel's bucket and filter by the cluster condition
 31213        foreach (var bucket in _voxelOccupants.Values)
 214        {
 43215            foreach (OccupantEntry entry in bucket)
 216            {
 14217                IVoxelOccupant occupant = entry.Occupant;
 14218                if (occupantCondition != null && !occupantCondition(occupant))
 219                    continue;
 220
 11221                if (groupConditional != null && !groupConditional(occupant.OccupantGroupId))
 222                    continue;
 223
 7224                yield return occupant;
 225            }
 226        }
 7227    }
 228
 229    /// <summary>
 230    /// Appends occupants within the squared radius to caller-owned storage without allocating an iterator.
 231    /// </summary>
 232    internal void AddOccupantsWithinRadiusTo(
 233        SwiftList<IVoxelOccupant> results,
 234        Vector3d position,
 235        Fixed64 squaredRadius,
 236        Func<IVoxelOccupant, bool>? occupantCondition = null,
 237        Func<byte, bool>? groupCondition = null)
 238    {
 290239        if (_voxelOccupants == null)
 1240            return;
 241
 33552242        foreach (var kvp in _voxelOccupants)
 243        {
 16487244            SwiftSlotMap<OccupantEntry> bucket = kvp.Value;
 65950245            foreach (OccupantEntry entry in bucket)
 246            {
 16488247                IVoxelOccupant occupant = entry.Occupant;
 16488248                if (OccupantPassesFilters(occupant, occupantCondition, groupCondition)
 16488249                    && IsWithinSquaredRadius(occupant, position, squaredRadius))
 250                {
 16469251                    results.Add(occupant);
 252                }
 253            }
 254        }
 289255    }
 256
 257    /// <summary>
 258    /// Appends occupants within the XZ squared radius on the selected local Y voxel layer.
 259    /// </summary>
 260    internal void AddOccupantsWithinRadius2dTo(
 261        SwiftList<IVoxelOccupant> results,
 262        Vector3d position,
 263        int localLayerY,
 264        Fixed64 squaredRadius,
 265        Func<IVoxelOccupant, bool>? occupantCondition = null,
 266        Func<byte, bool>? groupCondition = null)
 267    {
 264268        if (_voxelOccupants == null)
 1269            return;
 270
 33440271        foreach (var kvp in _voxelOccupants)
 272        {
 16457273            if (kvp.Key.VoxelIndex.y != localLayerY)
 274                continue;
 275
 16453276            SwiftSlotMap<OccupantEntry> bucket = kvp.Value;
 65816277            foreach (OccupantEntry entry in bucket)
 278            {
 16455279                IVoxelOccupant occupant = entry.Occupant;
 16455280                if (OccupantPassesFilters(occupant, occupantCondition, groupCondition)
 16455281                    && GridPlane2d.DistanceSquaredXZ(occupant.Position, position) <= squaredRadius)
 282                {
 16452283                    results.Add(occupant);
 284                }
 285            }
 286        }
 263287    }
 288
 289    /// <summary>
 290    /// Appends typed occupants within the squared radius to caller-owned storage without LINQ.
 291    /// </summary>
 292    internal void AddOccupantsWithinRadiusTo<T>(
 293        SwiftList<T> results,
 294        Vector3d position,
 295        Fixed64 squaredRadius,
 296        Func<IVoxelOccupant, bool>? occupantCondition = null,
 297        Func<byte, bool>? groupCondition = null) where T : IVoxelOccupant
 298    {
 169299        if (_voxelOccupants == null)
 1300            return;
 301
 672302        foreach (var kvp in _voxelOccupants)
 303        {
 168304            SwiftSlotMap<OccupantEntry> bucket = kvp.Value;
 674305            foreach (OccupantEntry entry in bucket)
 306            {
 169307                IVoxelOccupant occupant = entry.Occupant;
 169308                if (!OccupantPassesFilters(occupant, occupantCondition, groupCondition))
 309                    continue;
 310
 168311                if (TryGetTypedOccupantWithinRadius(occupant, position, squaredRadius, out T typedOccupant))
 158312                    results.Add(typedOccupant);
 313            }
 314        }
 168315    }
 316
 317    /// <summary>
 318    /// Appends typed occupants within the XZ squared radius on the selected local Y voxel layer.
 319    /// </summary>
 320    internal void AddOccupantsWithinRadius2dTo<T>(
 321        SwiftList<T> results,
 322        Vector3d position,
 323        int localLayerY,
 324        Fixed64 squaredRadius,
 325        Func<IVoxelOccupant, bool>? occupantCondition = null,
 326        Func<byte, bool>? groupCondition = null) where T : IVoxelOccupant
 327    {
 5328        if (_voxelOccupants == null)
 1329            return;
 330
 20331        foreach (var kvp in _voxelOccupants)
 332        {
 6333            if (kvp.Key.VoxelIndex.y != localLayerY)
 334                continue;
 335
 4336            SwiftSlotMap<OccupantEntry> bucket = kvp.Value;
 20337            foreach (OccupantEntry entry in bucket)
 338            {
 6339                IVoxelOccupant occupant = entry.Occupant;
 6340                if (!OccupantPassesFilters(occupant, occupantCondition, groupCondition))
 341                    continue;
 342
 4343                if (occupant is T typedOccupant
 4344                    && GridPlane2d.DistanceSquaredXZ(occupant.Position, position) <= squaredRadius)
 345                {
 2346                    results.Add(typedOccupant);
 347                }
 348            }
 349        }
 4350    }
 351
 352    private static bool OccupantPassesFilters(
 353        IVoxelOccupant occupant,
 354        Func<IVoxelOccupant, bool>? occupantCondition,
 355        Func<byte, bool>? groupCondition)
 356    {
 33118357        return (occupantCondition == null || occupantCondition(occupant))
 33118358            && (groupCondition == null || groupCondition(occupant.OccupantGroupId));
 359    }
 360
 361    private static bool IsWithinSquaredRadius(
 362        IVoxelOccupant occupant,
 363        Vector3d position,
 364        Fixed64 squaredRadius)
 365    {
 16650366        return (occupant.Position - position).MagnitudeSquared <= squaredRadius;
 367    }
 368
 369    private static bool TryGetTypedOccupantWithinRadius<T>(
 370        IVoxelOccupant occupant,
 371        Vector3d position,
 372        Fixed64 squaredRadius,
 373        out T typedOccupant) where T : IVoxelOccupant
 374    {
 168375        typedOccupant = default!;
 168376        if (occupant is not T candidate || !IsWithinSquaredRadius(occupant, position, squaredRadius))
 10377            return false;
 378
 158379        typedOccupant = candidate;
 158380        return true;
 381    }
 382
 383    /// <summary>
 384    /// Retrieves all occupants associated with a world-scoped voxel identity within this scan cell.
 385    /// </summary>
 386    /// <param name="index">The voxel identity including world and grid generations and its local index.</param>
 387    /// <returns>An enumerable collection of occupants assigned to the voxel.</returns>
 388    public IEnumerable<IVoxelOccupant> GetOccupantsFor(WorldVoxelIndex index)
 389    {
 6390        if (_voxelOccupants == null || !_voxelOccupants.TryGetValue(index, out SwiftSlotMap<OccupantEntry> voxelOccupant
 2391            yield break;
 392
 526393        foreach (OccupantEntry entry in voxelOccupants)
 259394            yield return entry.Occupant;
 4395    }
 396
 397    /// <summary>
 398    /// Attempts to retrieve a specific occupant in this scan cell using a world-scoped voxel identity and occupant tick
 399    /// </summary>
 400    /// <param name="index">The world-scoped identity of the voxel the occupant belongs to.</param>
 401    /// <param name="occupantTicket">The unique ticket identifying the occupant.</param>
 402    /// <param name="voxelOccupant">The retrieved occupant if found.</param>
 403    /// <returns>True if the occupant was found, otherwise false.</returns>
 404    public bool TryGetOccupantAt(
 405        WorldVoxelIndex index,
 406        OccupantTicket occupantTicket,
 407        out IVoxelOccupant? voxelOccupant)
 408    {
 8225409        voxelOccupant = null;
 8225410        object? syncRoot = Volatile.Read(ref _occupantSyncRoot);
 8225411        if (syncRoot == null)
 1412            return false;
 413
 8224414        lock (syncRoot)
 415        {
 8224416            if (!ReferenceEquals(syncRoot, Volatile.Read(ref _occupantSyncRoot))
 8224417                || _voxelOccupants == null
 8224418                || !_voxelOccupants.TryGetValue(index, out SwiftSlotMap<OccupantEntry> voxelOccupants)
 8224419                || !occupantTicket.IsValid
 8224420                || !voxelOccupants.TryGetValue(occupantTicket.Slot, out OccupantEntry entry)
 8224421                || entry.Generation != occupantTicket.Generation)
 422            {
 12423                return false;
 424            }
 425
 8212426            voxelOccupant = entry.Occupant;
 8212427            return true;
 428        }
 8224429    }
 430
 431    #endregion
 432
 433    /// <inheritdoc/>
 2756434    public override int GetHashCode() => SwiftHashTools.CombineHashCodes(GridIndex, CellKey);
 435}

Methods/Properties

get_IsOccupied()
Initialize(GridForge.Grids.VoxelGrid,System.Int32)
Reset()
AddOccupant(GridForge.Spatial.WorldVoxelIndex,GridForge.Spatial.IVoxelOccupant)
TryRemoveOccupant(GridForge.Spatial.WorldVoxelIndex,GridForge.OccupantTicket)
GetOccupants()
GetConditionalOccupants()
AddOccupantsWithinRadiusTo(SwiftCollections.SwiftList`1<GridForge.Spatial.IVoxelOccupant>,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64,System.Func`2<GridForge.Spatial.IVoxelOccupant,System.Boolean>,System.Func`2<System.Byte,System.Boolean>)
AddOccupantsWithinRadius2dTo(SwiftCollections.SwiftList`1<GridForge.Spatial.IVoxelOccupant>,FixedMathSharp.Vector3d,System.Int32,FixedMathSharp.Fixed64,System.Func`2<GridForge.Spatial.IVoxelOccupant,System.Boolean>,System.Func`2<System.Byte,System.Boolean>)
AddOccupantsWithinRadiusTo(SwiftCollections.SwiftList`1<T>,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64,System.Func`2<GridForge.Spatial.IVoxelOccupant,System.Boolean>,System.Func`2<System.Byte,System.Boolean>)
AddOccupantsWithinRadius2dTo(SwiftCollections.SwiftList`1<T>,FixedMathSharp.Vector3d,System.Int32,FixedMathSharp.Fixed64,System.Func`2<GridForge.Spatial.IVoxelOccupant,System.Boolean>,System.Func`2<System.Byte,System.Boolean>)
OccupantPassesFilters(GridForge.Spatial.IVoxelOccupant,System.Func`2<GridForge.Spatial.IVoxelOccupant,System.Boolean>,System.Func`2<System.Byte,System.Boolean>)
IsWithinSquaredRadius(GridForge.Spatial.IVoxelOccupant,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64)
TryGetTypedOccupantWithinRadius(GridForge.Spatial.IVoxelOccupant,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64,T&)
GetOccupantsFor()
TryGetOccupantAt(GridForge.Spatial.WorldVoxelIndex,GridForge.OccupantTicket,GridForge.Spatial.IVoxelOccupant&)
GetHashCode()