using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [SkipLocalsInit] public sealed unsafe class RTree { private const int M = 16; private const int MinFill = 6; private const int MaxHeight = 32; // Sentinels for unused slots in AoSoA-4 blocks. // Valid coordinates are in [0, 2^20 - 1]. // These sentinels simultaneously: // 1) fail every intersection test (x0 <= qx1 && x1 >= qx0 && y0 <= qy1 && y1 >= qy0) // 2) fail every containment test (x0 <= rx0 && x1 >= rx1 && y0 <= ry0 && y1 >= ry1) // 3) fail every exact-match test (x0 == rx0 && x1 == rx1 && y0 == ry0 && y1 == ry1) // 4) act as identity elements for bounding-box min/max reductions private const int SentinelLo = 1 << 22; private const int SentinelHi = -1; private static readonly Vector Mask4 = Vector.Count == 4 ? new Vector(new int[] { 1, 2, 4, 8 }) : Vector.Zero; // Node storage pools (128-byte aligned AoSoA-4 rects, 64-byte aligned data, 1-byte counts). // Node n rects live at _rects + (n * 64), laid out as 4 blocks of 16 ints (64 bytes each): // block b (entries 4b..4b+3): x0[4], x1[4], y0[4], y1[4]. // Entries 0..7 fit in 1 single 128-byte cache line; entries 8..15 fit in the next 128-byte cache line. // Node n data (child node indices for internal nodes, entry ids for leaves) live at _data + (n * 16). private int* _rects; private int* _data; private byte* _counts; private int _poolCap; private int _poolUsed; private int _freeHead; private int _root; private int _height; private int _count; private int _nodeCount; // Reusable scratch space for Nearest() (4-ary min-heap + result max-heap for k > 32). private ulong* _pqKey; private int* _pqNode; private int _pqCap; private long* _resDist; private int* _resId; private int _resCap; public RTree() { _root = -1; _freeHead = -1; } ~RTree() { if (_rects != null) { NativeMemory.AlignedFree(_rects); _rects = null; } if (_data != null) { NativeMemory.AlignedFree(_data); _data = null; } if (_counts != null) { NativeMemory.AlignedFree(_counts); _counts = null; } if (_pqKey != null) { NativeMemory.AlignedFree(_pqKey); _pqKey = null; } if (_pqNode != null) { NativeMemory.AlignedFree(_pqNode); _pqNode = null; } if (_resDist != null) { NativeMemory.AlignedFree(_resDist); _resDist = null; } if (_resId != null) { NativeMemory.AlignedFree(_resId); _resId = null; } } public int Count => _count; public int Height() => _height; public int NodeCount() => _nodeCount; // --------------------------------------------------------- pool management private void GrowPool() { int newCap = _poolCap == 0 ? 16 : _poolCap * 2; _rects = (int*)NativeMemory.AlignedRealloc(_rects, (nuint)newCap * 256, 128); _data = (int*)NativeMemory.AlignedRealloc(_data, (nuint)newCap * 64, 64); _counts = (byte*)NativeMemory.AlignedRealloc(_counts, (nuint)newCap, 64); _poolCap = newCap; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int AllocNode() { int idx; if (_freeHead >= 0) { idx = _freeHead; _freeHead = _data[(nint)idx << 4]; } else { if (_poolUsed == _poolCap) GrowPool(); idx = _poolUsed++; } _nodeCount++; InitNodeSentinels(idx); return idx; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeNode(int idx) { _data[(nint)idx << 4] = _freeHead; _freeHead = idx; _nodeCount--; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void InitNodeSentinels(int idx) { int* p = _rects + ((nint)idx << 6); if (Vector.Count == 4) { Vector lo = new Vector(SentinelLo); Vector hi = new Vector(SentinelHi); *(Vector*)(p + 0) = lo; *(Vector*)(p + 4) = hi; *(Vector*)(p + 8) = lo; *(Vector*)(p + 12) = hi; *(Vector*)(p + 16) = lo; *(Vector*)(p + 20) = hi; *(Vector*)(p + 24) = lo; *(Vector*)(p + 28) = hi; *(Vector*)(p + 32) = lo; *(Vector*)(p + 36) = hi; *(Vector*)(p + 40) = lo; *(Vector*)(p + 44) = hi; *(Vector*)(p + 48) = lo; *(Vector*)(p + 52) = hi; *(Vector*)(p + 56) = lo; *(Vector*)(p + 60) = hi; } else { for (int b = 0; b < 64; b += 16) { for (int l = 0; l < 4; l++) { p[b + l] = SentinelLo; p[b + 4 + l] = SentinelHi; p[b + 8 + l] = SentinelLo; p[b + 12 + l] = SentinelHi; } } } _counts[idx] = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int SlotOffset(int slot) => ((slot & ~3) << 2) | (slot & 3); [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteSlot(int node, int slot, int x0, int y0, int x1, int y1, int data) { int* p = _rects + ((nint)node << 6) + SlotOffset(slot); p[0] = x0; p[4] = x1; p[8] = y0; p[12] = y1; _data[((nint)node << 4) + slot] = data; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RemoveSlot(int node, int slot) { int last = _counts[node] - 1; int* r = _rects + ((nint)node << 6); int* d = _data + ((nint)node << 4); int lastOff = SlotOffset(last); if (slot != last) { int slotOff = SlotOffset(slot); r[slotOff] = r[lastOff]; r[slotOff + 4] = r[lastOff + 4]; r[slotOff + 8] = r[lastOff + 8]; r[slotOff + 12] = r[lastOff + 12]; d[slot] = d[last]; } r[lastOff] = SentinelLo; r[lastOff + 4] = SentinelHi; r[lastOff + 8] = SentinelLo; r[lastOff + 12] = SentinelHi; _counts[node] = (byte)last; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ComputeNodeBBox(int node, out int bx0, out int by0, out int bx1, out int by1) { int* p = _rects + ((nint)node << 6); int cnt = _counts[node]; if (Vector.Count == 4) { Vector vx0 = *(Vector*)(p + 0); Vector vx1 = *(Vector*)(p + 4); Vector vy0 = *(Vector*)(p + 8); Vector vy1 = *(Vector*)(p + 12); if (cnt > 4) { vx0 = Vector.Min(vx0, *(Vector*)(p + 16)); vx1 = Vector.Max(vx1, *(Vector*)(p + 20)); vy0 = Vector.Min(vy0, *(Vector*)(p + 24)); vy1 = Vector.Max(vy1, *(Vector*)(p + 28)); if (cnt > 8) { vx0 = Vector.Min(vx0, *(Vector*)(p + 32)); vx1 = Vector.Max(vx1, *(Vector*)(p + 36)); vy0 = Vector.Min(vy0, *(Vector*)(p + 40)); vy1 = Vector.Max(vy1, *(Vector*)(p + 44)); if (cnt > 12) { vx0 = Vector.Min(vx0, *(Vector*)(p + 48)); vx1 = Vector.Max(vx1, *(Vector*)(p + 52)); vy0 = Vector.Min(vy0, *(Vector*)(p + 56)); vy1 = Vector.Max(vy1, *(Vector*)(p + 60)); } } } int a = vx0[0] < vx0[1] ? vx0[0] : vx0[1]; int b = vx0[2] < vx0[3] ? vx0[2] : vx0[3]; bx0 = a < b ? a : b; a = vx1[0] > vx1[1] ? vx1[0] : vx1[1]; b = vx1[2] > vx1[3] ? vx1[2] : vx1[3]; bx1 = a > b ? a : b; a = vy0[0] < vy0[1] ? vy0[0] : vy0[1]; b = vy0[2] < vy0[3] ? vy0[2] : vy0[3]; by0 = a < b ? a : b; a = vy1[0] > vy1[1] ? vy1[0] : vy1[1]; b = vy1[2] > vy1[3] ? vy1[2] : vy1[3]; by1 = a > b ? a : b; } else { bx0 = SentinelLo; by0 = SentinelLo; bx1 = SentinelHi; by1 = SentinelHi; for (int i = 0; i < cnt; i++) { int off = SlotOffset(i); int v = p[off]; if (v < bx0) bx0 = v; v = p[off + 4]; if (v > bx1) bx1 = v; v = p[off + 8]; if (v < by0) by0 = v; v = p[off + 12]; if (v > by1) by1 = v; } } } // --------------------------------------------------------------- Insert public void Insert(int x0, int y0, int x1, int y1, int id) { if (_root < 0) { int r = AllocNode(); WriteSlot(r, 0, x0, y0, x1, y1, id); _counts[r] = 1; _root = r; _height = 1; _count = 1; return; } _count++; InsertAtLevel(x0, y0, x1, y1, id, 0); } private void InsertAtLevel(int x0, int y0, int x1, int y1, int data, int targetLevel) { int* pathNode = stackalloc int[MaxHeight]; int* pathSlot = stackalloc int[MaxHeight]; int cur = _root; int level = _height - 1; while (level > targetLevel) { int* r = _rects + ((nint)cur << 6); int cnt = _counts[cur]; long bestEnl = long.MaxValue; long bestArea = long.MaxValue; int bestIdx = 0; int* p = r; int rem = cnt; int baseIdx = 0; while (rem >= 4) { for (int lane = 0; lane < 4; lane++) { int ex0 = p[lane]; int ex1 = p[lane + 4]; int ey0 = p[lane + 8]; int ey1 = p[lane + 12]; long area = (long)(ex1 - ex0) * (ey1 - ey0); int nx0 = ex0 < x0 ? ex0 : x0; int nx1 = ex1 > x1 ? ex1 : x1; int ny0 = ey0 < y0 ? ey0 : y0; int ny1 = ey1 > y1 ? ey1 : y1; long enl = (long)(nx1 - nx0) * (ny1 - ny0) - area; if (enl < bestEnl || (enl == bestEnl && area < bestArea)) { bestEnl = enl; bestArea = area; bestIdx = baseIdx + lane; } } p += 16; baseIdx += 4; rem -= 4; } for (int lane = 0; lane < rem; lane++) { int ex0 = p[lane]; int ex1 = p[lane + 4]; int ey0 = p[lane + 8]; int ey1 = p[lane + 12]; long area = (long)(ex1 - ex0) * (ey1 - ey0); int nx0 = ex0 < x0 ? ex0 : x0; int nx1 = ex1 > x1 ? ex1 : x1; int ny0 = ey0 < y0 ? ey0 : y0; int ny1 = ey1 > y1 ? ey1 : y1; long enl = (long)(nx1 - nx0) * (ny1 - ny0) - area; if (enl < bestEnl || (enl == bestEnl && area < bestArea)) { bestEnl = enl; bestArea = area; bestIdx = baseIdx + lane; } } pathNode[level] = cur; pathSlot[level] = bestIdx; // Eagerly expand bounding box on the way down. // If no split occurs (the common case), AdjustTree does zero work. // If a split occurs, AdjustTree overwrites the split node's slot with exact bbox; // once splitting stops, all ancestors above already hold the exact union bbox. int* bp = r + SlotOffset(bestIdx); if (x0 < bp[0]) bp[0] = x0; if (x1 > bp[4]) bp[4] = x1; if (y0 < bp[8]) bp[8] = y0; if (y1 > bp[12]) bp[12] = y1; cur = _data[((nint)cur << 4) + bestIdx]; level--; } int curCnt = _counts[cur]; if (curCnt < M) { WriteSlot(cur, curCnt, x0, y0, x1, y1, data); _counts[cur] = (byte)(curCnt + 1); return; } // Node overflow: quadratic split and propagate upward. int newNode = SplitNode(cur, x0, y0, x1, y1, data, out int lx0, out int ly0, out int lx1, out int ly1, out int rx0, out int ry0, out int rx1, out int ry1); int curLevel = targetLevel; while (true) { if (curLevel == _height - 1) { int newRoot = AllocNode(); WriteSlot(newRoot, 0, lx0, ly0, lx1, ly1, cur); WriteSlot(newRoot, 1, rx0, ry0, rx1, ry1, newNode); _counts[newRoot] = 2; _root = newRoot; _height++; return; } int parent = pathNode[curLevel + 1]; int slot = pathSlot[curLevel + 1]; int* pp = _rects + ((nint)parent << 6) + SlotOffset(slot); pp[0] = lx0; pp[4] = lx1; pp[8] = ly0; pp[12] = ly1; int pCnt = _counts[parent]; if (pCnt < M) { WriteSlot(parent, pCnt, rx0, ry0, rx1, ry1, newNode); _counts[parent] = (byte)(pCnt + 1); return; } newNode = SplitNode(parent, rx0, ry0, rx1, ry1, newNode, out lx0, out ly0, out lx1, out ly1, out rx0, out ry0, out rx1, out ry1); cur = parent; curLevel++; } } private int SplitNode( int node, int addX0, int addY0, int addX1, int addY1, int addData, out int g1x0, out int g1y0, out int g1x1, out int g1y1, out int g2x0, out int g2y0, out int g2x1, out int g2y1) { int* sx0 = stackalloc int[17]; int* sx1 = stackalloc int[17]; int* sy0 = stackalloc int[17]; int* sy1 = stackalloc int[17]; int* sdata = stackalloc int[17]; long* sarea = stackalloc long[17]; // Unpack the 16 entries from AoSoA-4 into contiguous stack arrays. int* nr = _rects + ((nint)node << 6); int* nd = _data + ((nint)node << 4); for (int b = 0; b < 4; b++) { int* bp = nr + (b << 4); int dst = b << 2; for (int l = 0; l < 4; l++) { int x0 = bp[l]; int x1 = bp[4 + l]; int y0 = bp[8 + l]; int y1 = bp[12 + l]; sx0[dst + l] = x0; sx1[dst + l] = x1; sy0[dst + l] = y0; sy1[dst + l] = y1; sdata[dst + l] = nd[dst + l]; sarea[dst + l] = (long)(x1 - x0) * (y1 - y0); } } sx0[16] = addX0; sx1[16] = addX1; sy0[16] = addY0; sy1[16] = addY1; sdata[16] = addData; sarea[16] = (long)(addX1 - addX0) * (addY1 - addY0); // 1. PickSeeds: maximize area(J) - area(E1) - area(E2) over all 136 pairs. long bestD = long.MinValue; int seed1 = 0, seed2 = 1; for (int i = 0; i < 16; i++) { int ix0 = sx0[i], ix1 = sx1[i], iy0 = sy0[i], iy1 = sy1[i]; long ia = sarea[i]; for (int j = i + 1; j < 17; j++) { int jx0 = sx0[j], jx1 = sx1[j], jy0 = sy0[j], jy1 = sy1[j]; int ux0 = ix0 < jx0 ? ix0 : jx0; int ux1 = ix1 > jx1 ? ix1 : jx1; int uy0 = iy0 < jy0 ? iy0 : jy0; int uy1 = iy1 > jy1 ? iy1 : jy1; long d = (long)(ux1 - ux0) * (uy1 - uy0) - ia - sarea[j]; if (d > bestD) { bestD = d; seed1 = i; seed2 = j; } } } // Initialize groups with the two seeds. int newNode = AllocNode(); InitNodeSentinels(node); int* n1r = _rects + ((nint)node << 6); int* n1d = _data + ((nint)node << 4); int* n2r = _rects + ((nint)newNode << 6); int* n2d = _data + ((nint)newNode << 4); n1r[0] = sx0[seed1]; n1r[4] = sx1[seed1]; n1r[8] = sy0[seed1]; n1r[12] = sy1[seed1]; n1d[0] = sdata[seed1]; g1x0 = sx0[seed1]; g1y0 = sy0[seed1]; g1x1 = sx1[seed1]; g1y1 = sy1[seed1]; long g1Area = sarea[seed1]; int g1Cnt = 1; n2r[0] = sx0[seed2]; n2r[4] = sx1[seed2]; n2r[8] = sy0[seed2]; n2r[12] = sy1[seed2]; n2d[0] = sdata[seed2]; g2x0 = sx0[seed2]; g2y0 = sy0[seed2]; g2x1 = sx1[seed2]; g2y1 = sy1[seed2]; long g2Area = sarea[seed2]; int g2Cnt = 1; // Build compact list of the 15 remaining entries and cache d1/d2 enlargements. int* rem = stackalloc int[15]; long* d1Arr = stackalloc long[15]; long* d2Arr = stackalloc long[15]; int remCnt = 0; for (int i = 0; i < 17; i++) { if (i == seed1 || i == seed2) continue; rem[remCnt] = i; int ex0 = sx0[i], ex1 = sx1[i], ey0 = sy0[i], ey1 = sy1[i]; int ux0 = g1x0 < ex0 ? g1x0 : ex0; int ux1 = g1x1 > ex1 ? g1x1 : ex1; int uy0 = g1y0 < ey0 ? g1y0 : ey0; int uy1 = g1y1 > ey1 ? g1y1 : ey1; d1Arr[remCnt] = (long)(ux1 - ux0) * (uy1 - uy0) - g1Area; ux0 = g2x0 < ex0 ? g2x0 : ex0; ux1 = g2x1 > ex1 ? g2x1 : ex1; uy0 = g2y0 < ey0 ? g2y0 : ey0; uy1 = g2y1 > ey1 ? g2y1 : ey1; d2Arr[remCnt] = (long)(ux1 - ux0) * (uy1 - uy0) - g2Area; remCnt++; } // 2. PickNext loop with incremental d1/d2 updates. while (remCnt > 0) { if (g1Cnt + remCnt == MinFill) { for (int k = 0; k < remCnt; k++) { int e = rem[k]; int ex0 = sx0[e], ex1 = sx1[e], ey0 = sy0[e], ey1 = sy1[e]; int off = SlotOffset(g1Cnt); n1r[off] = ex0; n1r[off + 4] = ex1; n1r[off + 8] = ey0; n1r[off + 12] = ey1; n1d[g1Cnt++] = sdata[e]; if (ex0 < g1x0) g1x0 = ex0; if (ex1 > g1x1) g1x1 = ex1; if (ey0 < g1y0) g1y0 = ey0; if (ey1 > g1y1) g1y1 = ey1; } break; } if (g2Cnt + remCnt == MinFill) { for (int k = 0; k < remCnt; k++) { int e = rem[k]; int ex0 = sx0[e], ex1 = sx1[e], ey0 = sy0[e], ey1 = sy1[e]; int off = SlotOffset(g2Cnt); n2r[off] = ex0; n2r[off + 4] = ex1; n2r[off + 8] = ey0; n2r[off + 12] = ey1; n2d[g2Cnt++] = sdata[e]; if (ex0 < g2x0) g2x0 = ex0; if (ex1 > g2x1) g2x1 = ex1; if (ey0 < g2y0) g2y0 = ey0; if (ey1 > g2y1) g2y1 = ey1; } break; } long maxDiff = -1; int bestK = 0; for (int k = 0; k < remCnt; k++) { long diff = d1Arr[k] - d2Arr[k]; if (diff < 0) diff = -diff; if (diff > maxDiff) { maxDiff = diff; bestK = k; } } int pick = rem[bestK]; long d1 = d1Arr[bestK]; long d2 = d2Arr[bestK]; // Swap-remove bestK from remaining list. remCnt--; if (bestK != remCnt) { rem[bestK] = rem[remCnt]; d1Arr[bestK] = d1Arr[remCnt]; d2Arr[bestK] = d2Arr[remCnt]; } bool toGroup1 = d1 < d2 || (d1 == d2 && (g1Area < g2Area || (g1Area == g2Area && g1Cnt <= g2Cnt))); int px0 = sx0[pick], px1 = sx1[pick], py0 = sy0[pick], py1 = sy1[pick]; if (toGroup1) { int off = SlotOffset(g1Cnt); n1r[off] = px0; n1r[off + 4] = px1; n1r[off + 8] = py0; n1r[off + 12] = py1; n1d[g1Cnt++] = sdata[pick]; bool changed = false; if (px0 < g1x0) { g1x0 = px0; changed = true; } if (px1 > g1x1) { g1x1 = px1; changed = true; } if (py0 < g1y0) { g1y0 = py0; changed = true; } if (py1 > g1y1) { g1y1 = py1; changed = true; } if (changed) { g1Area = (long)(g1x1 - g1x0) * (g1y1 - g1y0); for (int k = 0; k < remCnt; k++) { int e = rem[k]; int ux0 = g1x0 < sx0[e] ? g1x0 : sx0[e]; int ux1 = g1x1 > sx1[e] ? g1x1 : sx1[e]; int uy0 = g1y0 < sy0[e] ? g1y0 : sy0[e]; int uy1 = g1y1 > sy1[e] ? g1y1 : sy1[e]; d1Arr[k] = (long)(ux1 - ux0) * (uy1 - uy0) - g1Area; } } } else { int off = SlotOffset(g2Cnt); n2r[off] = px0; n2r[off + 4] = px1; n2r[off + 8] = py0; n2r[off + 12] = py1; n2d[g2Cnt++] = sdata[pick]; bool changed = false; if (px0 < g2x0) { g2x0 = px0; changed = true; } if (px1 > g2x1) { g2x1 = px1; changed = true; } if (py0 < g2y0) { g2y0 = py0; changed = true; } if (py1 > g2y1) { g2y1 = py1; changed = true; } if (changed) { g2Area = (long)(g2x1 - g2x0) * (g2y1 - g2y0); for (int k = 0; k < remCnt; k++) { int e = rem[k]; int ux0 = g2x0 < sx0[e] ? g2x0 : sx0[e]; int ux1 = g2x1 > sx1[e] ? g2x1 : sx1[e]; int uy0 = g2y0 < sy0[e] ? g2y0 : sy0[e]; int uy1 = g2y1 > sy1[e] ? g2y1 : sy1[e]; d2Arr[k] = (long)(ux1 - ux0) * (uy1 - uy0) - g2Area; } } } } _counts[node] = (byte)g1Cnt; _counts[newNode] = (byte)g2Cnt; return newNode; } // --------------------------------------------------------------- Remove public bool Remove(int x0, int y0, int x1, int y1, int id) { if (_root < 0) return false; int* pathNode = stackalloc int[MaxHeight]; int* pathSlot = stackalloc int[MaxHeight]; if (!FindLeaf(_root, _height - 1, x0, y0, x1, y1, id, pathNode, pathSlot, out int foundSlot)) { return false; } _count--; int leaf = pathNode[0]; RemoveSlot(leaf, foundSlot); // Special case: root is a leaf. if (_height == 1) { if (_counts[leaf] == 0) { _root = -1; _height = 0; _nodeCount = 0; _poolUsed = 0; _freeHead = -1; } return true; } // CondenseTree: walk from leaf up to root's children. int* elimNode = stackalloc int[MaxHeight]; int* elimLevel = stackalloc int[MaxHeight]; int elimCount = 0; // Track the removed/shrunk rectangle to skip recomputing unchanged parent MBRs. int modX0 = x0, modY0 = y0, modX1 = x1, modY1 = y1; bool checkBoundary = true; int cur = leaf; for (int level = 0; level < _height - 1; level++) { int parent = pathNode[level + 1]; int slot = pathSlot[level + 1]; int* pp = _rects + ((nint)parent << 6) + SlotOffset(slot); int ox0 = pp[0], ox1 = pp[4], oy0 = pp[8], oy1 = pp[12]; if (_counts[cur] < MinFill) { // Eliminate underflowing node from parent and set it aside. elimNode[elimCount] = cur; elimLevel[elimCount] = level; elimCount++; RemoveSlot(parent, slot); // Check whether removed child's MBR touched parent's MBR on the next level up. modX0 = ox0; modY0 = oy0; modX1 = ox1; modY1 = oy1; checkBoundary = true; } else { // Node did not underflow: tighten its MBR in parent if it could have shrunk. if (checkBoundary && modX0 > ox0 && modX1 < ox1 && modY0 > oy0 && modY1 < oy1) { // Strictly interior change: MBR of cur and all ancestors cannot shrink. break; } ComputeNodeBBox(cur, out int nx0, out int ny0, out int nx1, out int ny1); if (nx0 == ox0 && nx1 == ox1 && ny0 == oy0 && ny1 == oy1) { // MBR unchanged: no ancestor can change either. break; } pp[0] = nx0; pp[4] = nx1; pp[8] = ny0; pp[12] = ny1; // Only edges that actually shrank can shrink the parent's MBR. modX0 = nx0 > ox0 ? ox0 : (ox0 + 1); modX1 = nx1 < ox1 ? ox1 : (ox1 - 1); modY0 = ny0 > oy0 ? oy0 : (oy0 + 1); modY1 = ny1 < oy1 ? oy1 : (oy1 - 1); checkBoundary = true; } cur = parent; } // Reinsert all set-aside entries at their original levels (higher levels first). if (elimCount > 0) { int* ex0 = stackalloc int[MinFill]; int* ey0 = stackalloc int[MinFill]; int* ex1 = stackalloc int[MinFill]; int* ey1 = stackalloc int[MinFill]; int* edata = stackalloc int[MinFill]; for (int e = elimCount - 1; e >= 0; e--) { int en = elimNode[e]; int el = elimLevel[e]; int ec = _counts[en]; int* er = _rects + ((nint)en << 6); int* ed = _data + ((nint)en << 4); for (int i = 0; i < ec; i++) { int off = SlotOffset(i); ex0[i] = er[off]; ex1[i] = er[off + 4]; ey0[i] = er[off + 8]; ey1[i] = er[off + 12]; edata[i] = ed[i]; } FreeNode(en); for (int i = 0; i < ec; i++) { InsertAtLevel(ex0[i], ey0[i], ex1[i], ey1[i], edata[i], el); } } } // Shrink tree if root is an internal node with only one child. while (_height > 1 && _counts[_root] == 1) { int oldRoot = _root; _root = _data[(nint)oldRoot << 4]; FreeNode(oldRoot); _height--; } return true; } private bool FindLeaf( int node, int level, int rx0, int ry0, int rx1, int ry1, int id, int* pathNode, int* pathSlot, out int foundSlot) { int* r = _rects + ((nint)node << 6); int* d = _data + ((nint)node << 4); int cnt = _counts[node]; if (level == 0) { if (Vector.Count == 4) { Vector vx0 = new Vector(rx0); Vector vx1 = new Vector(rx1); Vector vy0 = new Vector(ry0); Vector vy1 = new Vector(ry1); Vector vMask = Mask4; int* p = r; for (int i = 0; i < cnt; i += 4, p += 16) { Vector eq = Vector.Equals(*(Vector*)(p), vx0) & Vector.Equals(*(Vector*)(p + 4), vx1) & Vector.Equals(*(Vector*)(p + 8), vy0) & Vector.Equals(*(Vector*)(p + 12), vy1); int mask = Vector.Sum(eq & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; int idx = i + lane; if (d[idx] == id) { pathNode[0] = node; foundSlot = idx; return true; } } } } else { for (int i = 0; i < cnt; i++) { int off = SlotOffset(i); if (r[off] == rx0 && r[off + 4] == rx1 && r[off + 8] == ry0 && r[off + 12] == ry1 && d[i] == id) { pathNode[0] = node; foundSlot = i; return true; } } } foundSlot = -1; return false; } if (Vector.Count == 4) { Vector vx0 = new Vector(rx0); Vector vx1 = new Vector(rx1); Vector vy0 = new Vector(ry0); Vector vy1 = new Vector(ry1); Vector vMask = Mask4; int* p = r; for (int i = 0; i < cnt; i += 4, p += 16) { Vector cont = Vector.LessThanOrEqual(*(Vector*)(p), vx0) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vx1) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vy0) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vy1); int mask = Vector.Sum(cont & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; int idx = i + lane; if (FindLeaf(d[idx], level - 1, rx0, ry0, rx1, ry1, id, pathNode, pathSlot, out foundSlot)) { pathNode[level] = node; pathSlot[level] = idx; return true; } } } } else { for (int i = 0; i < cnt; i++) { int off = SlotOffset(i); if (r[off] <= rx0 && r[off + 4] >= rx1 && r[off + 8] <= ry0 && r[off + 12] >= ry1) { if (FindLeaf(d[i], level - 1, rx0, ry0, rx1, ry1, id, pathNode, pathSlot, out foundSlot)) { pathNode[level] = node; pathSlot[level] = i; return true; } } } } foundSlot = -1; return false; } // --------------------------------------------------------------- Search public int Search(int x0, int y0, int x1, int y1, int[] outIds, int cap) { if (_root < 0) return 0; fixed (int* pOut = outIds) { int total = 0; if (_height == 1) { ScanLeaf(_root, x0, y0, x1, y1, pOut, cap, ref total); return total; } if (x0 == x1 && y0 == y1 && Vector.Count == 4) { return SearchPointVec4(x0, y0, pOut, cap); } // Explicit DFS stack packing (level << 27) | nodeIdx. // Max entries <= 1 + 15 * (height - 1) < 256. int* stack = stackalloc int[256]; int sp = 0; stack[sp++] = ((_height - 1) << 27) | _root; if (Vector.Count == 4) { Vector vqx0 = new Vector(x0); Vector vqy0 = new Vector(y0); Vector vqx1 = new Vector(x1); Vector vqy1 = new Vector(y1); Vector vMask = Mask4; while (sp > 0) { int packed = stack[--sp]; int node = packed & 0x07FFFFFF; int level = packed >> 27; int* p = _rects + ((nint)node << 6); int* d = _data + ((nint)node << 4); int cnt = _counts[node]; if (level == 1) { // Children are leaves: scan matching leaves inline without pushing to stack. for (int i = 0; i < cnt; i += 4, p += 16) { Vector hit = Vector.LessThanOrEqual(*(Vector*)(p), vqx1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vqx0) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vqy1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vqy0); int mask = Vector.Sum(hit & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; int child = d[i + lane]; if (x0 <= p[lane] && p[lane + 4] <= x1 && y0 <= p[lane + 8] && p[lane + 12] <= y1) { int lCnt = _counts[child]; int avail = cap - total; if (avail > 0) { int toCopy = lCnt < avail ? lCnt : avail; Unsafe.CopyBlockUnaligned(pOut + total, _data + ((nint)child << 4), (uint)(toCopy << 2)); } total += lCnt; } else { ScanLeafVec4(child, vqx0, vqy0, vqx1, vqy1, vMask, pOut, cap, ref total); } } } } else { int childLevelShifted = (level - 1) << 27; for (int i = 0; i < cnt; i += 4, p += 16) { Vector hit = Vector.LessThanOrEqual(*(Vector*)(p), vqx1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vqx0) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vqy1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vqy0); int mask = Vector.Sum(hit & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; int child = d[i + lane]; if (x0 <= p[lane] && p[lane + 4] <= x1 && y0 <= p[lane + 8] && p[lane + 12] <= y1) { CollectAll(child, level - 1, pOut, cap, ref total); } else { stack[sp++] = childLevelShifted | child; } } } } } } else { bool checkContain = (x0 < x1) | (y0 < y1); while (sp > 0) { int packed = stack[--sp]; int node = packed & 0x07FFFFFF; int level = packed >> 27; int* r = _rects + ((nint)node << 6); int* d = _data + ((nint)node << 4); int cnt = _counts[node]; for (int i = 0; i < cnt; i++) { int off = SlotOffset(i); int ex0 = r[off], ex1 = r[off + 4], ey0 = r[off + 8], ey1 = r[off + 12]; if (ex0 <= x1 && ex1 >= x0 && ey0 <= y1 && ey1 >= y0) { int child = d[i]; if (checkContain && x0 <= ex0 && ex1 <= x1 && y0 <= ey0 && ey1 <= y1) { CollectAll(child, level - 1, pOut, cap, ref total); } else if (level == 1) { ScanLeaf(child, x0, y0, x1, y1, pOut, cap, ref total); } else { stack[sp++] = ((level - 1) << 27) | child; } } } } } return total; } } // Streamlined point-stabbing fast path (2 query vectors, no containment checks). private int SearchPointVec4(int px, int py, int* pOut, int cap) { int* stack = stackalloc int[256]; int sp = 0; stack[sp++] = ((_height - 1) << 27) | _root; Vector vpx = new Vector(px); Vector vpy = new Vector(py); Vector vMask = Mask4; int total = 0; while (sp > 0) { int packed = stack[--sp]; int node = packed & 0x07FFFFFF; int level = packed >> 27; int* p = _rects + ((nint)node << 6); int* d = _data + ((nint)node << 4); int cnt = _counts[node]; if (level == 1) { for (int i = 0; i < cnt; i += 4, p += 16) { Vector hit = Vector.LessThanOrEqual(*(Vector*)(p), vpx) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vpx) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vpy) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vpy); int mask = Vector.Sum(hit & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; int leaf = d[i + lane]; int* lp = _rects + ((nint)leaf << 6); int* ld = _data + ((nint)leaf << 4); int lCnt = _counts[leaf]; for (int j = 0; j < lCnt; j += 4, lp += 16) { Vector lhit = Vector.LessThanOrEqual(*(Vector*)(lp), vpx) & Vector.GreaterThanOrEqual(*(Vector*)(lp + 4), vpx) & Vector.LessThanOrEqual(*(Vector*)(lp + 8), vpy) & Vector.GreaterThanOrEqual(*(Vector*)(lp + 12), vpy); int lmask = Vector.Sum(lhit & vMask); while (lmask != 0) { int llane = BitOperations.TrailingZeroCount(lmask); lmask &= lmask - 1; if (total < cap) pOut[total] = ld[j + llane]; total++; } } } } } else { int childLevelShifted = (level - 1) << 27; for (int i = 0; i < cnt; i += 4, p += 16) { Vector hit = Vector.LessThanOrEqual(*(Vector*)(p), vpx) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vpx) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vpy) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vpy); int mask = Vector.Sum(hit & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; stack[sp++] = childLevelShifted | d[i + lane]; } } } } return total; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ScanLeafVec4( int leaf, Vector vqx0, Vector vqy0, Vector vqx1, Vector vqy1, Vector vMask, int* pOut, int cap, ref int total) { int* p = _rects + ((nint)leaf << 6); int* d = _data + ((nint)leaf << 4); int cnt = _counts[leaf]; int t = total; for (int i = 0; i < cnt; i += 4, p += 16) { Vector hit = Vector.LessThanOrEqual(*(Vector*)(p), vqx1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 4), vqx0) & Vector.LessThanOrEqual(*(Vector*)(p + 8), vqy1) & Vector.GreaterThanOrEqual(*(Vector*)(p + 12), vqy0); int mask = Vector.Sum(hit & vMask); while (mask != 0) { int lane = BitOperations.TrailingZeroCount(mask); mask &= mask - 1; if (t < cap) pOut[t] = d[i + lane]; t++; } } total = t; } private void ScanLeaf(int leaf, int x0, int y0, int x1, int y1, int* pOut, int cap, ref int total) { if (Vector.Count == 4) { ScanLeafVec4(leaf, new Vector(x0), new Vector(y0), new Vector(x1), new Vector(y1), Mask4, pOut, cap, ref total); return; } int* r = _rects + ((nint)leaf << 6); int* d = _data + ((nint)leaf << 4); int cnt = _counts[leaf]; int t = total; for (int i = 0; i < cnt; i++) { int off = SlotOffset(i); if (r[off] <= x1 && r[off + 4] >= x0 && r[off + 8] <= y1 && r[off + 12] >= y0) { if (t < cap) pOut[t] = d[i]; t++; } } total = t; } // Collect every leaf entry in a subtree completely contained within the query rectangle. // Never reads _rects (only _counts and _data). private void CollectAll(int startNode, int startLevel, int* pOut, int cap, ref int total) { int t = total; if (startLevel == 0) { int lCnt = _counts[startNode]; int avail = cap - t; if (avail > 0) { int toCopy = lCnt < avail ? lCnt : avail; Unsafe.CopyBlockUnaligned(pOut + t, _data + ((nint)startNode << 4), (uint)(toCopy << 2)); } total = t + lCnt; return; } int* stack = stackalloc int[256]; int sp = 0; stack[sp++] = (startLevel << 27) | startNode; while (sp > 0) { int packed = stack[--sp]; int node = packed & 0x07FFFFFF; int level = packed >> 27; int cnt = _counts[node]; int* d = _data + ((nint)node << 4); if (level == 1) { for (int i = 0; i < cnt; i++) { int leaf = d[i]; int lCnt = _counts[leaf]; int avail = cap - t; if (avail > 0) { int toCopy = lCnt < avail ? lCnt : avail; Unsafe.CopyBlockUnaligned(pOut + t, _data + ((nint)leaf << 4), (uint)(toCopy << 2)); } t += lCnt; } } else { int nextShift = (level - 1) << 27; for (int i = 0; i < cnt; i++) { stack[sp++] = nextShift | d[i]; } } } total = t; } // -------------------------------------------------------------- Nearest private void EnsurePqCap(int needed) { if (needed <= _pqCap) return; int newCap = _pqCap == 0 ? 256 : _pqCap * 2; while (newCap < needed) newCap *= 2; _pqKey = (ulong*)NativeMemory.AlignedRealloc(_pqKey, (nuint)newCap * sizeof(ulong), 64); _pqNode = (int*)NativeMemory.AlignedRealloc(_pqNode, (nuint)newCap * sizeof(int), 64); _pqCap = newCap; } private void EnsureResCap(int needed) { if (needed <= _resCap) return; int newCap = _resCap == 0 ? 64 : _resCap * 2; while (newCap < needed) newCap *= 2; _resDist = (long*)NativeMemory.AlignedRealloc(_resDist, (nuint)newCap * sizeof(long), 64); _resId = (int*)NativeMemory.AlignedRealloc(_resId, (nuint)newCap * sizeof(int), 64); _resCap = newCap; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void PqPush(ulong* keys, int* nodes, ref int count, ulong key, int node) { int i = count++; while (i > 0) { int parent = (i - 1) >> 2; if (key >= keys[parent]) break; keys[i] = keys[parent]; nodes[i] = nodes[parent]; i = parent; } keys[i] = key; nodes[i] = node; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void PqPop(ulong* keys, int* nodes, ref int count, out ulong outKey, out int outNode) { outKey = keys[0]; outNode = nodes[0]; int n = --count; if (n == 0) return; ulong lastKey = keys[n]; int lastNode = nodes[n]; int i = 0; while (true) { int c0 = (i << 2) + 1; if (c0 >= n) break; int minC = c0; ulong minK = keys[c0]; int end = c0 + 4; if (end > n) end = n; for (int c = c0 + 1; c < end; c++) { ulong k = keys[c]; if (k < minK) { minK = k; minC = c; } } if (lastKey <= minK) break; keys[i] = minK; nodes[i] = nodes[minC]; i = minC; } keys[i] = lastKey; nodes[i] = lastNode; } public int Nearest(int x, int y, int k, int[] outIds) { if (k <= 0 || _root < 0) return 0; if (k == 1) return Nearest1(x, y, outIds); return NearestK(x, y, k, outIds); } // Specialized k = 1 best-first search with direct-descent bypass. private int Nearest1(int px, int py, int[] outIds) { long bestDist = long.MaxValue; int bestId = int.MaxValue; if (_pqCap < 64) EnsurePqCap(64); ulong* pqKey = _pqKey; int* pqNode = _pqNode; int pqCount = 0; int cur = _root; int level = _height - 1; long curDist = 0; while (true) { if (curDist > bestDist) break; int* r = _rects + ((nint)cur << 6); int* d = _data + ((nint)cur << 4); int cnt = _counts[cur]; if (level == 0) { int* p = r; int rem = cnt; int baseIdx = 0; while (rem > 0) { int chunk = rem < 4 ? rem : 4; for (int lane = 0; lane < chunk; lane++) { int dx = p[lane] - px; int t = px - p[lane + 4]; if (t > dx) dx = t; if (dx < 0) dx = 0; int dy = p[lane + 8] - py; t = py - p[lane + 12]; if (t > dy) dy = t; if (dy < 0) dy = 0; long dist = (long)dx * dx + (long)dy * dy; if (dist <= bestDist) { int id = d[baseIdx + lane]; if (dist < bestDist || id < bestId) { bestDist = dist; bestId = id; } } } p += 16; baseIdx += 4; rem -= 4; } if (bestDist == 0 && bestId == 0) break; if (pqCount == 0) break; PqPop(pqKey, pqNode, ref pqCount, out ulong nextKey, out cur); curDist = (long)(nextKey >> 4); level = (int)(nextKey & 0xF); } else { if (pqCount + cnt > _pqCap) { EnsurePqCap(pqCount + cnt); pqKey = _pqKey; pqNode = _pqNode; } uint childLevel = (uint)(level - 1); int directChild = -1; long directDist = long.MaxValue; int* p = r; int rem = cnt; int baseIdx = 0; while (rem > 0) { int chunk = rem < 4 ? rem : 4; for (int lane = 0; lane < chunk; lane++) { int dx = p[lane] - px; int t = px - p[lane + 4]; if (t > dx) dx = t; if (dx < 0) dx = 0; int dy = p[lane + 8] - py; t = py - p[lane + 12]; if (t > dy) dy = t; if (dy < 0) dy = 0; long dist = (long)dx * dx + (long)dy * dy; if (dist > bestDist) continue; int child = d[baseIdx + lane]; if (dist < directDist) { if (directChild >= 0) { PqPush(pqKey, pqNode, ref pqCount, ((ulong)directDist << 4) | childLevel, directChild); } directChild = child; directDist = dist; } else { PqPush(pqKey, pqNode, ref pqCount, ((ulong)dist << 4) | childLevel, child); } } p += 16; baseIdx += 4; rem -= 4; } if (directChild >= 0) { ulong directKey = ((ulong)directDist << 4) | childLevel; if (pqCount == 0 || directKey <= pqKey[0]) { cur = directChild; curDist = directDist; level = (int)childLevel; continue; } PqPush(pqKey, pqNode, ref pqCount, directKey, directChild); } if (pqCount == 0) break; PqPop(pqKey, pqNode, ref pqCount, out ulong nextKey, out cur); curDist = (long)(nextKey >> 4); level = (int)(nextKey & 0xF); } } outIds[0] = bestId; return 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ResHeapPush(long* dists, int* ids, ref int count, long dist, int id) { int i = count++; while (i > 0) { int parent = (i - 1) >> 1; long pd = dists[parent]; if (dist < pd || (dist == pd && id <= ids[parent])) break; dists[i] = pd; ids[i] = ids[parent]; i = parent; } dists[i] = dist; ids[i] = id; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ResHeapReplaceRoot(long* dists, int* ids, int count, long dist, int id) { int i = 0; while (true) { int left = (i << 1) + 1; if (left >= count) break; int best = left; long bd = dists[left]; int bi = ids[left]; int right = left + 1; if (right < count) { long rd = dists[right]; int ri = ids[right]; if (rd > bd || (rd == bd && ri > bi)) { best = right; bd = rd; bi = ri; } } if (dist > bd || (dist == bd && id >= bi)) break; dists[i] = bd; ids[i] = bi; i = best; } dists[i] = dist; ids[i] = id; } private int NearestK(int px, int py, int k, int[] outIds) { int target = k < _count ? k : _count; long* stackDist = stackalloc long[32]; int* stackId = stackalloc int[32]; long* resDist; int* resId; if (target <= 32) { resDist = stackDist; resId = stackId; } else { EnsureResCap(target); resDist = _resDist; resId = _resId; } int resCount = 0; long worstDist = long.MaxValue; int worstId = int.MaxValue; if (_pqCap < 64) EnsurePqCap(64); ulong* pqKey = _pqKey; int* pqNode = _pqNode; int pqCount = 0; int cur = _root; int level = _height - 1; long curDist = 0; while (true) { if (curDist > worstDist) break; int* r = _rects + ((nint)cur << 6); int* d = _data + ((nint)cur << 4); int cnt = _counts[cur]; if (level == 0) { int* p = r; int rem = cnt; int baseIdx = 0; while (rem > 0) { int chunk = rem < 4 ? rem : 4; for (int lane = 0; lane < chunk; lane++) { int dx = p[lane] - px; int t = px - p[lane + 4]; if (t > dx) dx = t; if (dx < 0) dx = 0; int dy = p[lane + 8] - py; t = py - p[lane + 12]; if (t > dy) dy = t; if (dy < 0) dy = 0; long dist = (long)dx * dx + (long)dy * dy; if (resCount < target) { ResHeapPush(resDist, resId, ref resCount, dist, d[baseIdx + lane]); if (resCount == target) { worstDist = resDist[0]; worstId = resId[0]; } } else if (dist <= worstDist) { int id = d[baseIdx + lane]; if (dist < worstDist || id < worstId) { ResHeapReplaceRoot(resDist, resId, target, dist, id); worstDist = resDist[0]; worstId = resId[0]; } } } p += 16; baseIdx += 4; rem -= 4; } if (pqCount == 0) break; PqPop(pqKey, pqNode, ref pqCount, out ulong nextKey, out cur); curDist = (long)(nextKey >> 4); level = (int)(nextKey & 0xF); } else { if (pqCount + cnt > _pqCap) { EnsurePqCap(pqCount + cnt); pqKey = _pqKey; pqNode = _pqNode; } uint childLevel = (uint)(level - 1); int directChild = -1; long directDist = long.MaxValue; int* p = r; int rem = cnt; int baseIdx = 0; while (rem > 0) { int chunk = rem < 4 ? rem : 4; for (int lane = 0; lane < chunk; lane++) { int dx = p[lane] - px; int t = px - p[lane + 4]; if (t > dx) dx = t; if (dx < 0) dx = 0; int dy = p[lane + 8] - py; t = py - p[lane + 12]; if (t > dy) dy = t; if (dy < 0) dy = 0; long dist = (long)dx * dx + (long)dy * dy; if (dist > worstDist) continue; int child = d[baseIdx + lane]; if (dist < directDist) { if (directChild >= 0) { PqPush(pqKey, pqNode, ref pqCount, ((ulong)directDist << 4) | childLevel, directChild); } directChild = child; directDist = dist; } else { PqPush(pqKey, pqNode, ref pqCount, ((ulong)dist << 4) | childLevel, child); } } p += 16; baseIdx += 4; rem -= 4; } if (directChild >= 0) { ulong directKey = ((ulong)directDist << 4) | childLevel; if (pqCount == 0 || directKey <= pqKey[0]) { cur = directChild; curDist = directDist; level = (int)childLevel; continue; } PqPush(pqKey, pqNode, ref pqCount, directKey, directChild); } if (pqCount == 0) break; PqPop(pqKey, pqNode, ref pqCount, out ulong nextKey, out cur); curDist = (long)(nextKey >> 4); level = (int)(nextKey & 0xF); } } // Extract from max-heap in reverse to produce ascending (dist, id) order. int n = resCount; for (int outPos = n - 1; outPos >= 0; outPos--) { outIds[outPos] = resId[0]; int last = --resCount; if (last > 0) { ResHeapReplaceRoot(resDist, resId, last, resDist[last], resId[last]); } } return n; } }