using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Guttman R-tree (quadratic split), M = 16, m = 6. // // Nodes live in one native pool, addressed by index. Each node is 384 bytes // (96 ints, 128-byte aligned = 3 cache lines): // [0..16) header: count, level (0 = leaf), next-free link // [16..32) x0 of the 16 slots // [32..48) y0 // [48..64) x1 // [64..80) y1 // [80..96) ref: child node index (internal) or entry id (leaf) // Unused slots have x0 = int.MaxValue, which never intersects/contains/equals // any valid rectangle, so searches can test all 16 slots with vectors. public sealed unsafe class RTree { const int M = 16; const int MINF = 6; const int STRIDE = 96; const int HCOUNT = 0, HLEVEL = 1, HNEXT = 2; const int OX0 = 16, OY0 = 32, OX1 = 48, OY1 = 64, OREF = 80; const int EMPTY = int.MaxValue; const int MAXDEPTH = 64; int* pool; int capNodes; int usedNodes; int freeHead = -1; int root; int height; // levels, root level + 1 int count; // scratch (native) int* stack; // search stack int* pathNode; int* pathSlot; int* setAside; // 6 ints per entry int* scr; // split scratch ints long* sarea; // split scratch areas int leafDepth; long* heapD; int* heapN; int heapCap; long* bestD; int bestCap; int m1x0, m1y0, m1x1, m1y1, m2x0, m2y0, m2x1, m2y1; public RTree() { capNodes = 64; pool = (int*)NativeMemory.AlignedAlloc((nuint)capNodes * STRIDE * 4, 128); stack = (int*)NativeMemory.Alloc((nuint)(16 * MAXDEPTH + 64) * 4); pathNode = (int*)NativeMemory.Alloc(MAXDEPTH * 4); pathSlot = (int*)NativeMemory.Alloc(MAXDEPTH * 4); setAside = (int*)NativeMemory.Alloc((nuint)(6 * 16 * MAXDEPTH) * 4); scr = (int*)NativeMemory.Alloc(32 * 8 * 4); sarea = (long*)NativeMemory.Alloc(32 * 8); heapCap = 256; heapD = (long*)NativeMemory.Alloc((nuint)heapCap * 8); heapN = (int*)NativeMemory.Alloc((nuint)heapCap * 4); bestCap = 64; bestD = (long*)NativeMemory.Alloc((nuint)bestCap * 8); root = AllocNode(0); height = 1; count = 0; } ~RTree() { if (pool != null) { NativeMemory.AlignedFree(pool); pool = null; } NativeMemory.Free(stack); NativeMemory.Free(pathNode); NativeMemory.Free(pathSlot); NativeMemory.Free(setAside); NativeMemory.Free(scr); NativeMemory.Free(sarea); NativeMemory.Free(heapD); NativeMemory.Free(heapN); NativeMemory.Free(bestD); } public int Count => count; public int Height() => count == 0 ? 0 : height; public int NodeCount() => count == 0 ? 0 : CountNodes(root); int CountNodes(int node) { int* p = N(node); if (p[HLEVEL] == 0) return 1; int s = 1, c = p[HCOUNT]; for (int i = 0; i < c; i++) s += CountNodes(p[OREF + i]); return s; } // ------------------------------------------------------------ pool [MethodImpl(MethodImplOptions.AggressiveInlining)] int* N(int node) => pool + (nint)node * STRIDE; void EnsureCapacity(int need) { if (need <= capNodes) return; int nc = capNodes * 2; if (nc < need) nc = need; pool = (int*)NativeMemory.AlignedRealloc(pool, (nuint)nc * STRIDE * 4, 128); capNodes = nc; } int AllocNode(int level) { int n; if (freeHead >= 0) { n = freeHead; freeHead = N(n)[HNEXT]; } else { if (usedNodes >= capNodes) EnsureCapacity(usedNodes + 1); n = usedNodes++; } int* p = N(n); p[HCOUNT] = 0; p[HLEVEL] = level; for (int i = 0; i < M; i++) p[OX0 + i] = EMPTY; return n; } void FreeNode(int n) { N(n)[HNEXT] = freeHead; freeHead = n; } // ------------------------------------------------------------ insert public void Insert(int x0, int y0, int x1, int y1, int id) { InsertAt(x0, y0, x1, y1, id, 0); count++; } void InsertAt(int rx0, int ry0, int rx1, int ry1, int rref, int level) { EnsureCapacity(usedNodes + height + 2); // no reallocation below int node = root; int depth = 0; int* p = N(node); while (p[HLEVEL] > level) { int s = ChooseSubtree(p, rx0, ry0, rx1, ry1); pathNode[depth] = node; pathSlot[depth] = s; depth++; // The child will contain the new rectangle: its exact bounding // rectangle becomes the union (splits below don't change that). if (rx0 < p[OX0 + s]) p[OX0 + s] = rx0; if (ry0 < p[OY0 + s]) p[OY0 + s] = ry0; if (rx1 > p[OX1 + s]) p[OX1 + s] = rx1; if (ry1 > p[OY1 + s]) p[OY1 + s] = ry1; node = p[OREF + s]; p = N(node); } int c = p[HCOUNT]; if (c < M) { p[OX0 + c] = rx0; p[OY0 + c] = ry0; p[OX1 + c] = rx1; p[OY1 + c] = ry1; p[OREF + c] = rref; p[HCOUNT] = c + 1; return; } int nn = Split(node, rx0, ry0, rx1, ry1, rref); while (depth > 0) { depth--; int parent = pathNode[depth]; int s = pathSlot[depth]; int* pp = N(parent); pp[OX0 + s] = m1x0; pp[OY0 + s] = m1y0; pp[OX1 + s] = m1x1; pp[OY1 + s] = m1y1; c = pp[HCOUNT]; if (c < M) { pp[OX0 + c] = m2x0; pp[OY0 + c] = m2y0; pp[OX1 + c] = m2x1; pp[OY1 + c] = m2y1; pp[OREF + c] = nn; pp[HCOUNT] = c + 1; return; } nn = Split(parent, m2x0, m2y0, m2x1, m2y1, nn); } // the root was split int nr = AllocNode(N(root)[HLEVEL] + 1); int* q = N(nr); q[OX0] = m1x0; q[OY0] = m1y0; q[OX1] = m1x1; q[OY1] = m1y1; q[OREF] = root; q[OX0 + 1] = m2x0; q[OY0 + 1] = m2y0; q[OX1 + 1] = m2x1; q[OY1 + 1] = m2y1; q[OREF + 1] = nn; q[HCOUNT] = 2; root = nr; height++; } [MethodImpl(MethodImplOptions.AggressiveInlining)] static int ChooseSubtree(int* p, int rx0, int ry0, int rx1, int ry1) { int n = p[HCOUNT]; int best = 0; long bestEnl = long.MaxValue, bestArea = long.MaxValue; for (int i = 0; i < n; i++) { int a0 = p[OX0 + i], b0 = p[OY0 + i], a1 = p[OX1 + i], b1 = p[OY1 + i]; long area = (long)(a1 - a0) * (b1 - b0); int u0 = Math.Min(a0, rx0), v0 = Math.Min(b0, ry0); int u1 = Math.Max(a1, rx1), v1 = Math.Max(b1, ry1); long enl = (long)(u1 - u0) * (v1 - v0) - area; if (enl < bestEnl || (enl == bestEnl && area < bestArea)) { bestEnl = enl; bestArea = area; best = i; } } return best; } // Quadratic split of node's 16 entries plus one extra entry. The node keeps // group 1, a new node (returned) gets group 2; their bounding rectangles // are left in m1* and m2*. Capacity must have been ensured. int Split(int node, int ex0, int ey0, int ex1, int ey1, int eref) { int q = AllocNode(N(node)[HLEVEL]); int* p = N(node); int* pq = N(q); int* X0 = scr, Y0 = scr + 32, X1 = scr + 64, Y1 = scr + 96, R = scr + 128; int* rem = scr + 160, g1 = scr + 192, g2 = scr + 224; long* A = sarea; for (int i = 0; i < M; i++) { X0[i] = p[OX0 + i]; Y0[i] = p[OY0 + i]; X1[i] = p[OX1 + i]; Y1[i] = p[OY1 + i]; R[i] = p[OREF + i]; } X0[M] = ex0; Y0[M] = ey0; X1[M] = ex1; Y1[M] = ey1; R[M] = eref; const int T = M + 1; for (int i = 0; i < T; i++) A[i] = (long)(X1[i] - X0[i]) * (Y1[i] - Y0[i]); // PickSeeds long worst = long.MinValue; int s1 = 0, s2 = 1; for (int i = 0; i < T - 1; i++) { int ix0 = X0[i], iy0 = Y0[i], ix1 = X1[i], iy1 = Y1[i]; long ia = A[i]; for (int j = i + 1; j < T; j++) { long d = (long)(Math.Max(ix1, X1[j]) - Math.Min(ix0, X0[j])) * (Math.Max(iy1, Y1[j]) - Math.Min(iy0, Y0[j])) - ia - A[j]; if (d > worst) { worst = d; s1 = i; s2 = j; } } } int nrem = 0; for (int i = 0; i < T; i++) if (i != s1 && i != s2) rem[nrem++] = i; int c1 = 0, c2 = 0; g1[c1++] = s1; g2[c2++] = s2; int ax0 = X0[s1], ay0 = Y0[s1], ax1 = X1[s1], ay1 = Y1[s1]; int bx0 = X0[s2], by0 = Y0[s2], bx1 = X1[s2], by1 = Y1[s2]; while (nrem > 0) { if (c1 + nrem == MINF) { for (int r = 0; r < nrem; r++) { int e = rem[r]; g1[c1++] = e; if (X0[e] < ax0) ax0 = X0[e]; if (Y0[e] < ay0) ay0 = Y0[e]; if (X1[e] > ax1) ax1 = X1[e]; if (Y1[e] > ay1) ay1 = Y1[e]; } break; } if (c2 + nrem == MINF) { for (int r = 0; r < nrem; r++) { int e = rem[r]; g2[c2++] = e; if (X0[e] < bx0) bx0 = X0[e]; if (Y0[e] < by0) by0 = Y0[e]; if (X1[e] > bx1) bx1 = X1[e]; if (Y1[e] > by1) by1 = Y1[e]; } break; } long a1 = (long)(ax1 - ax0) * (ay1 - ay0); long a2 = (long)(bx1 - bx0) * (by1 - by0); long bestDiff = -1, bd1 = 0, bd2 = 0; int bi = 0; for (int r = 0; r < nrem; r++) { int i = rem[r]; int x0 = X0[i], y0 = Y0[i], x1 = X1[i], y1 = Y1[i]; long d1 = (long)(Math.Max(ax1, x1) - Math.Min(ax0, x0)) * (Math.Max(ay1, y1) - Math.Min(ay0, y0)) - a1; long d2 = (long)(Math.Max(bx1, x1) - Math.Min(bx0, x0)) * (Math.Max(by1, y1) - Math.Min(by0, y0)) - a2; long diff = d1 - d2; if (diff < 0) diff = -diff; if (diff > bestDiff) { bestDiff = diff; bi = r; bd1 = d1; bd2 = d2; } } int en = rem[bi]; rem[bi] = rem[--nrem]; bool to1; if (bd1 != bd2) to1 = bd1 < bd2; else if (a1 != a2) to1 = a1 < a2; else to1 = c1 <= c2; if (to1) { g1[c1++] = en; if (X0[en] < ax0) ax0 = X0[en]; if (Y0[en] < ay0) ay0 = Y0[en]; if (X1[en] > ax1) ax1 = X1[en]; if (Y1[en] > ay1) ay1 = Y1[en]; } else { g2[c2++] = en; if (X0[en] < bx0) bx0 = X0[en]; if (Y0[en] < by0) by0 = Y0[en]; if (X1[en] > bx1) bx1 = X1[en]; if (Y1[en] > by1) by1 = Y1[en]; } } for (int i = 0; i < c1; i++) { int e = g1[i]; p[OX0 + i] = X0[e]; p[OY0 + i] = Y0[e]; p[OX1 + i] = X1[e]; p[OY1 + i] = Y1[e]; p[OREF + i] = R[e]; } for (int i = c1; i < M; i++) p[OX0 + i] = EMPTY; p[HCOUNT] = c1; for (int i = 0; i < c2; i++) { int e = g2[i]; pq[OX0 + i] = X0[e]; pq[OY0 + i] = Y0[e]; pq[OX1 + i] = X1[e]; pq[OY1 + i] = Y1[e]; pq[OREF + i] = R[e]; } pq[HCOUNT] = c2; // slots >= c2 are already EMPTY (fresh node) m1x0 = ax0; m1y0 = ay0; m1x1 = ax1; m1y1 = ay1; m2x0 = bx0; m2y0 = by0; m2x1 = bx1; m2y1 = by1; return q; } // ------------------------------------------------------------ remove public bool Remove(int x0, int y0, int x1, int y1, int id) { if (count == 0) return false; if (!FindLeaf(root, 0, x0, y0, x1, y1, id)) return false; int D = leafDepth; int* p = N(pathNode[D]); int s = pathSlot[D]; int last = p[HCOUNT] - 1; p[OX0 + s] = p[OX0 + last]; p[OY0 + s] = p[OY0 + last]; p[OX1 + s] = p[OX1 + last]; p[OY1 + s] = p[OY1 + last]; p[OREF + s] = p[OREF + last]; p[OX0 + last] = EMPTY; p[HCOUNT] = last; count--; // Condense the tree. int nSet = 0; int* sa = setAside; for (int d = D; d > 0; d--) { int nd = pathNode[d]; int* pn = N(nd); int* pp = N(pathNode[d - 1]); int ps = pathSlot[d - 1]; int c = pn[HCOUNT]; if (c < MINF) { int lvl = pn[HLEVEL]; for (int i = 0; i < c; i++) { int* e = sa + 6 * nSet++; e[0] = pn[OX0 + i]; e[1] = pn[OY0 + i]; e[2] = pn[OX1 + i]; e[3] = pn[OY1 + i]; e[4] = pn[OREF + i]; e[5] = lvl; } int pl = pp[HCOUNT] - 1; pp[OX0 + ps] = pp[OX0 + pl]; pp[OY0 + ps] = pp[OY0 + pl]; pp[OX1 + ps] = pp[OX1 + pl]; pp[OY1 + ps] = pp[OY1 + pl]; pp[OREF + ps] = pp[OREF + pl]; pp[OX0 + pl] = EMPTY; pp[HCOUNT] = pl; FreeNode(nd); } else { int bx0 = pn[OX0], by0 = pn[OY0], bx1 = pn[OX1], by1 = pn[OY1]; for (int i = 1; i < c; i++) { bx0 = Math.Min(bx0, pn[OX0 + i]); by0 = Math.Min(by0, pn[OY0 + i]); bx1 = Math.Max(bx1, pn[OX1 + i]); by1 = Math.Max(by1, pn[OY1 + i]); } if (bx0 == pp[OX0 + ps] && by0 == pp[OY0 + ps] && bx1 == pp[OX1 + ps] && by1 == pp[OY1 + ps]) break; // nothing above changes pp[OX0 + ps] = bx0; pp[OY0 + ps] = by0; pp[OX1 + ps] = bx1; pp[OY1 + ps] = by1; } } // Reinsert the set-aside entries at their levels (highest first). for (int i = nSet - 1; i >= 0; i--) { int* e = sa + 6 * i; InsertAt(e[0], e[1], e[2], e[3], e[4], e[5]); } // Shorten the tree. while (height > 1) { int* r = N(root); if (r[HCOUNT] != 1) break; int old = root; root = r[OREF]; FreeNode(old); height--; } return true; } bool FindLeaf(int node, int depth, int x0, int y0, int x1, int y1, int id) { int* p = N(node); pathNode[depth] = node; int c = p[HCOUNT]; if (p[HLEVEL] == 0) { for (int i = 0; i < c; i++) { if (((p[OX0 + i] ^ x0) | (p[OY0 + i] ^ y0) | (p[OX1 + i] ^ x1) | (p[OY1 + i] ^ y1) | (p[OREF + i] ^ id)) == 0) { pathSlot[depth] = i; leafDepth = depth; return true; } } return false; } for (int i = 0; i < c; i++) { if (((x0 - p[OX0 + i]) | (y0 - p[OY0 + i]) | (p[OX1 + i] - x1) | (p[OY1 + i] - y1)) >= 0) { pathSlot[depth] = i; if (FindLeaf(p[OREF + i], depth + 1, x0, y0, x1, y1, id)) return true; } } return false; } // ------------------------------------------------------------ search public int Search(int qx0, int qy0, int qx1, int qy1, int[] outIds, int cap) { if (count == 0) return 0; int total = 0; Vector vqx0 = new Vector(qx0), vqy0 = new Vector(qy0); Vector vqx1 = new Vector(qx1), vqy1 = new Vector(qy1); Vector zero = Vector.Zero; int VC = Vector.Count; fixed (int* o = outIds) { int* st = stack; int sp = 0; st[sp++] = root; while (sp > 0) { int* p = N(st[--sp]); if (p[HLEVEL] == 0) { for (int c = 0; c < M; c += VC) { Vector t = (vqx1 - Unsafe.Read>(p + OX0 + c)) | (Unsafe.Read>(p + OX1 + c) - vqx0) | (vqy1 - Unsafe.Read>(p + OY0 + c)) | (Unsafe.Read>(p + OY1 + c) - vqy0); if (Vector.LessThanAll(t, zero)) continue; for (int j = c; j < c + VC; j++) { if (((qx1 - p[OX0 + j]) | (p[OX1 + j] - qx0) | (qy1 - p[OY0 + j]) | (p[OY1 + j] - qy0)) >= 0) { if (total < cap) o[total] = p[OREF + j]; total++; } } } } else { for (int c = 0; c < M; c += VC) { Vector t = (vqx1 - Unsafe.Read>(p + OX0 + c)) | (Unsafe.Read>(p + OX1 + c) - vqx0) | (vqy1 - Unsafe.Read>(p + OY0 + c)) | (Unsafe.Read>(p + OY1 + c) - vqy0); if (Vector.LessThanAll(t, zero)) continue; for (int j = c; j < c + VC; j++) { if (((qx1 - p[OX0 + j]) | (p[OX1 + j] - qx0) | (qy1 - p[OY0 + j]) | (p[OY1 + j] - qy0)) >= 0) { st[sp++] = p[OREF + j]; } } } } } } return total; } // ------------------------------------------------------------ nearest void GrowHeap() { int nc = heapCap * 2; heapD = (long*)NativeMemory.Realloc(heapD, (nuint)nc * 8); heapN = (int*)NativeMemory.Realloc(heapN, (nuint)nc * 4); heapCap = nc; } public int Nearest(int px, int py, int k, int[] outIds) { if (k <= 0 || count == 0) return 0; int kk = Math.Min(k, count); if (kk > bestCap) { int nc = Math.Max(kk, bestCap * 2); bestD = (long*)NativeMemory.Realloc(bestD, (nuint)nc * 8); bestCap = nc; } long* bd = bestD; int nb = 0; fixed (int* bid = outIds) { long* hd = heapD; int* hn = heapN; int hs = 1; hd[0] = 0; hn[0] = root; while (hs > 0) { long d0 = hd[0]; if (nb == kk && d0 > bd[kk - 1]) break; int node = hn[0]; // pop hs--; if (hs > 0) { long ld = hd[hs]; int ln = hn[hs]; int i = 0; while (true) { int l = 2 * i + 1; if (l >= hs) break; int r = l + 1; if (r < hs && hd[r] < hd[l]) l = r; if (hd[l] >= ld) break; hd[i] = hd[l]; hn[i] = hn[l]; i = l; } hd[i] = ld; hn[i] = ln; } int* p = N(node); int c = p[HCOUNT]; if (p[HLEVEL] == 0) { for (int i = 0; i < c; i++) { int dx = Math.Max(Math.Max(p[OX0 + i] - px, px - p[OX1 + i]), 0); int dy = Math.Max(Math.Max(p[OY0 + i] - py, py - p[OY1 + i]), 0); long dist = (long)dx * dx + (long)dy * dy; int id = p[OREF + i]; int j; if (nb < kk) { j = nb++; } else { long ld = bd[kk - 1]; if (dist > ld || (dist == ld && id > bid[kk - 1])) continue; j = kk - 1; } while (j > 0 && (bd[j - 1] > dist || (bd[j - 1] == dist && bid[j - 1] > id))) { bd[j] = bd[j - 1]; bid[j] = bid[j - 1]; j--; } bd[j] = dist; bid[j] = id; } } else { if (hs + M > heapCap) { GrowHeap(); hd = heapD; hn = heapN; } long lim = nb == kk ? bd[kk - 1] : long.MaxValue; for (int i = 0; i < c; i++) { int dx = Math.Max(Math.Max(p[OX0 + i] - px, px - p[OX1 + i]), 0); int dy = Math.Max(Math.Max(p[OY0 + i] - py, py - p[OY1 + i]), 0); long dist = (long)dx * dx + (long)dy * dy; if (dist > lim) continue; int ch = p[OREF + i]; int j = hs++; while (j > 0) { int par = (j - 1) >> 1; if (hd[par] <= dist) break; hd[j] = hd[par]; hn[j] = hn[par]; j = par; } hd[j] = dist; hn[j] = ch; } } } } return kk; } }