| | | 1 | | //======================================================================= |
| | | 2 | | // GridWorld.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 | | |
| | | 8 | | using System; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.Diagnostics; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Threading; |
| | | 13 | | using FixedMathSharp; |
| | | 14 | | using GridForge.Configuration; |
| | | 15 | | using GridForge.Grids.Storage; |
| | | 16 | | using GridForge.Grids.Topology; |
| | | 17 | | using GridForge.Spatial; |
| | | 18 | | using SwiftCollections; |
| | | 19 | | using SwiftCollections.Query; |
| | | 20 | | |
| | | 21 | | namespace GridForge.Grids; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Owns the mutable runtime state for one GridForge world. |
| | | 25 | | /// </summary> |
| | | 26 | | public sealed class GridWorld : IDisposable |
| | | 27 | | { |
| | | 28 | | #region Constants |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Maximum number of grids that can be managed within a world. |
| | | 32 | | /// </summary> |
| | | 33 | | public const ushort MaxGrids = ushort.MaxValue - 1; |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// The default rectangular cell edge in world units. |
| | | 37 | | /// </summary> |
| | 1 | 38 | | public static readonly Fixed64 DefaultRectangularCellSize = Fixed64.One; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// The default cell size used to tune ordinary-grid lookup. |
| | | 42 | | /// Oversized grids are indexed automatically outside this tier. |
| | | 43 | | /// </summary> |
| | | 44 | | public const int DefaultSpatialGridCellSize = 50; |
| | | 45 | | |
| | | 46 | | #endregion |
| | | 47 | | |
| | | 48 | | #region Properties |
| | | 49 | | |
| | 1 | 50 | | private static readonly Comparison<VoxelIndex> CompareVoxelIndices = |
| | 1 | 51 | | static (left, right) => left.CompareTo(right); |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// The cell size used to tune ordinary-grid lookup in this world. |
| | | 55 | | /// Oversized grids are indexed automatically outside this tier. |
| | | 56 | | /// </summary> |
| | | 57 | | public int SpatialGridCellSize { get; } |
| | | 58 | | |
| | | 59 | | /// <summary> |
| | | 60 | | /// Collection of all active grids owned by this world. |
| | | 61 | | /// </summary> |
| | | 62 | | public SwiftBucket<VoxelGrid> ActiveGrids { get; } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Dictionary mapping exact grid configuration keys to grid indices to prevent duplicate grids. |
| | | 66 | | /// </summary> |
| | | 67 | | public SwiftDictionary<GridConfigurationKey, ushort> BoundsTracker { get; } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Nonzero process-unique 64-bit runtime allocation token for this active world. |
| | | 71 | | /// Zero indicates an inactive world. |
| | | 72 | | /// </summary> |
| | | 73 | | public long SpawnToken { get; private set; } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// The current version of the world, incremented on major changes. |
| | | 77 | | /// </summary> |
| | | 78 | | public uint Version { get; private set; } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Indicates whether this world is currently active. |
| | | 82 | | /// </summary> |
| | | 83 | | public bool IsActive { get; private set; } |
| | | 84 | | |
| | | 85 | | internal Fixed64 MaxTopologyCellEdge { get; private set; } |
| | | 86 | | |
| | | 87 | | private static long s_worldAllocationCounter; |
| | | 88 | | private static long s_obstacleRegistrationCounter; |
| | | 89 | | |
| | 537 | 90 | | private readonly ReaderWriterLockSlim _gridLock = new(); |
| | 537 | 91 | | private readonly SwiftList<ushort> _gridCandidates = new(); |
| | | 92 | | private readonly GridSpatialIndex _spatialIndex; |
| | | 93 | | private long _gridGenerationCounter; |
| | | 94 | | |
| | | 95 | | #endregion |
| | | 96 | | |
| | | 97 | | #region Events |
| | | 98 | | |
| | | 99 | | private Action<GridEventInfo>? _onActiveGridAdded; |
| | | 100 | | private Action<GridEventInfo>? _onActiveGridRemoved; |
| | | 101 | | private Action<GridEventInfo>? _onActiveGridChange; |
| | | 102 | | private Action? _onReset; |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Event triggered when a new grid is added to this world. |
| | | 106 | | /// </summary> |
| | | 107 | | public event Action<GridEventInfo> OnActiveGridAdded |
| | | 108 | | { |
| | 170 | 109 | | add => _onActiveGridAdded += value; |
| | 167 | 110 | | remove => _onActiveGridAdded -= value; |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Event triggered when a grid is removed from this world. |
| | | 115 | | /// </summary> |
| | | 116 | | public event Action<GridEventInfo> OnActiveGridRemoved |
| | | 117 | | { |
| | 170 | 118 | | add => _onActiveGridRemoved += value; |
| | 167 | 119 | | remove => _onActiveGridRemoved -= value; |
| | | 120 | | } |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Event triggered when a grid in this world undergoes a significant change. |
| | | 124 | | /// </summary> |
| | | 125 | | public event Action<GridEventInfo> OnActiveGridChange |
| | | 126 | | { |
| | 176 | 127 | | add => _onActiveGridChange += value; |
| | 168 | 128 | | remove => _onActiveGridChange -= value; |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Event triggered when this world is reset. |
| | | 133 | | /// </summary> |
| | | 134 | | public event Action OnReset |
| | | 135 | | { |
| | 170 | 136 | | add => _onReset += value; |
| | 167 | 137 | | remove => _onReset -= value; |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | #endregion |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Initializes a new world with optional ordinary-grid lookup tuning. |
| | | 144 | | /// </summary> |
| | | 145 | | /// <param name="spatialGridCellSize">Optional ordinary-grid lookup cell size for this world.</param> |
| | 537 | 146 | | public GridWorld(int spatialGridCellSize = DefaultSpatialGridCellSize) |
| | | 147 | | { |
| | 537 | 148 | | ActiveGrids = new SwiftBucket<VoxelGrid>(); |
| | 537 | 149 | | BoundsTracker = new SwiftDictionary<GridConfigurationKey, ushort>(); |
| | | 150 | | |
| | 537 | 151 | | SpatialGridCellSize = ResolveSpatialGridCellSize(spatialGridCellSize); |
| | 537 | 152 | | _spatialIndex = new GridSpatialIndex(SpatialGridCellSize); |
| | 537 | 153 | | SpawnToken = RuntimeIdentityAllocator.Allocate(ref s_worldAllocationCounter); |
| | 537 | 154 | | Version = 1; |
| | 537 | 155 | | IsActive = true; |
| | 537 | 156 | | } |
| | | 157 | | |
| | | 158 | | #region Lifecycle |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Clears all grids and spatial data owned by this world. |
| | | 162 | | /// </summary> |
| | | 163 | | /// <param name="deactivate">If true, marks the world inactive and releases its event handlers.</param> |
| | | 164 | | public void Reset(bool deactivate = false) |
| | | 165 | | { |
| | 548 | 166 | | if (!IsActive) |
| | | 167 | | { |
| | 6 | 168 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot reset an inactive world."); |
| | 6 | 169 | | return; |
| | | 170 | | } |
| | | 171 | | |
| | 542 | 172 | | NotifyResetHandlers(); |
| | 542 | 173 | | ReleaseActiveGrids(); |
| | 542 | 174 | | GridOccupantManager.ClearTrackedOccupancies(this); |
| | | 175 | | |
| | 542 | 176 | | if (!deactivate) |
| | 9 | 177 | | return; |
| | | 178 | | |
| | 533 | 179 | | GridOccupantManager.ReleaseTrackedOccupancies(this); |
| | 533 | 180 | | IsActive = false; |
| | 533 | 181 | | SpawnToken = 0; |
| | 533 | 182 | | _onActiveGridAdded = null; |
| | 533 | 183 | | _onActiveGridRemoved = null; |
| | 533 | 184 | | _onActiveGridChange = null; |
| | 533 | 185 | | _onReset = null; |
| | 533 | 186 | | } |
| | | 187 | | |
| | | 188 | | private void NotifyResetHandlers() |
| | | 189 | | { |
| | 542 | 190 | | Action? resetHandlers = _onReset; |
| | 542 | 191 | | if (resetHandlers == null) |
| | 520 | 192 | | return; |
| | | 193 | | |
| | 22 | 194 | | var handlerDelegates = resetHandlers.GetInvocationList(); |
| | 312 | 195 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 196 | | { |
| | | 197 | | try |
| | | 198 | | { |
| | 134 | 199 | | ((Action)handlerDelegates[i])(); |
| | 132 | 200 | | } |
| | 2 | 201 | | catch (Exception ex) |
| | | 202 | | { |
| | 2 | 203 | | GridForgeLogger.Channel.Error($"World reset notification error: {ex.Message}"); |
| | 2 | 204 | | } |
| | | 205 | | } |
| | 22 | 206 | | } |
| | | 207 | | |
| | | 208 | | private void ReleaseActiveGrids() |
| | | 209 | | { |
| | 542 | 210 | | _spatialIndex.Clear(); |
| | | 211 | | |
| | 2110 | 212 | | foreach (VoxelGrid grid in ActiveGrids) |
| | 513 | 213 | | Pools.GridPool.Release(grid); |
| | | 214 | | |
| | 542 | 215 | | ActiveGrids.Clear(); |
| | 542 | 216 | | BoundsTracker.Clear(); |
| | 542 | 217 | | MaxTopologyCellEdge = Fixed64.Zero; |
| | 542 | 218 | | } |
| | | 219 | | |
| | | 220 | | /// <inheritdoc /> |
| | | 221 | | public void Dispose() |
| | | 222 | | { |
| | 536 | 223 | | Reset(deactivate: true); |
| | 536 | 224 | | _gridLock.Dispose(); |
| | 536 | 225 | | GC.SuppressFinalize(this); |
| | 536 | 226 | | } |
| | | 227 | | |
| | | 228 | | #endregion |
| | | 229 | | |
| | | 230 | | #region Grid Management |
| | | 231 | | |
| | | 232 | | /// <summary> |
| | | 233 | | /// Allocates a nonzero process-unique identity for one obstacle registration lifetime. |
| | | 234 | | /// </summary> |
| | | 235 | | /// <returns>A fresh opaque obstacle token.</returns> |
| | | 236 | | /// <exception cref="InvalidOperationException">The world is inactive or its token space is exhausted.</exception> |
| | | 237 | | public ObstacleToken AllocateObstacleToken() |
| | | 238 | | { |
| | 509 | 239 | | if (!IsActive) |
| | 1 | 240 | | throw new InvalidOperationException("Cannot allocate an obstacle token from an inactive world."); |
| | | 241 | | |
| | 508 | 242 | | return new ObstacleToken(RuntimeIdentityAllocator.Allocate(ref s_obstacleRegistrationCounter)); |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | /// <summary> |
| | | 246 | | /// Adds a new grid to this world and registers it in the spatial index. |
| | | 247 | | /// </summary> |
| | | 248 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 249 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 250 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 251 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 252 | | public bool TryAddGrid(GridConfiguration configuration, out ushort allocatedIndex) => |
| | 493 | 253 | | TryAddGridCore(configuration, null, null, out allocatedIndex); |
| | | 254 | | |
| | | 255 | | /// <summary> |
| | | 256 | | /// Adds a new grid to this world and materializes the supplied sparse voxel indices when sparse storage is configur |
| | | 257 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 258 | | /// </summary> |
| | | 259 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 260 | | /// <param name="configuredVoxels">Grid-local voxel indices to materialize for sparse storage.</param> |
| | | 261 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 262 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 263 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 264 | | public bool TryAddGrid( |
| | | 265 | | GridConfiguration configuration, |
| | | 266 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 267 | | out ushort allocatedIndex) => |
| | 81 | 268 | | TryAddGridCore(configuration, configuredVoxels, null, out allocatedIndex); |
| | | 269 | | |
| | | 270 | | /// <summary> |
| | | 271 | | /// Adds a new grid to this world and materializes true cells from the supplied sparse voxel mask when sparse storag |
| | | 272 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 273 | | /// </summary> |
| | | 274 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 275 | | /// <param name="configuredVoxels">A [x, y, z] mask whose true values identify sparse voxels to materialize. Sparse |
| | | 276 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 277 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 278 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 279 | | public bool TryAddGrid( |
| | | 280 | | GridConfiguration configuration, |
| | | 281 | | bool[,,]? configuredVoxels, |
| | | 282 | | out ushort allocatedIndex) => |
| | 7 | 283 | | TryAddGridCore(configuration, null, configuredVoxels, out allocatedIndex); |
| | | 284 | | |
| | | 285 | | private bool TryAddGridCore( |
| | | 286 | | GridConfiguration configuration, |
| | | 287 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 288 | | bool[,,]? configuredVoxelMask, |
| | | 289 | | out ushort allocatedIndex) |
| | | 290 | | { |
| | 581 | 291 | | allocatedIndex = ushort.MaxValue; |
| | | 292 | | |
| | 581 | 293 | | if (!CanAddGrid()) |
| | 5 | 294 | | return false; |
| | | 295 | | |
| | 576 | 296 | | if (!TryNormalizeConfiguration( |
| | 576 | 297 | | configuration, |
| | 576 | 298 | | out GridConfiguration normalizedConfiguration, |
| | 576 | 299 | | out IGridTopology topology, |
| | 576 | 300 | | out GridDimensions dimensions) |
| | 576 | 301 | | || !TryValidateGridDimensions(dimensions)) |
| | | 302 | | { |
| | 6 | 303 | | return false; |
| | | 304 | | } |
| | | 305 | | |
| | 570 | 306 | | if (!TryPrepareConfiguredVoxels( |
| | 570 | 307 | | normalizedConfiguration, |
| | 570 | 308 | | dimensions, |
| | 570 | 309 | | configuredVoxels, |
| | 570 | 310 | | configuredVoxelMask, |
| | 570 | 311 | | out VoxelIndex[] preparedVoxels)) |
| | | 312 | | { |
| | 12 | 313 | | return false; |
| | | 314 | | } |
| | | 315 | | |
| | 558 | 316 | | GridConfigurationKey boundsKey = normalizedConfiguration.ToGridKey(); |
| | | 317 | | |
| | 558 | 318 | | if (TryFindExistingGrid(boundsKey, out allocatedIndex)) |
| | 4 | 319 | | return false; |
| | | 320 | | |
| | 554 | 321 | | long gridGeneration = RuntimeIdentityAllocator.Allocate(ref _gridGenerationCounter); |
| | 554 | 322 | | VoxelGrid newGrid = Pools.GridPool.Rent(); |
| | 554 | 323 | | GridEventInfo addedGridInfo = default; |
| | | 324 | | |
| | 554 | 325 | | _gridLock.EnterWriteLock(); |
| | | 326 | | try |
| | | 327 | | { |
| | 554 | 328 | | allocatedIndex = (ushort)ActiveGrids.Add(newGrid); |
| | 554 | 329 | | BoundsTracker.Add(boundsKey, allocatedIndex); |
| | | 330 | | |
| | 554 | 331 | | newGrid.Initialize(this, allocatedIndex, gridGeneration, normalizedConfiguration, topology, preparedVoxels); |
| | 554 | 332 | | UpdateMaxTopologyCellEdge(newGrid.Topology.MaxCellEdge); |
| | 554 | 333 | | RegisterGrid(newGrid, allocatedIndex); |
| | | 334 | | |
| | 554 | 335 | | Version++; |
| | 554 | 336 | | addedGridInfo = CreateGridEventInfo(newGrid, GridEventKind.GridAdded); |
| | 554 | 337 | | } |
| | | 338 | | finally |
| | | 339 | | { |
| | 554 | 340 | | _gridLock.ExitWriteLock(); |
| | 554 | 341 | | } |
| | | 342 | | |
| | 554 | 343 | | NotifyActiveGridAdded(addedGridInfo); |
| | 554 | 344 | | return true; |
| | | 345 | | } |
| | | 346 | | |
| | | 347 | | /// <summary> |
| | | 348 | | /// Removes a grid from this world and updates all references to ensure integrity. |
| | | 349 | | /// </summary> |
| | | 350 | | /// <param name="removeIndex">The world-local grid slot to remove.</param> |
| | | 351 | | /// <returns>True if the grid was removed; otherwise false.</returns> |
| | | 352 | | public bool TryRemoveGrid(ushort removeIndex) |
| | | 353 | | { |
| | 43 | 354 | | if (!IsActive || !ActiveGrids.IsAllocated(removeIndex)) |
| | 2 | 355 | | return false; |
| | | 356 | | |
| | | 357 | | VoxelGrid gridToRemove; |
| | 41 | 358 | | GridEventInfo removedGridInfo = default; |
| | | 359 | | |
| | 41 | 360 | | _gridLock.EnterWriteLock(); |
| | | 361 | | try |
| | | 362 | | { |
| | 41 | 363 | | gridToRemove = ActiveGrids[removeIndex]; |
| | 41 | 364 | | Fixed64 removedMaxCellEdge = gridToRemove.Topology.MaxCellEdge; |
| | 41 | 365 | | UnregisterGrid(gridToRemove, removeIndex); |
| | 41 | 366 | | BoundsTracker.Remove(gridToRemove.Configuration.ToGridKey()); |
| | 41 | 367 | | ActiveGrids.RemoveAt(removeIndex); |
| | 41 | 368 | | RecalculateMaxTopologyCellEdgeIfNeeded(removedMaxCellEdge); |
| | | 369 | | |
| | 41 | 370 | | Version++; |
| | 41 | 371 | | removedGridInfo = CreateGridEventInfo(gridToRemove, GridEventKind.GridRemoved); |
| | 41 | 372 | | } |
| | | 373 | | finally |
| | | 374 | | { |
| | 41 | 375 | | _gridLock.ExitWriteLock(); |
| | 41 | 376 | | } |
| | | 377 | | |
| | 41 | 378 | | Pools.GridPool.Release(gridToRemove); |
| | 41 | 379 | | NotifyActiveGridRemoved(removedGridInfo); |
| | | 380 | | |
| | 41 | 381 | | if (ActiveGrids.Count == 0) |
| | 25 | 382 | | ActiveGrids.TrimExcessCapacity(); |
| | | 383 | | |
| | 41 | 384 | | return true; |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | #endregion |
| | | 388 | | |
| | | 389 | | private bool CanAddGrid() |
| | | 390 | | { |
| | 581 | 391 | | if (!IsActive) |
| | | 392 | | { |
| | 3 | 393 | | GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world."); |
| | 3 | 394 | | return false; |
| | | 395 | | } |
| | | 396 | | |
| | 578 | 397 | | if ((uint)ActiveGrids.Count >= MaxGrids) |
| | | 398 | | { |
| | 2 | 399 | | GridForgeLogger.Channel.Warn($"No more grids can be added at this time."); |
| | 2 | 400 | | return false; |
| | | 401 | | } |
| | | 402 | | |
| | 576 | 403 | | return true; |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | private static bool TryPrepareConfiguredVoxels( |
| | | 407 | | GridConfiguration configuration, |
| | | 408 | | GridDimensions dimensions, |
| | | 409 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 410 | | bool[,,]? configuredVoxelMask, |
| | | 411 | | out VoxelIndex[] preparedVoxels) |
| | | 412 | | { |
| | 570 | 413 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 570 | 414 | | if (configuration.StorageKind != GridStorageKind.Sparse) |
| | 456 | 415 | | return true; |
| | | 416 | | |
| | 114 | 417 | | if (configuredVoxelMask != null) |
| | 7 | 418 | | return TryPrepareConfiguredVoxelMask(configuredVoxelMask, dimensions, out preparedVoxels); |
| | | 419 | | |
| | 107 | 420 | | return TryPrepareConfiguredVoxelIndices(configuredVoxels, dimensions, out preparedVoxels); |
| | | 421 | | } |
| | | 422 | | |
| | | 423 | | private static bool TryValidateGridDimensions(GridDimensions dimensions) |
| | | 424 | | { |
| | 575 | 425 | | long layerSize = (long)dimensions.Width * dimensions.Height; |
| | 575 | 426 | | if (layerSize > int.MaxValue || layerSize * dimensions.Length > int.MaxValue) |
| | | 427 | | { |
| | 4 | 428 | | GridForgeLogger.Channel.Warn($"Grid dimensions exceed the supported int voxel address space."); |
| | 4 | 429 | | return false; |
| | | 430 | | } |
| | | 431 | | |
| | 571 | 432 | | return true; |
| | | 433 | | } |
| | | 434 | | |
| | | 435 | | private static bool TryPrepareConfiguredVoxelMask( |
| | | 436 | | bool[,,] configuredVoxelMask, |
| | | 437 | | GridDimensions dimensions, |
| | | 438 | | out VoxelIndex[] preparedVoxels) |
| | | 439 | | { |
| | 7 | 440 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | | 441 | | |
| | 7 | 442 | | if (configuredVoxelMask.GetLength(0) != dimensions.Width |
| | 7 | 443 | | || configuredVoxelMask.GetLength(1) != dimensions.Height |
| | 7 | 444 | | || configuredVoxelMask.GetLength(2) != dimensions.Length) |
| | | 445 | | { |
| | 5 | 446 | | GridForgeLogger.Channel.Warn($"Sparse voxel mask dimensions must match normalized grid dimensions."); |
| | 5 | 447 | | return false; |
| | | 448 | | } |
| | | 449 | | |
| | 2 | 450 | | int configuredCount = 0; |
| | 12 | 451 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 452 | | { |
| | 16 | 453 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 454 | | { |
| | 24 | 455 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 456 | | { |
| | 8 | 457 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 458 | | configuredCount++; |
| | | 459 | | } |
| | | 460 | | } |
| | | 461 | | } |
| | | 462 | | |
| | 2 | 463 | | if (configuredCount == 0) |
| | 1 | 464 | | return true; |
| | | 465 | | |
| | 1 | 466 | | preparedVoxels = new VoxelIndex[configuredCount]; |
| | 1 | 467 | | int index = 0; |
| | 6 | 468 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 469 | | { |
| | 8 | 470 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 471 | | { |
| | 12 | 472 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 473 | | { |
| | 4 | 474 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 475 | | preparedVoxels[index++] = new VoxelIndex(x, y, z); |
| | | 476 | | } |
| | | 477 | | } |
| | | 478 | | } |
| | | 479 | | |
| | 1 | 480 | | return true; |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | private static bool TryPrepareConfiguredVoxelIndices( |
| | | 484 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 485 | | GridDimensions dimensions, |
| | | 486 | | out VoxelIndex[] preparedVoxels) |
| | | 487 | | { |
| | 107 | 488 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 107 | 489 | | if (configuredVoxels == null) |
| | 27 | 490 | | return true; |
| | | 491 | | |
| | 80 | 492 | | SwiftList<VoxelIndex> indices = configuredVoxels is ICollection<VoxelIndex> collection |
| | 80 | 493 | | ? new SwiftList<VoxelIndex>(collection.Count) |
| | 80 | 494 | | : new SwiftList<VoxelIndex>(); |
| | | 495 | | |
| | 371 | 496 | | foreach (VoxelIndex configuredVoxel in configuredVoxels) |
| | | 497 | | { |
| | 109 | 498 | | if (!IsConfiguredVoxelInBounds(configuredVoxel, dimensions)) |
| | | 499 | | { |
| | 7 | 500 | | GridForgeLogger.Channel.Warn($"Sparse voxel index {configuredVoxel} is outside normalized grid dimension |
| | 7 | 501 | | return false; |
| | | 502 | | } |
| | | 503 | | |
| | 102 | 504 | | indices.Add(configuredVoxel); |
| | | 505 | | } |
| | | 506 | | |
| | 73 | 507 | | if (indices.Count == 0) |
| | 3 | 508 | | return true; |
| | | 509 | | |
| | 70 | 510 | | preparedVoxels = indices.ToArray(); |
| | 70 | 511 | | Array.Sort(preparedVoxels, CompareVoxelIndices); |
| | 70 | 512 | | CompactPreparedVoxels(ref preparedVoxels); |
| | 70 | 513 | | return true; |
| | 7 | 514 | | } |
| | | 515 | | |
| | | 516 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 517 | | private static bool IsConfiguredVoxelInBounds(VoxelIndex voxelIndex, GridDimensions dimensions) => |
| | 109 | 518 | | (uint)voxelIndex.x < (uint)dimensions.Width |
| | 109 | 519 | | && (uint)voxelIndex.y < (uint)dimensions.Height |
| | 109 | 520 | | && (uint)voxelIndex.z < (uint)dimensions.Length; |
| | | 521 | | |
| | | 522 | | private static void CompactPreparedVoxels(ref VoxelIndex[] preparedVoxels) |
| | | 523 | | { |
| | 70 | 524 | | if (preparedVoxels.Length < 2) |
| | 49 | 525 | | return; |
| | | 526 | | |
| | 21 | 527 | | int writeIndex = 1; |
| | 21 | 528 | | VoxelIndex previous = preparedVoxels[0]; |
| | 106 | 529 | | for (int readIndex = 1; readIndex < preparedVoxels.Length; readIndex++) |
| | | 530 | | { |
| | 32 | 531 | | VoxelIndex current = preparedVoxels[readIndex]; |
| | 32 | 532 | | if (current == previous) |
| | | 533 | | continue; |
| | | 534 | | |
| | 30 | 535 | | preparedVoxels[writeIndex++] = current; |
| | 30 | 536 | | previous = current; |
| | | 537 | | } |
| | | 538 | | |
| | 21 | 539 | | if (writeIndex != preparedVoxels.Length) |
| | 2 | 540 | | Array.Resize(ref preparedVoxels, writeIndex); |
| | 21 | 541 | | } |
| | | 542 | | |
| | | 543 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 544 | | private void UpdateMaxTopologyCellEdge(Fixed64 candidate) |
| | | 545 | | { |
| | 554 | 546 | | if (candidate > MaxTopologyCellEdge) |
| | 445 | 547 | | MaxTopologyCellEdge = candidate; |
| | 554 | 548 | | } |
| | | 549 | | |
| | | 550 | | private void RecalculateMaxTopologyCellEdgeIfNeeded(Fixed64 removedMaxCellEdge) |
| | | 551 | | { |
| | 41 | 552 | | if (removedMaxCellEdge < MaxTopologyCellEdge) |
| | 3 | 553 | | return; |
| | | 554 | | |
| | 38 | 555 | | Fixed64 maxCellEdge = Fixed64.Zero; |
| | 108 | 556 | | foreach (VoxelGrid grid in ActiveGrids) |
| | | 557 | | { |
| | 16 | 558 | | if (grid.Topology.MaxCellEdge > maxCellEdge) |
| | 13 | 559 | | maxCellEdge = grid.Topology.MaxCellEdge; |
| | | 560 | | } |
| | | 561 | | |
| | 38 | 562 | | MaxTopologyCellEdge = maxCellEdge; |
| | 38 | 563 | | } |
| | | 564 | | |
| | | 565 | | private bool TryFindExistingGrid(GridConfigurationKey boundsKey, out ushort allocatedIndex) |
| | | 566 | | { |
| | 558 | 567 | | _gridLock.EnterReadLock(); |
| | | 568 | | try |
| | | 569 | | { |
| | 558 | 570 | | if (BoundsTracker.TryGetValue(boundsKey, out allocatedIndex)) |
| | | 571 | | { |
| | 4 | 572 | | GridForgeLogger.Channel.Warn($"A grid with these bounds has already been allocated."); |
| | 4 | 573 | | return true; |
| | | 574 | | } |
| | 554 | 575 | | } |
| | | 576 | | finally |
| | | 577 | | { |
| | 558 | 578 | | _gridLock.ExitReadLock(); |
| | 558 | 579 | | } |
| | | 580 | | |
| | 554 | 581 | | allocatedIndex = ushort.MaxValue; |
| | 554 | 582 | | return false; |
| | 4 | 583 | | } |
| | | 584 | | |
| | | 585 | | private void RegisterGrid(VoxelGrid newGrid, ushort allocatedIndex) |
| | | 586 | | { |
| | 554 | 587 | | _spatialIndex.Insert( |
| | 554 | 588 | | allocatedIndex, |
| | 554 | 589 | | new FixedBoundVolume(newGrid.BoundsMin, newGrid.BoundsMax)); |
| | 554 | 590 | | _spatialIndex.CollectCandidates( |
| | 554 | 591 | | CreateExpandedBounds( |
| | 554 | 592 | | newGrid.BoundsMin, |
| | 554 | 593 | | newGrid.BoundsMax, |
| | 554 | 594 | | newGrid.Topology.OverlapTolerance), |
| | 554 | 595 | | ActiveGrids, |
| | 554 | 596 | | _gridCandidates); |
| | | 597 | | |
| | 2398 | 598 | | for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++) |
| | | 599 | | { |
| | 645 | 600 | | ushort neighborIndex = _gridCandidates[candidateIndex]; |
| | 645 | 601 | | if (neighborIndex == allocatedIndex) |
| | | 602 | | continue; |
| | | 603 | | |
| | 91 | 604 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 91 | 605 | | newGrid.TryAddGridNeighbor(neighborGrid); |
| | 91 | 606 | | neighborGrid.TryAddGridNeighbor(newGrid); |
| | | 607 | | } |
| | 554 | 608 | | } |
| | | 609 | | |
| | | 610 | | private void UnregisterGrid(VoxelGrid gridToRemove, ushort removeIndex) |
| | | 611 | | { |
| | 41 | 612 | | _spatialIndex.Remove(removeIndex); |
| | 41 | 613 | | UnlinkGridNeighbors(gridToRemove); |
| | 41 | 614 | | } |
| | | 615 | | |
| | | 616 | | private void UnlinkGridNeighbors(VoxelGrid gridToRemove) |
| | | 617 | | { |
| | 41 | 618 | | if (!gridToRemove.IsConjoined) |
| | 29 | 619 | | return; |
| | | 620 | | |
| | 12 | 621 | | var neighborSets = gridToRemove.Neighbors!.DenseValues; |
| | 12 | 622 | | int neighborSetCount = gridToRemove.Neighbors.Count; |
| | 54 | 623 | | for (int neighborSetIndex = 0; neighborSetIndex < neighborSetCount; neighborSetIndex++) |
| | | 624 | | { |
| | 70 | 625 | | foreach (int neighborIndex in neighborSets[neighborSetIndex]) |
| | | 626 | | { |
| | 20 | 627 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 20 | 628 | | neighborGrid.TryRemoveGridNeighbor(gridToRemove); |
| | | 629 | | } |
| | | 630 | | } |
| | 12 | 631 | | } |
| | | 632 | | |
| | | 633 | | internal void CollectGridCandidates( |
| | | 634 | | Vector3d boundsMin, |
| | | 635 | | Vector3d boundsMax, |
| | | 636 | | SwiftList<ushort> candidates) => |
| | 869 | 637 | | _spatialIndex.CollectCandidates( |
| | 869 | 638 | | new FixedBoundVolume(boundsMin, boundsMax), |
| | 869 | 639 | | ActiveGrids, |
| | 869 | 640 | | candidates); |
| | | 641 | | |
| | | 642 | | private static FixedBoundVolume CreateExpandedBounds( |
| | | 643 | | Vector3d boundsMin, |
| | | 644 | | Vector3d boundsMax, |
| | | 645 | | Fixed64 padding) |
| | | 646 | | { |
| | 558 | 647 | | Vector3d expansion = new(padding, padding, padding); |
| | 558 | 648 | | return new FixedBoundVolume(boundsMin - expansion, boundsMax + expansion); |
| | | 649 | | } |
| | | 650 | | |
| | | 651 | | #region Lookup |
| | | 652 | | |
| | | 653 | | /// <summary> |
| | | 654 | | /// Retrieves a grid by its world-local index. |
| | | 655 | | /// </summary> |
| | | 656 | | /// <param name="index">The world-local grid slot to resolve.</param> |
| | | 657 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 658 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 659 | | public bool TryGetGrid(int index, out VoxelGrid? outGrid) |
| | | 660 | | { |
| | 1426 | 661 | | outGrid = null; |
| | 1426 | 662 | | if (!CanResolveGrid(index)) |
| | 17 | 663 | | return false; |
| | | 664 | | |
| | 1409 | 665 | | outGrid = ActiveGrids[index]; |
| | 1409 | 666 | | return true; |
| | | 667 | | } |
| | | 668 | | |
| | | 669 | | /// <summary> |
| | | 670 | | /// Retrieves the grid containing a given world position. |
| | | 671 | | /// </summary> |
| | | 672 | | /// <param name="position">The world position to resolve.</param> |
| | | 673 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 674 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 675 | | public bool TryGetGrid(Vector3d position, out VoxelGrid? outGrid) |
| | | 676 | | { |
| | 154 | 677 | | outGrid = null; |
| | 154 | 678 | | if (!CanResolvePosition()) |
| | 2 | 679 | | return false; |
| | | 680 | | |
| | 152 | 681 | | _spatialIndex.CollectPointCandidates(position, _gridCandidates); |
| | 152 | 682 | | if (TryGetContainingGrid(position, _gridCandidates, out outGrid)) |
| | 64 | 683 | | return true; |
| | | 684 | | |
| | 88 | 685 | | GridForgeLogger.Channel.Info($"No grid contains position {position}."); |
| | 88 | 686 | | return false; |
| | | 687 | | } |
| | | 688 | | |
| | | 689 | | /// <summary> |
| | | 690 | | /// Retrieves the grid containing a 2D XZ-plane world position on the default world Y layer. |
| | | 691 | | /// </summary> |
| | | 692 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 693 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 694 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 695 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 696 | | public bool TryGetGrid(Vector2d position, out VoxelGrid? outGrid) => |
| | 1 | 697 | | TryGetGrid(position, default, out outGrid); |
| | | 698 | | |
| | | 699 | | /// <summary> |
| | | 700 | | /// Retrieves the grid containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 701 | | /// </summary> |
| | | 702 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 703 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 704 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 705 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 706 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 707 | | public bool TryGetGrid(Vector2d position, Fixed64 layerY, out VoxelGrid? outGrid) => |
| | 3 | 708 | | TryGetGrid(GridPlane2d.ToWorld(position, layerY), out outGrid); |
| | | 709 | | |
| | | 710 | | /// <summary> |
| | | 711 | | /// Retrieves the active grid whose bounds are nearest to the supplied world position. |
| | | 712 | | /// </summary> |
| | | 713 | | /// <param name="position">The world position to resolve.</param> |
| | | 714 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 715 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 716 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 717 | | public bool TryGetClosestGrid( |
| | | 718 | | Vector3d position, |
| | | 719 | | out VoxelGrid? outGrid, |
| | | 720 | | GridTopologyKind? topologyKind = null) |
| | | 721 | | { |
| | 27 | 722 | | outGrid = null; |
| | 27 | 723 | | if (!CanResolveActiveGrid()) |
| | 1 | 724 | | return false; |
| | | 725 | | |
| | 26 | 726 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 124 | 727 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 728 | | { |
| | 36 | 729 | | if (!candidateGrid.IsActive |
| | 36 | 730 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 731 | | { |
| | | 732 | | continue; |
| | | 733 | | } |
| | | 734 | | |
| | 30 | 735 | | Fixed64 distanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid.Bounds |
| | 30 | 736 | | if (outGrid == null || distanceSquared < closestDistanceSquared) |
| | | 737 | | { |
| | 23 | 738 | | outGrid = candidateGrid; |
| | 23 | 739 | | closestDistanceSquared = distanceSquared; |
| | | 740 | | } |
| | | 741 | | } |
| | | 742 | | |
| | 26 | 743 | | return outGrid != null; |
| | | 744 | | } |
| | | 745 | | |
| | | 746 | | /// <summary> |
| | | 747 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the default world Y layer. |
| | | 748 | | /// </summary> |
| | | 749 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 750 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 751 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 752 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 753 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 754 | | public bool TryGetClosestGrid( |
| | | 755 | | Vector2d position, |
| | | 756 | | out VoxelGrid? outGrid, |
| | | 757 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 758 | | TryGetClosestGrid(position, default, out outGrid, topologyKind); |
| | | 759 | | |
| | | 760 | | /// <summary> |
| | | 761 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the supplied world Y layer |
| | | 762 | | /// </summary> |
| | | 763 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 764 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 765 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 766 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 767 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 768 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 769 | | public bool TryGetClosestGrid( |
| | | 770 | | Vector2d position, |
| | | 771 | | Fixed64 layerY, |
| | | 772 | | out VoxelGrid? outGrid, |
| | | 773 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 774 | | TryGetClosestGrid(GridPlane2d.ToWorld(position, layerY), out outGrid, topologyKind); |
| | | 775 | | |
| | | 776 | | /// <summary> |
| | | 777 | | /// Retrieves a grid by a world-scoped voxel identity. |
| | | 778 | | /// </summary> |
| | | 779 | | /// <param name="worldVoxelIndex">The voxel identity whose grid should be resolved.</param> |
| | | 780 | | /// <param name="result">The resolved grid, if found.</param> |
| | | 781 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 782 | | public bool TryGetGrid(WorldVoxelIndex worldVoxelIndex, out VoxelGrid? result) |
| | | 783 | | { |
| | 1131 | 784 | | result = null; |
| | 1131 | 785 | | if (worldVoxelIndex.WorldSpawnToken != SpawnToken |
| | 1131 | 786 | | || !TryGetGrid(worldVoxelIndex.GridIndex, out VoxelGrid? resolvedGrid) |
| | 1131 | 787 | | || worldVoxelIndex.GridSpawnToken != resolvedGrid!.SpawnToken) |
| | | 788 | | { |
| | 22 | 789 | | return false; |
| | | 790 | | } |
| | | 791 | | |
| | 1109 | 792 | | result = resolvedGrid; |
| | 1109 | 793 | | return true; |
| | | 794 | | } |
| | | 795 | | |
| | | 796 | | /// <summary> |
| | | 797 | | /// Retrieves the grid and voxel containing a given world position. |
| | | 798 | | /// </summary> |
| | | 799 | | /// <param name="position">The world position to resolve.</param> |
| | | 800 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 801 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 802 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 803 | | public bool TryGetGridAndVoxel( |
| | | 804 | | Vector3d position, |
| | | 805 | | out VoxelGrid? outGrid, |
| | | 806 | | out Voxel? outVoxel) |
| | | 807 | | { |
| | 28 | 808 | | outVoxel = null; |
| | 28 | 809 | | return TryGetGrid(position, out outGrid) |
| | 28 | 810 | | && outGrid!.TryGetVoxel(position, out outVoxel); |
| | | 811 | | } |
| | | 812 | | |
| | | 813 | | /// <summary> |
| | | 814 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the default world Y layer. |
| | | 815 | | /// </summary> |
| | | 816 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 817 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 818 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 819 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 820 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 821 | | public bool TryGetGridAndVoxel( |
| | | 822 | | Vector2d position, |
| | | 823 | | out VoxelGrid? outGrid, |
| | | 824 | | out Voxel? outVoxel) => |
| | 1 | 825 | | TryGetGridAndVoxel(position, default, out outGrid, out outVoxel); |
| | | 826 | | |
| | | 827 | | /// <summary> |
| | | 828 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 829 | | /// </summary> |
| | | 830 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 831 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 832 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 833 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 834 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 835 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 836 | | public bool TryGetGridAndVoxel( |
| | | 837 | | Vector2d position, |
| | | 838 | | Fixed64 layerY, |
| | | 839 | | out VoxelGrid? outGrid, |
| | | 840 | | out Voxel? outVoxel) => |
| | 3 | 841 | | TryGetGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel); |
| | | 842 | | |
| | | 843 | | /// <summary> |
| | | 844 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position and the grid that owns it. |
| | | 845 | | /// Sparse grids only consider configured physical voxels. |
| | | 846 | | /// </summary> |
| | | 847 | | /// <param name="position">The world position to resolve.</param> |
| | | 848 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 849 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 850 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 851 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 852 | | public bool TryGetClosestGridAndVoxel( |
| | | 853 | | Vector3d position, |
| | | 854 | | out VoxelGrid? outGrid, |
| | | 855 | | out Voxel? outVoxel, |
| | | 856 | | GridTopologyKind? topologyKind = null) |
| | | 857 | | { |
| | 16 | 858 | | outGrid = null; |
| | 16 | 859 | | outVoxel = null; |
| | 16 | 860 | | if (!CanResolveActiveGrid()) |
| | 2 | 861 | | return false; |
| | | 862 | | |
| | 14 | 863 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 14 | 864 | | if (TryGetClosestGrid(position, out VoxelGrid? closestBoundsGrid, topologyKind) |
| | 14 | 865 | | && closestBoundsGrid!.ConfiguredVoxelCount != 0) |
| | | 866 | | { |
| | 10 | 867 | | bool resolved = closestBoundsGrid.TryGetClosestVoxel( |
| | 10 | 868 | | position, |
| | 10 | 869 | | out outVoxel, |
| | 10 | 870 | | out closestDistanceSquared); |
| | | 871 | | Debug.Assert(resolved); |
| | 10 | 872 | | outGrid = closestBoundsGrid; |
| | | 873 | | } |
| | | 874 | | |
| | 66 | 875 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 876 | | { |
| | 19 | 877 | | if (candidateGrid == null |
| | 19 | 878 | | || !candidateGrid.IsActive |
| | 19 | 879 | | || candidateGrid.ConfiguredVoxelCount == 0 |
| | 19 | 880 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 881 | | { |
| | | 882 | | continue; |
| | | 883 | | } |
| | 14 | 884 | | if (ReferenceEquals(candidateGrid, outGrid)) |
| | | 885 | | continue; |
| | | 886 | | |
| | 5 | 887 | | Fixed64 boundsDistanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid. |
| | 5 | 888 | | if (outVoxel != null && boundsDistanceSquared > closestDistanceSquared) |
| | | 889 | | continue; |
| | | 890 | | |
| | 4 | 891 | | candidateGrid.TryGetClosestVoxel( |
| | 4 | 892 | | position, |
| | 4 | 893 | | out Voxel? candidateVoxel, |
| | 4 | 894 | | out Fixed64 candidateDistanceSquared); |
| | | 895 | | |
| | 4 | 896 | | if (IsBetterClosestVoxel( |
| | 4 | 897 | | candidateDistanceSquared, |
| | 4 | 898 | | candidateGrid, |
| | 4 | 899 | | candidateVoxel!, |
| | 4 | 900 | | closestDistanceSquared, |
| | 4 | 901 | | outGrid, |
| | 4 | 902 | | outVoxel)) |
| | | 903 | | { |
| | 3 | 904 | | outGrid = candidateGrid; |
| | 3 | 905 | | outVoxel = candidateVoxel; |
| | 3 | 906 | | closestDistanceSquared = candidateDistanceSquared; |
| | | 907 | | } |
| | | 908 | | } |
| | | 909 | | |
| | 14 | 910 | | return outVoxel != null; |
| | | 911 | | } |
| | | 912 | | |
| | | 913 | | /// <summary> |
| | | 914 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 915 | | /// Sparse grids only consider configured physical voxels. |
| | | 916 | | /// </summary> |
| | | 917 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 918 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 919 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 920 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 921 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 922 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 923 | | public bool TryGetClosestGridAndVoxel( |
| | | 924 | | Vector2d position, |
| | | 925 | | out VoxelGrid? outGrid, |
| | | 926 | | out Voxel? outVoxel, |
| | | 927 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 928 | | TryGetClosestGridAndVoxel(position, default, out outGrid, out outVoxel, topologyKind); |
| | | 929 | | |
| | | 930 | | /// <summary> |
| | | 931 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 932 | | /// Sparse grids only consider configured physical voxels. |
| | | 933 | | /// </summary> |
| | | 934 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 935 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 936 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 937 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 938 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 939 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 940 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 941 | | public bool TryGetClosestGridAndVoxel( |
| | | 942 | | Vector2d position, |
| | | 943 | | Fixed64 layerY, |
| | | 944 | | out VoxelGrid? outGrid, |
| | | 945 | | out Voxel? outVoxel, |
| | | 946 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 947 | | TryGetClosestGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel, topologyKind); |
| | | 948 | | |
| | | 949 | | /// <summary> |
| | | 950 | | /// Retrieves the grid and voxel for a given voxel identity. |
| | | 951 | | /// </summary> |
| | | 952 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 953 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 954 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 955 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 956 | | public bool TryGetGridAndVoxel( |
| | | 957 | | WorldVoxelIndex worldVoxelIndex, |
| | | 958 | | out VoxelGrid? outGrid, |
| | | 959 | | out Voxel? result) |
| | | 960 | | { |
| | 70 | 961 | | result = null; |
| | 70 | 962 | | return TryGetGrid(worldVoxelIndex, out outGrid) |
| | 70 | 963 | | && outGrid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 964 | | } |
| | | 965 | | |
| | | 966 | | /// <summary> |
| | | 967 | | /// Retrieves a voxel from a world position. |
| | | 968 | | /// </summary> |
| | | 969 | | /// <param name="position">The world position to resolve.</param> |
| | | 970 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 971 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 972 | | public bool TryGetVoxel( |
| | | 973 | | Vector3d position, |
| | | 974 | | out Voxel? result) |
| | | 975 | | { |
| | 101 | 976 | | result = null; |
| | 101 | 977 | | return TryGetGrid(position, out VoxelGrid? grid) |
| | 101 | 978 | | && grid!.TryGetVoxel(position, out result); |
| | | 979 | | } |
| | | 980 | | |
| | | 981 | | /// <summary> |
| | | 982 | | /// Retrieves a voxel from a 2D XZ-plane world position on the default world Y layer. |
| | | 983 | | /// </summary> |
| | | 984 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 985 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 986 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 987 | | public bool TryGetVoxel( |
| | | 988 | | Vector2d position, |
| | | 989 | | out Voxel? result) |
| | | 990 | | { |
| | 1 | 991 | | return TryGetVoxel(position, default, out result); |
| | | 992 | | } |
| | | 993 | | |
| | | 994 | | /// <summary> |
| | | 995 | | /// Retrieves a voxel from a 2D XZ-plane world position on the supplied world Y layer. |
| | | 996 | | /// </summary> |
| | | 997 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 998 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 999 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 1000 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 1001 | | public bool TryGetVoxel( |
| | | 1002 | | Vector2d position, |
| | | 1003 | | Fixed64 layerY, |
| | | 1004 | | out Voxel? result) |
| | | 1005 | | { |
| | 3 | 1006 | | return TryGetVoxel(GridPlane2d.ToWorld(position, layerY), out result); |
| | | 1007 | | } |
| | | 1008 | | |
| | | 1009 | | /// <summary> |
| | | 1010 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position. |
| | | 1011 | | /// Sparse grids only consider configured physical voxels. |
| | | 1012 | | /// </summary> |
| | | 1013 | | /// <param name="position">The world position to resolve.</param> |
| | | 1014 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 1015 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1016 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1017 | | public bool TryGetClosestVoxel( |
| | | 1018 | | Vector3d position, |
| | | 1019 | | out Voxel? result, |
| | | 1020 | | GridTopologyKind? topologyKind = null) |
| | | 1021 | | { |
| | 6 | 1022 | | result = null; |
| | 6 | 1023 | | if (!TryGetClosestGridAndVoxel(position, out _, out Voxel? closestVoxel, topologyKind)) |
| | 2 | 1024 | | return false; |
| | | 1025 | | |
| | 4 | 1026 | | result = closestVoxel; |
| | 4 | 1027 | | return true; |
| | | 1028 | | } |
| | | 1029 | | |
| | | 1030 | | /// <summary> |
| | | 1031 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 1032 | | /// Sparse grids only consider configured physical voxels. |
| | | 1033 | | /// </summary> |
| | | 1034 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1035 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 1036 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1037 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1038 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1039 | | public bool TryGetClosestVoxel( |
| | | 1040 | | Vector2d position, |
| | | 1041 | | out Voxel? result, |
| | | 1042 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 1043 | | TryGetClosestVoxel(position, default, out result, topologyKind); |
| | | 1044 | | |
| | | 1045 | | /// <summary> |
| | | 1046 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 1047 | | /// Sparse grids only consider configured physical voxels. |
| | | 1048 | | /// </summary> |
| | | 1049 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1050 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 1051 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 1052 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1053 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1054 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1055 | | public bool TryGetClosestVoxel( |
| | | 1056 | | Vector2d position, |
| | | 1057 | | Fixed64 layerY, |
| | | 1058 | | out Voxel? result, |
| | | 1059 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 1060 | | TryGetClosestVoxel(GridPlane2d.ToWorld(position, layerY), out result, topologyKind); |
| | | 1061 | | |
| | | 1062 | | /// <summary> |
| | | 1063 | | /// Retrieves a voxel from a world-scoped voxel identity. |
| | | 1064 | | /// </summary> |
| | | 1065 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 1066 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 1067 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 1068 | | public bool TryGetVoxel( |
| | | 1069 | | WorldVoxelIndex worldVoxelIndex, |
| | | 1070 | | out Voxel? result) |
| | | 1071 | | { |
| | 3 | 1072 | | result = null; |
| | 3 | 1073 | | return TryGetGrid(worldVoxelIndex, out VoxelGrid? grid) |
| | 3 | 1074 | | && grid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 1075 | | } |
| | | 1076 | | |
| | | 1077 | | #endregion |
| | | 1078 | | |
| | | 1079 | | #region Internal Helpers |
| | | 1080 | | |
| | | 1081 | | internal static bool TryNormalizeConfiguration( |
| | | 1082 | | GridConfiguration configuration, |
| | | 1083 | | out GridConfiguration normalizedConfiguration, |
| | | 1084 | | out IGridTopology topology, |
| | | 1085 | | out GridDimensions dimensions) |
| | | 1086 | | { |
| | 586 | 1087 | | normalizedConfiguration = default; |
| | 586 | 1088 | | topology = null!; |
| | 586 | 1089 | | dimensions = default; |
| | 586 | 1090 | | if (!GridTopologyFactory.TryCreate(configuration, out IGridTopology? createdTopology)) |
| | 11 | 1091 | | return false; |
| | | 1092 | | |
| | 575 | 1093 | | (Vector3d boundsMin, Vector3d boundsMax) = |
| | 575 | 1094 | | createdTopology!.NormalizeBounds(configuration.BoundsMin, configuration.BoundsMax); |
| | | 1095 | | |
| | 575 | 1096 | | normalizedConfiguration = new GridConfiguration( |
| | 575 | 1097 | | boundsMin, |
| | 575 | 1098 | | boundsMax, |
| | 575 | 1099 | | configuration.ScanCellSize, |
| | 575 | 1100 | | configuration.TopologyKind, |
| | 575 | 1101 | | configuration.TopologyMetrics, |
| | 575 | 1102 | | configuration.StorageKind); |
| | 575 | 1103 | | topology = createdTopology; |
| | 575 | 1104 | | dimensions = topology.CalculateDimensions(boundsMin, boundsMax); |
| | 575 | 1105 | | return true; |
| | | 1106 | | } |
| | | 1107 | | |
| | | 1108 | | /// <summary> |
| | | 1109 | | /// Increments the version of the specified grid and optionally the world version. |
| | | 1110 | | /// </summary> |
| | | 1111 | | public void IncrementGridVersion(int index, bool significant = false) |
| | | 1112 | | { |
| | 5 | 1113 | | if (!IsActive) |
| | | 1114 | | { |
| | 3 | 1115 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot increment grid versions."); |
| | 3 | 1116 | | return; |
| | | 1117 | | } |
| | | 1118 | | |
| | 2 | 1119 | | _gridLock.EnterWriteLock(); |
| | | 1120 | | try |
| | | 1121 | | { |
| | 2 | 1122 | | if (significant) |
| | 1 | 1123 | | Version++; |
| | | 1124 | | |
| | 2 | 1125 | | if (ActiveGrids.IsAllocated(index)) |
| | 1 | 1126 | | ActiveGrids[index].IncrementVersion(); |
| | 2 | 1127 | | } |
| | | 1128 | | finally |
| | | 1129 | | { |
| | 2 | 1130 | | _gridLock.ExitWriteLock(); |
| | 2 | 1131 | | } |
| | 2 | 1132 | | } |
| | | 1133 | | |
| | | 1134 | | /// <summary> |
| | | 1135 | | /// Finds active grids in this world that overlap the supplied target grid. |
| | | 1136 | | /// </summary> |
| | | 1137 | | public IEnumerable<VoxelGrid> FindOverlappingGrids(VoxelGrid targetGrid) |
| | | 1138 | | { |
| | 5 | 1139 | | SwiftList<VoxelGrid> overlappingGrids = new(); |
| | 5 | 1140 | | FindOverlappingGridsInto(targetGrid, overlappingGrids); |
| | 5 | 1141 | | return overlappingGrids; |
| | | 1142 | | } |
| | | 1143 | | |
| | | 1144 | | /// <summary> |
| | | 1145 | | /// Clears and fills caller-owned storage with active grids that overlap the supplied target grid. |
| | | 1146 | | /// </summary> |
| | | 1147 | | /// <param name="targetGrid">The grid whose expanded topology bounds define the overlap query.</param> |
| | | 1148 | | /// <param name="results">Caller-owned storage cleared and filled in ascending grid-slot order.</param> |
| | | 1149 | | public void FindOverlappingGridsInto(VoxelGrid targetGrid, SwiftList<VoxelGrid> results) |
| | | 1150 | | { |
| | 7 | 1151 | | SwiftThrowHelper.ThrowIfNull(targetGrid, nameof(targetGrid)); |
| | 7 | 1152 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | | 1153 | | |
| | 7 | 1154 | | results.Clear(); |
| | | 1155 | | |
| | 7 | 1156 | | if (!IsActive) |
| | | 1157 | | { |
| | 3 | 1158 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve overlaps."); |
| | 3 | 1159 | | return; |
| | | 1160 | | } |
| | | 1161 | | |
| | 4 | 1162 | | _spatialIndex.CollectCandidates( |
| | 4 | 1163 | | CreateExpandedBounds( |
| | 4 | 1164 | | targetGrid.BoundsMin, |
| | 4 | 1165 | | targetGrid.BoundsMax, |
| | 4 | 1166 | | targetGrid.Topology.OverlapTolerance), |
| | 4 | 1167 | | ActiveGrids, |
| | 4 | 1168 | | _gridCandidates); |
| | 26 | 1169 | | for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++) |
| | 9 | 1170 | | TryAddOverlappingGrid(targetGrid, _gridCandidates[candidateIndex], results); |
| | 4 | 1171 | | } |
| | | 1172 | | |
| | | 1173 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1174 | | private static bool MatchesTopologyKind(VoxelGrid grid, GridTopologyKind? topologyKind) => |
| | 53 | 1175 | | !topologyKind.HasValue || grid.TopologyKind == topologyKind.Value; |
| | | 1176 | | |
| | | 1177 | | private static bool IsBetterClosestVoxel( |
| | | 1178 | | Fixed64 candidateDistanceSquared, |
| | | 1179 | | VoxelGrid candidateGrid, |
| | | 1180 | | Voxel candidateVoxel, |
| | | 1181 | | Fixed64 closestDistanceSquared, |
| | | 1182 | | VoxelGrid? closestGrid, |
| | | 1183 | | Voxel? closestVoxel) |
| | | 1184 | | { |
| | 4 | 1185 | | if (closestVoxel == null || closestGrid == null) |
| | 1 | 1186 | | return true; |
| | | 1187 | | |
| | 3 | 1188 | | if (candidateDistanceSquared != closestDistanceSquared) |
| | 1 | 1189 | | return candidateDistanceSquared < closestDistanceSquared; |
| | | 1190 | | |
| | 2 | 1191 | | return candidateGrid.GridIndex < closestGrid.GridIndex; |
| | | 1192 | | } |
| | | 1193 | | |
| | | 1194 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1195 | | private static Fixed64 GetDistanceSquaredToBounds(Vector3d position, Vector3d boundsMin, Vector3d boundsMax) |
| | | 1196 | | { |
| | 35 | 1197 | | Fixed64 x = GetAxisDistanceToBounds(position.X, boundsMin.X, boundsMax.X); |
| | 35 | 1198 | | Fixed64 y = GetAxisDistanceToBounds(position.Y, boundsMin.Y, boundsMax.Y); |
| | 35 | 1199 | | Fixed64 z = GetAxisDistanceToBounds(position.Z, boundsMin.Z, boundsMax.Z); |
| | 35 | 1200 | | return x * x + y * y + z * z; |
| | | 1201 | | } |
| | | 1202 | | |
| | | 1203 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1204 | | private static Fixed64 GetAxisDistanceToBounds(Fixed64 coordinate, Fixed64 min, Fixed64 max) |
| | | 1205 | | { |
| | 105 | 1206 | | if (coordinate < min) |
| | 17 | 1207 | | return min - coordinate; |
| | | 1208 | | |
| | 88 | 1209 | | return coordinate > max ? coordinate - max : Fixed64.Zero; |
| | | 1210 | | } |
| | | 1211 | | |
| | | 1212 | | private bool CanResolveGrid(int index) |
| | | 1213 | | { |
| | 1426 | 1214 | | if (!CanResolveActiveGrid()) |
| | 2 | 1215 | | return false; |
| | | 1216 | | |
| | 1424 | 1217 | | if (!IsGridIndexInActiveRange(index)) |
| | | 1218 | | { |
| | 7 | 1219 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' is out-of-bounds for ActiveGrids."); |
| | 7 | 1220 | | return false; |
| | | 1221 | | } |
| | | 1222 | | |
| | 1417 | 1223 | | return IsGridIndexAllocated(index); |
| | | 1224 | | } |
| | | 1225 | | |
| | | 1226 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1227 | | private bool CanResolveActiveGrid() |
| | | 1228 | | { |
| | 1469 | 1229 | | if (IsActive) |
| | 1464 | 1230 | | return true; |
| | | 1231 | | |
| | 5 | 1232 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve grids."); |
| | 5 | 1233 | | return false; |
| | | 1234 | | } |
| | | 1235 | | |
| | | 1236 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1237 | | private bool IsGridIndexInActiveRange(int index) => |
| | 1424 | 1238 | | (uint)index < MaxGrids && (uint)index <= ActiveGrids.Count; |
| | | 1239 | | |
| | | 1240 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1241 | | private bool IsGridIndexAllocated(int index) |
| | | 1242 | | { |
| | 1417 | 1243 | | if (ActiveGrids.IsAllocated(index)) |
| | 1409 | 1244 | | return true; |
| | | 1245 | | |
| | 8 | 1246 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' has not been allocated to ActiveGrids."); |
| | 8 | 1247 | | return false; |
| | | 1248 | | } |
| | | 1249 | | |
| | | 1250 | | private bool CanResolvePosition() |
| | | 1251 | | { |
| | 154 | 1252 | | if (IsActive) |
| | 152 | 1253 | | return true; |
| | | 1254 | | |
| | 2 | 1255 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve positions."); |
| | 2 | 1256 | | return false; |
| | | 1257 | | } |
| | | 1258 | | |
| | | 1259 | | private bool TryGetContainingGrid( |
| | | 1260 | | Vector3d position, |
| | | 1261 | | SwiftList<ushort> gridList, |
| | | 1262 | | out VoxelGrid? outGrid) |
| | | 1263 | | { |
| | 152 | 1264 | | outGrid = null; |
| | | 1265 | | |
| | 352 | 1266 | | for (int index = 0; index < gridList.Count; index++) |
| | | 1267 | | { |
| | 88 | 1268 | | ushort candidateIndex = gridList[index]; |
| | 88 | 1269 | | VoxelGrid candidateGrid = ActiveGrids[candidateIndex]; |
| | 88 | 1270 | | if (candidateGrid.IsInBounds(position)) |
| | | 1271 | | { |
| | 64 | 1272 | | outGrid = candidateGrid; |
| | 64 | 1273 | | return true; |
| | | 1274 | | } |
| | | 1275 | | } |
| | | 1276 | | |
| | 88 | 1277 | | return false; |
| | | 1278 | | } |
| | | 1279 | | |
| | | 1280 | | private void TryAddOverlappingGrid( |
| | | 1281 | | VoxelGrid targetGrid, |
| | | 1282 | | ushort neighborIndex, |
| | | 1283 | | SwiftList<VoxelGrid> overlappingGrids) |
| | | 1284 | | { |
| | 9 | 1285 | | if (neighborIndex == targetGrid.GridIndex) |
| | 4 | 1286 | | return; |
| | | 1287 | | |
| | 5 | 1288 | | overlappingGrids.Add(ActiveGrids[neighborIndex]); |
| | 5 | 1289 | | } |
| | | 1290 | | |
| | | 1291 | | internal void NotifyActiveGridChange(VoxelGrid? grid) |
| | | 1292 | | { |
| | 1659 | 1293 | | if (grid == null || !grid.IsActive) |
| | 4 | 1294 | | return; |
| | | 1295 | | |
| | 1655 | 1296 | | NotifyActiveGridChange(CreateGridEventInfo(grid, GridEventKind.GridChanged)); |
| | 1655 | 1297 | | } |
| | | 1298 | | |
| | | 1299 | | internal void NotifyActiveGridChange( |
| | | 1300 | | VoxelGrid? grid, |
| | | 1301 | | GridEventKind changeKind, |
| | | 1302 | | VoxelIndex voxelIndex, |
| | | 1303 | | Vector3d affectedPosition) |
| | | 1304 | | { |
| | 48 | 1305 | | if (grid == null || !grid.IsActive) |
| | 2 | 1306 | | return; |
| | | 1307 | | |
| | 46 | 1308 | | NotifyActiveGridChange(CreateGridEventInfo(grid, changeKind, voxelIndex, affectedPosition, affectedPosition)); |
| | 46 | 1309 | | } |
| | | 1310 | | |
| | | 1311 | | #endregion |
| | | 1312 | | |
| | | 1313 | | #region Private Helpers |
| | | 1314 | | |
| | | 1315 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1316 | | private static int ResolveSpatialGridCellSize(int spatialGridCellSize) |
| | | 1317 | | { |
| | 537 | 1318 | | if (spatialGridCellSize <= 0) |
| | | 1319 | | { |
| | 3 | 1320 | | GridForgeLogger.Channel.Warn($"Spatial grid cell size must be greater than zero. Falling back to default siz |
| | 3 | 1321 | | return DefaultSpatialGridCellSize; |
| | | 1322 | | } |
| | | 1323 | | |
| | 534 | 1324 | | return spatialGridCellSize; |
| | | 1325 | | } |
| | | 1326 | | |
| | | 1327 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1328 | | private GridEventInfo CreateGridEventInfo(VoxelGrid grid, GridEventKind changeKind) => |
| | 2250 | 1329 | | new( |
| | 2250 | 1330 | | SpawnToken, |
| | 2250 | 1331 | | grid.GridIndex, |
| | 2250 | 1332 | | grid.SpawnToken, |
| | 2250 | 1333 | | grid.Configuration, |
| | 2250 | 1334 | | grid.Version, |
| | 2250 | 1335 | | changeKind, |
| | 2250 | 1336 | | default, |
| | 2250 | 1337 | | grid.BoundsMin, |
| | 2250 | 1338 | | grid.BoundsMax); |
| | | 1339 | | |
| | | 1340 | | private GridEventInfo CreateGridEventInfo( |
| | | 1341 | | VoxelGrid grid, |
| | | 1342 | | GridEventKind changeKind, |
| | | 1343 | | VoxelIndex voxelIndex, |
| | | 1344 | | Vector3d affectedBoundsMin, |
| | | 1345 | | Vector3d affectedBoundsMax) => |
| | 46 | 1346 | | new( |
| | 46 | 1347 | | SpawnToken, |
| | 46 | 1348 | | grid.GridIndex, |
| | 46 | 1349 | | grid.SpawnToken, |
| | 46 | 1350 | | grid.Configuration, |
| | 46 | 1351 | | grid.Version, |
| | 46 | 1352 | | changeKind, |
| | 46 | 1353 | | voxelIndex, |
| | 46 | 1354 | | affectedBoundsMin, |
| | 46 | 1355 | | affectedBoundsMax); |
| | | 1356 | | |
| | | 1357 | | private void NotifyActiveGridAdded(GridEventInfo eventInfo) |
| | | 1358 | | { |
| | 554 | 1359 | | Action<GridEventInfo>? handlers = _onActiveGridAdded; |
| | 554 | 1360 | | if (handlers == null) |
| | 543 | 1361 | | return; |
| | | 1362 | | |
| | 11 | 1363 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 48 | 1364 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1365 | | { |
| | | 1366 | | try |
| | | 1367 | | { |
| | 13 | 1368 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 12 | 1369 | | } |
| | 1 | 1370 | | catch (Exception ex) |
| | | 1371 | | { |
| | 1 | 1372 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] added notification error: {ex.Message}"); |
| | 1 | 1373 | | } |
| | | 1374 | | } |
| | 11 | 1375 | | } |
| | | 1376 | | |
| | | 1377 | | private void NotifyActiveGridRemoved(GridEventInfo eventInfo) |
| | | 1378 | | { |
| | 41 | 1379 | | Action<GridEventInfo>? handlers = _onActiveGridRemoved; |
| | 41 | 1380 | | if (handlers == null) |
| | 33 | 1381 | | return; |
| | | 1382 | | |
| | 8 | 1383 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 36 | 1384 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1385 | | { |
| | | 1386 | | try |
| | | 1387 | | { |
| | 10 | 1388 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 9 | 1389 | | } |
| | 1 | 1390 | | catch (Exception ex) |
| | | 1391 | | { |
| | 1 | 1392 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] removed notification error: {ex.Message}"); |
| | 1 | 1393 | | } |
| | | 1394 | | } |
| | 8 | 1395 | | } |
| | | 1396 | | |
| | | 1397 | | private void NotifyActiveGridChange(GridEventInfo eventInfo) |
| | | 1398 | | { |
| | 1701 | 1399 | | Action<GridEventInfo>? handlers = _onActiveGridChange; |
| | 1701 | 1400 | | if (handlers == null) |
| | 878 | 1401 | | return; |
| | | 1402 | | |
| | 823 | 1403 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 43704 | 1404 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1405 | | { |
| | | 1406 | | try |
| | | 1407 | | { |
| | 21029 | 1408 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 21027 | 1409 | | } |
| | 2 | 1410 | | catch (Exception ex) |
| | | 1411 | | { |
| | 2 | 1412 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] change notification error: {ex.Message}"); |
| | 2 | 1413 | | } |
| | | 1414 | | } |
| | 823 | 1415 | | } |
| | | 1416 | | |
| | | 1417 | | #endregion |
| | | 1418 | | } |