| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | |
| | | 5 | | namespace SwiftCollections.Query; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Represents a Bounding Volume Hierarchy (BVH) optimized for spatial queries. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// <para> |
| | | 12 | | /// This class is not thread-safe. Concurrent access from multiple threads must be |
| | | 13 | | /// serialized externally (e.g., with a lock or by limiting access to a single thread). |
| | | 14 | | /// </para> |
| | | 15 | | /// </remarks> |
| | | 16 | | public class SwiftBVH<TKey, TVolume> |
| | | 17 | | where TKey : notnull |
| | | 18 | | where TVolume : struct, IBoundVolume<TVolume> |
| | | 19 | | { |
| | | 20 | | #region Static & Constants |
| | | 21 | | |
| | | 22 | | private const string _diagnosticSource = nameof(SwiftBVH<TKey, TVolume>); |
| | | 23 | | |
| | | 24 | | #endregion |
| | | 25 | | |
| | | 26 | | #region Fields |
| | | 27 | | |
| | | 28 | | private SwiftBVHNode<TKey, TVolume>[] _nodePool; |
| | | 29 | | private int _peakIndex; |
| | | 30 | | private int _leafCount; |
| | | 31 | | |
| | | 32 | | private readonly QueryKeyIndexMap<TKey> _keyToNodeIndex; |
| | 37 | 33 | | private readonly QueryTraversalScratch _queryScratch = new(); |
| | | 34 | | |
| | 37 | 35 | | private readonly SwiftIntStack _freeIndices = new(); |
| | | 36 | | |
| | | 37 | | private int _rootNodeIndex; |
| | | 38 | | |
| | | 39 | | #endregion |
| | | 40 | | |
| | | 41 | | #region Constructor |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Initializes a new instance of the <see cref="SwiftBVH{TKey, TVolume}"/> class with the specified capacity. |
| | | 45 | | /// </summary> |
| | 37 | 46 | | public SwiftBVH(int capacity) |
| | | 47 | | { |
| | 37 | 48 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 37 | 49 | | _nodePool = new SwiftBVHNode<TKey, TVolume>[capacity].Populate(() => |
| | 18884 | 50 | | new SwiftBVHNode<TKey, TVolume>() { ParentIndex = -1, LeftChildIndex = -1, RightChildIndex = -1 }); |
| | 37 | 51 | | _keyToNodeIndex = new QueryKeyIndexMap<TKey>(capacity); |
| | | 52 | | |
| | 37 | 53 | | _rootNodeIndex = -1; |
| | | 54 | | |
| | 37 | 55 | | _freeIndices = new SwiftIntStack(SwiftIntStack.DefaultCapacity); |
| | 37 | 56 | | } |
| | | 57 | | |
| | | 58 | | #endregion |
| | | 59 | | |
| | | 60 | | #region Properties |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Gets the underlying pool of nodes used in the BVH. |
| | | 64 | | /// </summary> |
| | 8052 | 65 | | public SwiftBVHNode<TKey, TVolume>[] NodePool => _nodePool; |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Gets the root node of the BVH. |
| | | 69 | | /// </summary> |
| | 6 | 70 | | public SwiftBVHNode<TKey, TVolume> RootNode => _rootNodeIndex >= 0 && _nodePool[_rootNodeIndex].IsAllocated |
| | 6 | 71 | | ? _nodePool[_rootNodeIndex] |
| | 6 | 72 | | : SwiftBVHNode<TKey, TVolume>.Default; |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Gets the index of the root node in the BVH. |
| | | 76 | | /// </summary> |
| | 191 | 77 | | public int RootNodeIndex => _rootNodeIndex; |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// Gets the total number of leaf nodes in the BVH. |
| | | 81 | | /// </summary> |
| | 4 | 82 | | public int Count => _leafCount; |
| | | 83 | | |
| | | 84 | | #endregion |
| | | 85 | | |
| | | 86 | | #region Collection Manipulation |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Allocates a new node with the specified value, bounds, and leaf status. |
| | | 90 | | /// Reuses indices from the freelist when available. |
| | | 91 | | /// </summary> |
| | | 92 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 93 | | private int AllocateNode(TKey value, TVolume bounds, bool isLeaf) |
| | | 94 | | { |
| | | 95 | | int index; |
| | | 96 | | |
| | | 97 | | // Check if there are any reusable indices in the freelist |
| | 26429 | 98 | | if (_freeIndices.Count > 0) |
| | 4 | 99 | | index = _freeIndices.Pop(); // Reuse an available index |
| | | 100 | | else |
| | | 101 | | { |
| | 26425 | 102 | | if (_peakIndex + 1 >= _nodePool.Length) |
| | 25 | 103 | | Resize(_nodePool.Length * 2); |
| | | 104 | | |
| | | 105 | | // Allocate a new index if freelist is empty |
| | 26425 | 106 | | index = _peakIndex++; |
| | | 107 | | } |
| | | 108 | | |
| | 26429 | 109 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 26429 | 110 | | node.Reset(); // Explicit reset |
| | 26429 | 111 | | node.MyIndex = index; |
| | 26429 | 112 | | node.Value = value; |
| | 26429 | 113 | | node.Bounds = bounds; |
| | | 114 | | |
| | 26429 | 115 | | if (isLeaf) |
| | | 116 | | { |
| | 13232 | 117 | | node.IsLeaf = isLeaf; |
| | 13232 | 118 | | node.SubtreeSize = 1; |
| | 13232 | 119 | | _leafCount++; |
| | | 120 | | } |
| | | 121 | | |
| | 26429 | 122 | | node.IsAllocated = true; |
| | | 123 | | |
| | 26429 | 124 | | return index; |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Inserts a bounding volume with an associated value into the BVH. |
| | | 129 | | /// Ensures tree balance and updates hash buckets. |
| | | 130 | | /// </summary> |
| | | 131 | | public bool Insert(TKey value, TVolume bounds) |
| | | 132 | | { |
| | 13232 | 133 | | int newNodeIndex = AllocateNode(value, bounds, true); // Allocate new node as a leaf |
| | 13232 | 134 | | _rootNodeIndex = InsertIntoTree(_rootNodeIndex, newNodeIndex); |
| | 13232 | 135 | | InsertIntoBuckets(value, newNodeIndex); |
| | 13232 | 136 | | return true; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Inserts a node into the tree while maintaining tree balance. |
| | | 141 | | /// Adjusts parent-child relationships as necessary. |
| | | 142 | | /// </summary> |
| | | 143 | | [MethodImpl(MethodImplOptions.NoInlining)] |
| | | 144 | | private int InsertIntoTree(int parentNodeIndex, int newNodeIndex) |
| | | 145 | | { |
| | 151862 | 146 | | if (parentNodeIndex < 0 || !_nodePool[parentNodeIndex].IsAllocated) |
| | 35 | 147 | | return newNodeIndex; |
| | | 148 | | |
| | 151827 | 149 | | if (_nodePool[parentNodeIndex].IsLeaf) |
| | 13197 | 150 | | return CreateParentForLeaves(parentNodeIndex, newNodeIndex); |
| | | 151 | | |
| | 138630 | 152 | | InsertIntoBestChild(parentNodeIndex, newNodeIndex); |
| | 138630 | 153 | | RefreshParentNode(parentNodeIndex); |
| | 138630 | 154 | | return parentNodeIndex; |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | private int CreateParentForLeaves(int existingLeafIndex, int newLeafIndex) |
| | | 158 | | { |
| | 13197 | 159 | | TVolume combinedBounds = _nodePool[existingLeafIndex].Bounds.Union(_nodePool[newLeafIndex].Bounds); |
| | 13197 | 160 | | int oldParentIndex = _nodePool[existingLeafIndex].ParentIndex; |
| | 13197 | 161 | | int newParentIndex = AllocateNode(default!, combinedBounds, false); |
| | | 162 | | |
| | 13197 | 163 | | ref SwiftBVHNode<TKey, TVolume> newParentNode = ref _nodePool[newParentIndex]; |
| | 13197 | 164 | | newParentNode.ParentIndex = oldParentIndex; |
| | 13197 | 165 | | newParentNode.LeftChildIndex = existingLeafIndex; |
| | 13197 | 166 | | newParentNode.RightChildIndex = newLeafIndex; |
| | 13197 | 167 | | newParentNode.SubtreeSize = 1 + _nodePool[existingLeafIndex].SubtreeSize + _nodePool[newLeafIndex].SubtreeSize; |
| | | 168 | | |
| | 13197 | 169 | | _nodePool[existingLeafIndex].ParentIndex = newParentIndex; |
| | 13197 | 170 | | _nodePool[newLeafIndex].ParentIndex = newParentIndex; |
| | | 171 | | |
| | 13197 | 172 | | return newParentIndex; |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | private void InsertIntoBestChild(int parentNodeIndex, int newNodeIndex) |
| | | 176 | | { |
| | 138630 | 177 | | ref SwiftBVHNode<TKey, TVolume> parentNode = ref _nodePool[parentNodeIndex]; |
| | 138630 | 178 | | if (ShouldInsertIntoLeftChild(parentNodeIndex, newNodeIndex)) |
| | 70153 | 179 | | parentNode.LeftChildIndex = InsertIntoTree(parentNode.LeftChildIndex, newNodeIndex); |
| | | 180 | | else |
| | 68477 | 181 | | parentNode.RightChildIndex = InsertIntoTree(parentNode.RightChildIndex, newNodeIndex); |
| | 68477 | 182 | | } |
| | | 183 | | |
| | | 184 | | private bool ShouldInsertIntoLeftChild(int parentNodeIndex, int newNodeIndex) |
| | | 185 | | { |
| | 138630 | 186 | | SwiftBVHNode<TKey, TVolume> parentNode = _nodePool[parentNodeIndex]; |
| | 138630 | 187 | | SwiftBVHNode<TKey, TVolume> leftChild = GetNodeOrDefault(parentNode.LeftChildIndex); |
| | 138630 | 188 | | SwiftBVHNode<TKey, TVolume> rightChild = GetNodeOrDefault(parentNode.RightChildIndex); |
| | 138630 | 189 | | int leftSize = GetSubtreeSize(leftChild); |
| | 138630 | 190 | | int rightSize = GetSubtreeSize(rightChild); |
| | | 191 | | |
| | 138630 | 192 | | if (IsSeverelyUnbalanced(leftSize, rightSize)) |
| | 12624 | 193 | | return leftSize <= rightSize; |
| | | 194 | | |
| | 126006 | 195 | | return ShouldInsertIntoLowerCostChild( |
| | 126006 | 196 | | parentNode, |
| | 126006 | 197 | | leftChild, |
| | 126006 | 198 | | rightChild, |
| | 126006 | 199 | | leftSize, |
| | 126006 | 200 | | rightSize, |
| | 126006 | 201 | | _nodePool[newNodeIndex].Bounds); |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | private static bool IsSeverelyUnbalanced(int leftSize, int rightSize) |
| | | 205 | | { |
| | 138630 | 206 | | int maxSize = Math.Max(leftSize, rightSize); |
| | 138630 | 207 | | int minSize = Math.Min(leftSize, rightSize); |
| | 138630 | 208 | | return maxSize > minSize * 2; |
| | | 209 | | } |
| | | 210 | | |
| | | 211 | | private static bool ShouldInsertIntoLowerCostChild( |
| | | 212 | | SwiftBVHNode<TKey, TVolume> parentNode, |
| | | 213 | | SwiftBVHNode<TKey, TVolume> leftChild, |
| | | 214 | | SwiftBVHNode<TKey, TVolume> rightChild, |
| | | 215 | | int leftSize, |
| | | 216 | | int rightSize, |
| | | 217 | | TVolume newBounds) |
| | | 218 | | { |
| | 126006 | 219 | | long leftCost = GetInsertionCost(parentNode.LeftChildIndex, leftChild, newBounds); |
| | 126006 | 220 | | long rightCost = GetInsertionCost(parentNode.RightChildIndex, rightChild, newBounds); |
| | | 221 | | |
| | 126006 | 222 | | if (leftCost == rightCost) |
| | 5801 | 223 | | return leftSize <= rightSize; |
| | | 224 | | |
| | 120205 | 225 | | return leftCost < rightCost; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | private static long GetInsertionCost(int childIndex, SwiftBVHNode<TKey, TVolume> child, TVolume newBounds) |
| | | 229 | | { |
| | 252012 | 230 | | if (childIndex == -1) |
| | 0 | 231 | | return 0L; |
| | | 232 | | |
| | 252012 | 233 | | return child.Bounds.GetCost(newBounds); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | private void RefreshParentNode(int parentNodeIndex) |
| | | 237 | | { |
| | 139119 | 238 | | ref SwiftBVHNode<TKey, TVolume> parentNode = ref _nodePool[parentNodeIndex]; |
| | 139119 | 239 | | SwiftBVHNode<TKey, TVolume> leftChild = GetNodeOrDefault(parentNode.LeftChildIndex); |
| | 139119 | 240 | | SwiftBVHNode<TKey, TVolume> rightChild = GetNodeOrDefault(parentNode.RightChildIndex); |
| | | 241 | | |
| | 139119 | 242 | | parentNode.Bounds = GetCombinedBounds(leftChild, rightChild); |
| | 139119 | 243 | | parentNode.SubtreeSize = 1 + GetSubtreeSize(leftChild) + GetSubtreeSize(rightChild); |
| | 139119 | 244 | | } |
| | | 245 | | |
| | | 246 | | private SwiftBVHNode<TKey, TVolume> GetNodeOrDefault(int nodeIndex) |
| | | 247 | | { |
| | 555498 | 248 | | if (nodeIndex == -1) |
| | 0 | 249 | | return SwiftBVHNode<TKey, TVolume>.Default; |
| | | 250 | | |
| | 555498 | 251 | | return _nodePool[nodeIndex]; |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | private static int GetSubtreeSize(SwiftBVHNode<TKey, TVolume> node) |
| | | 255 | | { |
| | 555498 | 256 | | if (!node.IsAllocated) |
| | 0 | 257 | | return 0; |
| | | 258 | | |
| | 555498 | 259 | | return node.SubtreeSize; |
| | | 260 | | } |
| | | 261 | | |
| | | 262 | | /// <summary> |
| | | 263 | | /// Inserts a value into the hash bucket for fast lookup. |
| | | 264 | | /// Handles collisions with linear probing. |
| | | 265 | | /// </summary> |
| | | 266 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 267 | | private void InsertIntoBuckets(TKey value, int nodeIndex) |
| | | 268 | | { |
| | 13232 | 269 | | _keyToNodeIndex.Insert(value, nodeIndex); |
| | 13232 | 270 | | } |
| | | 271 | | |
| | | 272 | | /// <summary> |
| | | 273 | | /// Updates the bounding volume of a node and propagates changes up the tree. |
| | | 274 | | /// Ensures consistency in parent bounds and subtree sizes. |
| | | 275 | | /// </summary> |
| | | 276 | | public void UpdateEntryBounds(TKey value, TVolume newBounds) |
| | | 277 | | { |
| | 5 | 278 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | | 279 | | |
| | 5 | 280 | | int index = _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | 5 | 281 | | if (index == -1) return; |
| | | 282 | | |
| | 5 | 283 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 6 | 284 | | if (!node.IsAllocated) return; // Skip update if node has been removed |
| | | 285 | | |
| | 4 | 286 | | TVolume oldBounds = node.Bounds; |
| | 4 | 287 | | if (oldBounds.BoundsEquals(newBounds)) |
| | 1 | 288 | | return; // Skip unnecessary updates |
| | | 289 | | |
| | 3 | 290 | | node.Bounds = newBounds; |
| | | 291 | | |
| | | 292 | | // Propagate changes up the tree |
| | 3 | 293 | | int parentIndex = node.ParentIndex; |
| | 6 | 294 | | while (parentIndex != -1) |
| | | 295 | | { |
| | 3 | 296 | | ref SwiftBVHNode<TKey, TVolume> parent = ref _nodePool[parentIndex]; |
| | 3 | 297 | | SwiftBVHNode<TKey, TVolume> leftChild = parent.HasLeftChild |
| | 3 | 298 | | ? _nodePool[parent.LeftChildIndex] |
| | 3 | 299 | | : SwiftBVHNode<TKey, TVolume>.Default; |
| | 3 | 300 | | SwiftBVHNode<TKey, TVolume> rightChild = parent.HasRightChild |
| | 3 | 301 | | ? _nodePool[parent.RightChildIndex] |
| | 3 | 302 | | : SwiftBVHNode<TKey, TVolume>.Default; |
| | | 303 | | |
| | 3 | 304 | | TVolume newParentBounds = GetCombinedBounds(leftChild, rightChild); |
| | 3 | 305 | | if (parent.Bounds.BoundsEquals(newParentBounds)) |
| | | 306 | | break; // No further updates needed |
| | | 307 | | |
| | 3 | 308 | | parent.Bounds = newParentBounds; |
| | 3 | 309 | | parentIndex = parent.ParentIndex; |
| | | 310 | | } |
| | 3 | 311 | | } |
| | | 312 | | |
| | | 313 | | /// <summary> |
| | | 314 | | /// Removes a value and its associated bounding volume from the BVH. |
| | | 315 | | /// Updates tree structure and clears hash bucket entries. |
| | | 316 | | /// </summary> |
| | | 317 | | public bool Remove(TKey value) |
| | | 318 | | { |
| | 135 | 319 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | | 320 | | |
| | 135 | 321 | | int nodeIndex = _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | 137 | 322 | | if (nodeIndex == -1) return false; |
| | | 323 | | |
| | | 324 | | // If the node is the root and the only node, reset the BVH |
| | 133 | 325 | | if (nodeIndex == RootNodeIndex && _leafCount == 1) |
| | | 326 | | { |
| | 2 | 327 | | Clear(); |
| | 2 | 328 | | return true; |
| | | 329 | | } |
| | | 330 | | |
| | 131 | 331 | | RemoveFromBuckets(value); // Ensure the bucket is cleared before further operations |
| | | 332 | | |
| | | 333 | | // Remove node and update tree structure |
| | 131 | 334 | | RemoveFromTree(nodeIndex); |
| | | 335 | | |
| | 131 | 336 | | return true; |
| | | 337 | | } |
| | | 338 | | |
| | | 339 | | /// <summary> |
| | | 340 | | /// Removes an entry from the hash buckets, resolving collisions as necessary. |
| | | 341 | | /// </summary> |
| | | 342 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 343 | | private void RemoveFromBuckets(TKey value) |
| | | 344 | | { |
| | 131 | 345 | | _keyToNodeIndex.Remove(value, MatchesEntryKey, IsAllocatedLeafNode, GetNodeValue); |
| | 131 | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Removes a leaf node from the tree, collapses its parent, and propagates |
| | | 350 | | /// bound and subtree-size updates upward. Every internal node is guaranteed |
| | | 351 | | /// to have exactly two children after this operation completes. |
| | | 352 | | /// </summary> |
| | | 353 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 354 | | private void RemoveFromTree(int nodeIndex) |
| | | 355 | | { |
| | 131 | 356 | | int parentIndex = _nodePool[nodeIndex].ParentIndex; |
| | | 357 | | |
| | 131 | 358 | | if (parentIndex == -1) |
| | | 359 | | { |
| | 0 | 360 | | RemoveRootLeaf(nodeIndex); |
| | 0 | 361 | | return; |
| | | 362 | | } |
| | | 363 | | |
| | 131 | 364 | | int siblingIndex = ReleaseLeafAndParent(nodeIndex, parentIndex, out int grandParentIndex); |
| | 131 | 365 | | PromoteSiblingToGrandParent(siblingIndex, parentIndex, grandParentIndex); |
| | 131 | 366 | | if (grandParentIndex != -1) |
| | 125 | 367 | | RefreshAncestors(grandParentIndex); |
| | 131 | 368 | | } |
| | | 369 | | |
| | | 370 | | private void RemoveRootLeaf(int nodeIndex) |
| | | 371 | | { |
| | 0 | 372 | | _leafCount--; |
| | 0 | 373 | | _nodePool[nodeIndex].Reset(); |
| | 0 | 374 | | _freeIndices.Push(nodeIndex); |
| | 0 | 375 | | _rootNodeIndex = -1; |
| | 0 | 376 | | } |
| | | 377 | | |
| | | 378 | | private int ReleaseLeafAndParent(int nodeIndex, int parentIndex, out int grandParentIndex) |
| | | 379 | | { |
| | 131 | 380 | | ref SwiftBVHNode<TKey, TVolume> parent = ref _nodePool[parentIndex]; |
| | 131 | 381 | | int siblingIndex = parent.LeftChildIndex == nodeIndex |
| | 131 | 382 | | ? parent.RightChildIndex |
| | 131 | 383 | | : parent.LeftChildIndex; |
| | 131 | 384 | | grandParentIndex = parent.ParentIndex; |
| | | 385 | | |
| | | 386 | | // Push parent before the leaf so that the leaf index sits on top of the |
| | | 387 | | // freelist stack and is reused first by the next allocation. |
| | 131 | 388 | | parent.Reset(); |
| | 131 | 389 | | _freeIndices.Push(parentIndex); |
| | | 390 | | |
| | 131 | 391 | | _leafCount--; |
| | 131 | 392 | | _nodePool[nodeIndex].Reset(); |
| | 131 | 393 | | _freeIndices.Push(nodeIndex); |
| | | 394 | | |
| | 131 | 395 | | return siblingIndex; |
| | | 396 | | } |
| | | 397 | | |
| | | 398 | | private void PromoteSiblingToGrandParent(int siblingIndex, int parentIndex, int grandParentIndex) |
| | | 399 | | { |
| | 131 | 400 | | if (siblingIndex != -1) |
| | 131 | 401 | | _nodePool[siblingIndex].ParentIndex = grandParentIndex; |
| | | 402 | | |
| | 131 | 403 | | if (grandParentIndex == -1) |
| | | 404 | | { |
| | 6 | 405 | | _rootNodeIndex = siblingIndex; |
| | 6 | 406 | | return; |
| | | 407 | | } |
| | | 408 | | |
| | 125 | 409 | | ref SwiftBVHNode<TKey, TVolume> grandParent = ref _nodePool[grandParentIndex]; |
| | 125 | 410 | | if (grandParent.LeftChildIndex == parentIndex) |
| | 65 | 411 | | grandParent.LeftChildIndex = siblingIndex; |
| | | 412 | | else |
| | 60 | 413 | | grandParent.RightChildIndex = siblingIndex; |
| | 60 | 414 | | } |
| | | 415 | | |
| | | 416 | | private void RefreshAncestors(int current) |
| | | 417 | | { |
| | 614 | 418 | | while (current != -1) |
| | | 419 | | { |
| | 489 | 420 | | RefreshParentNode(current); |
| | 489 | 421 | | current = _nodePool[current].ParentIndex; |
| | | 422 | | } |
| | 125 | 423 | | } |
| | | 424 | | |
| | | 425 | | #endregion |
| | | 426 | | |
| | | 427 | | #region Capacity Management |
| | | 428 | | |
| | | 429 | | /// <summary> |
| | | 430 | | /// Ensures the BVH has sufficient capacity, resizing the node pool and buckets if needed. |
| | | 431 | | /// </summary> |
| | | 432 | | public void EnsureCapacity(int capacity) |
| | | 433 | | { |
| | 2 | 434 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 2 | 435 | | if (capacity > _nodePool.Length) |
| | 1 | 436 | | Resize(capacity); |
| | 2 | 437 | | } |
| | | 438 | | |
| | | 439 | | /// <summary> |
| | | 440 | | /// Resizes the internal node pool to accommodate additional nodes. |
| | | 441 | | /// Preserves existing nodes and reinitializes the expanded capacity. |
| | | 442 | | /// </summary> |
| | | 443 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 444 | | private void Resize(int newSize) |
| | | 445 | | { |
| | 26 | 446 | | SwiftBVHNode<TKey, TVolume>[] newArray = new SwiftBVHNode<TKey, TVolume>[newSize]; |
| | 26 | 447 | | Array.Copy(_nodePool, 0, newArray, 0, _peakIndex); |
| | | 448 | | |
| | 70432 | 449 | | for (int i = _peakIndex; i < newSize; i++) |
| | 35190 | 450 | | newArray[i].Reset(); // set default index lookup values |
| | | 451 | | |
| | 26 | 452 | | _nodePool = newArray; |
| | | 453 | | |
| | 26 | 454 | | ResizeBuckets(newSize); |
| | 26 | 455 | | QueryCollectionDiagnostics.WriteInfo(_diagnosticSource, $"Resized BVH storage to {newSize} nodes."); |
| | 26 | 456 | | } |
| | | 457 | | |
| | | 458 | | /// <summary> |
| | | 459 | | /// Resizes and rehashes the hash buckets to maintain lookup efficiency. |
| | | 460 | | /// Rehashes existing nodes after resizing. |
| | | 461 | | /// </summary> |
| | | 462 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 463 | | private void ResizeBuckets(int newSize) |
| | | 464 | | { |
| | 26 | 465 | | _keyToNodeIndex.ResizeAndRehash(newSize, _peakIndex, IsLeafNode, GetNodeValue); |
| | 26 | 466 | | } |
| | | 467 | | |
| | | 468 | | #endregion |
| | | 469 | | |
| | | 470 | | #region Utility Methods |
| | | 471 | | |
| | | 472 | | /// <summary> |
| | | 473 | | /// Gets the combined bounding volume of two child nodes. |
| | | 474 | | /// Handles cases where one or both children are missing. |
| | | 475 | | /// </summary> |
| | | 476 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 477 | | private static TVolume GetCombinedBounds(SwiftBVHNode<TKey, TVolume> leftChild, SwiftBVHNode<TKey, TVolume> rightChi |
| | | 478 | | { |
| | 139122 | 479 | | if (leftChild.IsAllocated && rightChild.IsAllocated) |
| | 139122 | 480 | | return leftChild.Bounds.Union(rightChild.Bounds); |
| | 0 | 481 | | if (leftChild.IsAllocated) |
| | 0 | 482 | | return leftChild.Bounds; |
| | 0 | 483 | | return rightChild.Bounds; |
| | | 484 | | } |
| | | 485 | | |
| | | 486 | | /// <summary> |
| | | 487 | | /// Queries the BVH for values whose bounding volumes intersect with the specified volume. |
| | | 488 | | /// Uses a stack-based approach for efficient traversal. |
| | | 489 | | /// </summary> |
| | | 490 | | public void Query(TVolume queryBounds, ICollection<TKey> results) |
| | | 491 | | { |
| | 25 | 492 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | | 493 | | |
| | 28 | 494 | | if (RootNodeIndex == -1) return; |
| | | 495 | | |
| | 22 | 496 | | SwiftIntStack nodeStack = _queryScratch.RentIntStack(_peakIndex + 1); |
| | 22 | 497 | | nodeStack.Push(RootNodeIndex); |
| | | 498 | | |
| | 21063 | 499 | | while (nodeStack.Count > 0) |
| | | 500 | | { |
| | 21042 | 501 | | int index = nodeStack.Pop(); |
| | 21042 | 502 | | QueryNode(index, queryBounds, results, nodeStack); |
| | | 503 | | } |
| | 21 | 504 | | } |
| | | 505 | | |
| | | 506 | | private void QueryNode(int index, TVolume queryBounds, ICollection<TKey> results, SwiftIntStack nodeStack) |
| | | 507 | | { |
| | 21042 | 508 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 21042 | 509 | | ThrowIfQueryNodeIsUnallocated(index, node); |
| | | 510 | | |
| | 21041 | 511 | | if (!queryBounds.Intersects(node.Bounds)) |
| | 306 | 512 | | return; |
| | | 513 | | |
| | 20735 | 514 | | if (node.IsLeaf) |
| | | 515 | | { |
| | 10225 | 516 | | results.Add(node.Value); |
| | 10225 | 517 | | return; |
| | | 518 | | } |
| | | 519 | | |
| | 10510 | 520 | | PushChildNodes(node, nodeStack); |
| | 10510 | 521 | | } |
| | | 522 | | |
| | | 523 | | private static void PushChildNodes(SwiftBVHNode<TKey, TVolume> node, SwiftIntStack nodeStack) |
| | | 524 | | { |
| | 10510 | 525 | | if (node.HasLeftChild) |
| | 10510 | 526 | | nodeStack.Push(node.LeftChildIndex); |
| | 10510 | 527 | | if (node.HasRightChild) |
| | 10510 | 528 | | nodeStack.Push(node.RightChildIndex); |
| | 10510 | 529 | | } |
| | | 530 | | |
| | | 531 | | private static void ThrowIfQueryNodeIsUnallocated(int index, SwiftBVHNode<TKey, TVolume> node) |
| | | 532 | | { |
| | 21042 | 533 | | if (node.IsAllocated) |
| | 21041 | 534 | | return; |
| | | 535 | | |
| | 1 | 536 | | QueryCollectionDiagnostics.WriteError( |
| | 1 | 537 | | _diagnosticSource, |
| | 1 | 538 | | $"Encountered an unallocated node at index {index} during query traversal."); |
| | 1 | 539 | | throw new InvalidOperationException($"Encountered an unallocated node at index {index} during query traversal.") |
| | | 540 | | } |
| | | 541 | | |
| | | 542 | | /// <summary> |
| | | 543 | | /// Finds the index of a node by its value in the BVH using hash buckets. |
| | | 544 | | /// Returns -1 if the value is not found. |
| | | 545 | | /// </summary> |
| | | 546 | | public int FindEntry(TKey value) |
| | | 547 | | { |
| | 11 | 548 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | 11 | 549 | | return _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | /// <summary> |
| | | 553 | | /// Clears the BVH, resetting all nodes, buckets, and metadata. |
| | | 554 | | /// </summary> |
| | | 555 | | public void Clear() |
| | | 556 | | { |
| | 3 | 557 | | if (RootNodeIndex == -1) return; |
| | | 558 | | |
| | 208 | 559 | | for (int i = 0; i < _peakIndex; i++) |
| | 101 | 560 | | _nodePool[i].Reset(); |
| | | 561 | | |
| | 3 | 562 | | _keyToNodeIndex.Clear(); |
| | | 563 | | |
| | 3 | 564 | | _freeIndices.Reset(); |
| | | 565 | | |
| | 3 | 566 | | _leafCount = 0; |
| | 3 | 567 | | _peakIndex = 0; |
| | 3 | 568 | | _rootNodeIndex = -1; |
| | 3 | 569 | | } |
| | | 570 | | |
| | | 571 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 18528 | 572 | | private TKey GetNodeValue(int index) => _nodePool[index].Value; |
| | | 573 | | |
| | | 574 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 35132 | 575 | | private bool IsLeafNode(int index) => _nodePool[index].IsLeaf; |
| | | 576 | | |
| | | 577 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 950 | 578 | | private bool IsAllocatedLeafNode(int index) => _nodePool[index].IsLeaf && _nodePool[index].IsAllocated; |
| | | 579 | | |
| | | 580 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 581 | | private bool MatchesEntryKey(int index, TKey value) |
| | | 582 | | { |
| | 284 | 583 | | return _nodePool[index].IsLeaf && EqualityComparer<TKey>.Default.Equals(_nodePool[index].Value, value); |
| | | 584 | | } |
| | | 585 | | |
| | | 586 | | #endregion |
| | | 587 | | } |