-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKdTree.cs
More file actions
336 lines (289 loc) · 11.7 KB
/
KdTree.cs
File metadata and controls
336 lines (289 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Contribution of original implementation:
// Andre Fecteau <andre.fecteau1@gmail.com>
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace CDT;
/// <summary>
/// Incrementally-built 2D KD-tree for nearest-point queries.
/// An external point buffer is referenced by index to keep the tree compact.
/// </summary>
/// <typeparam name="T">Coordinate type.</typeparam>
internal sealed class KdTree<T>
where T : IFloatingPoint<T>, IMinMaxValue<T>, IRootFunctions<T>
{
private const int NumVerticesInLeaf = 32;
private const int InitialStackDepth = 64;
private enum SplitDir { X, Y }
private struct Node
{
// children[0] == children[1] => leaf
public int Child0, Child1;
public List<int>? Data; // non-null only for leaf nodes
public bool IsLeaf => Child0 == Child1;
public static Node NewLeaf() => new() { Child0 = 0, Child1 = 0, Data = new List<int>(NumVerticesInLeaf) };
}
private readonly struct NearestTask
{
public readonly int NodeIndex;
public readonly T MinX, MinY, MaxX, MaxY;
public readonly SplitDir Dir;
public readonly T DistSq;
public NearestTask(int node, T minX, T minY, T maxX, T maxY, SplitDir dir, T distSq)
{
NodeIndex = node; MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY;
Dir = dir; DistSq = distSq;
}
}
private readonly List<Node> _nodes = new(64);
private int _root;
private SplitDir _rootDir = SplitDir.X;
private T _minX, _minY, _maxX, _maxY;
private bool _boxInitialized;
private int _size;
private readonly T _two;
private NearestTask[] _stack = new NearestTask[InitialStackDepth];
/// <summary>Initializes an empty KD-tree with no bounding box pre-set.</summary>
public KdTree()
{
_two = T.One + T.One;
_minX = T.MinValue; _minY = T.MinValue;
_maxX = T.MaxValue; _maxY = T.MaxValue;
_root = AddNewNode();
_boxInitialized = false;
}
/// <summary>Initializes an empty KD-tree with a known bounding box.</summary>
public KdTree(T minX, T minY, T maxX, T maxY)
{
_two = T.One + T.One;
_minX = minX; _minY = minY; _maxX = maxX; _maxY = maxY;
_root = AddNewNode();
_boxInitialized = true;
}
/// <summary>Number of points stored.</summary>
public int Size => _size;
/// <summary>Inserts point at index <paramref name="iPoint"/> from the external buffer.</summary>
public void Insert(int iPoint, ReadOnlySpan<V2d<T>> points)
{
_size++;
T px = points[iPoint].X, py = points[iPoint].Y;
// Extend tree if the point falls outside the current box
while (!IsInsideBox(px, py, _minX, _minY, _maxX, _maxY))
{
ExtendTree(px, py);
}
int node = _root;
T minX = _minX, minY = _minY, maxX = _maxX, maxY = _maxY;
SplitDir dir = _rootDir;
while (true)
{
ref Node n = ref CollectionsMarshal.AsSpan(_nodes)[node];
if (n.IsLeaf)
{
// Add point if capacity not reached
if (n.Data!.Count < NumVerticesInLeaf)
{
n.Data.Add(iPoint);
return;
}
// Lazy box initialization
if (!_boxInitialized)
{
InitializeRootBox(points);
minX = _minX; minY = _minY; maxX = _maxX; maxY = _maxY;
}
// Split the full leaf
T mid = GetMid(minX, minY, maxX, maxY, dir);
int c1 = AddNewNode(), c2 = AddNewNode();
n = ref CollectionsMarshal.AsSpan(_nodes)[node]; // re-acquire after possible resize
n.Child0 = c1; n.Child1 = c2;
// Move existing points to children
foreach (int ip in n.Data!)
{
T cx = points[ip].X, cy = points[ip].Y;
int target = WhichChild(cx, cy, mid, dir);
_nodes[target == 0 ? c1 : c2].Data!.Add(ip);
}
n.Data = null; // inner node – no data list needed
}
T midVal = GetMid(minX, minY, maxX, maxY, dir);
int childIdx = WhichChild(px, py, midVal, dir);
if (dir == SplitDir.X)
{
if (childIdx == 0) maxX = midVal; else minX = midVal;
}
else
{
if (childIdx == 0) maxY = midVal; else minY = midVal;
}
node = childIdx == 0 ? _nodes[node].Child0 : _nodes[node].Child1;
dir = dir == SplitDir.X ? SplitDir.Y : SplitDir.X;
}
}
/// <summary>Finds the nearest point to <paramref name="points"/> in the external buffer.</summary>
public int Nearest(T qx, T qy, ReadOnlySpan<V2d<T>> points)
{
int resultIdx = 0;
T minDistSq = T.MaxValue;
int stackTop = -1;
T rootDistSq = DistSqToBox(qx, qy, _minX, _minY, _maxX, _maxY);
PushStack(ref stackTop, new NearestTask(_root, _minX, _minY, _maxX, _maxY, _rootDir, rootDistSq));
while (stackTop >= 0)
{
NearestTask task = _stack[stackTop--];
if (task.DistSq > minDistSq) continue;
ref Node n = ref CollectionsMarshal.AsSpan(_nodes)[task.NodeIndex];
if (n.IsLeaf)
{
foreach (int ip in n.Data!)
{
T dx = points[ip].X - qx;
T dy = points[ip].Y - qy;
T d2 = dx * dx + dy * dy;
if (d2 < minDistSq) { minDistSq = d2; resultIdx = ip; }
}
}
else
{
T mid = GetMid(task.MinX, task.MinY, task.MaxX, task.MaxY, task.Dir);
SplitDir childDir = task.Dir == SplitDir.X ? SplitDir.Y : SplitDir.X;
bool afterSplit = IsAfterSplit(qx, qy, mid, task.Dir);
T dSqFarther = FartherBoxDistSq(qx, qy, task.MinX, task.MinY, task.MaxX, task.MaxY, mid, task.Dir);
if (stackTop + 2 >= _stack.Length)
Array.Resize(ref _stack, _stack.Length + InitialStackDepth);
if (afterSplit)
{
// Closer = child1, Farther = child0
T fMinX = task.MinX, fMinY = task.MinY, fMaxX = task.MaxX, fMaxY = task.MaxY;
T cMinX = task.MinX, cMinY = task.MinY, cMaxX = task.MaxX, cMaxY = task.MaxY;
if (task.Dir == SplitDir.X) { fMaxX = mid; cMinX = mid; }
else { fMaxY = mid; cMinY = mid; }
if (dSqFarther <= minDistSq)
PushStack(ref stackTop, new NearestTask(n.Child0, fMinX, fMinY, fMaxX, fMaxY, childDir, dSqFarther));
PushStack(ref stackTop, new NearestTask(n.Child1, cMinX, cMinY, cMaxX, cMaxY, childDir, task.DistSq));
}
else
{
// Closer = child0, Farther = child1
T cMinX = task.MinX, cMinY = task.MinY, cMaxX = task.MaxX, cMaxY = task.MaxY;
T fMinX = task.MinX, fMinY = task.MinY, fMaxX = task.MaxX, fMaxY = task.MaxY;
if (task.Dir == SplitDir.X) { cMaxX = mid; fMinX = mid; }
else { cMaxY = mid; fMinY = mid; }
if (dSqFarther <= minDistSq)
PushStack(ref stackTop, new NearestTask(n.Child1, fMinX, fMinY, fMaxX, fMaxY, childDir, dSqFarther));
PushStack(ref stackTop, new NearestTask(n.Child0, cMinX, cMinY, cMaxX, cMaxY, childDir, task.DistSq));
}
}
}
return resultIdx;
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void PushStack(ref int top, NearestTask task)
{
_stack[++top] = task;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsInsideBox(T px, T py, T minX, T minY, T maxX, T maxY)
=> px >= minX && px <= maxX && py >= minY && py <= maxY;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private T GetMid(T minX, T minY, T maxX, T maxY, SplitDir dir)
{
return dir == SplitDir.X ? (minX + maxX) / _two : (minY + maxY) / _two;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsAfterSplit(T px, T py, T split, SplitDir dir)
=> dir == SplitDir.X ? px > split : py > split;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int WhichChild(T px, T py, T split, SplitDir dir)
=> IsAfterSplit(px, py, split, dir) ? 1 : 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static T DistSqToBox(T px, T py, T minX, T minY, T maxX, T maxY)
{
T dx = T.Max(T.Max(minX - px, T.Zero), px - maxX);
T dy = T.Max(T.Max(minY - py, T.Zero), py - maxY);
return dx * dx + dy * dy;
}
private static T FartherBoxDistSq(T px, T py, T minX, T minY, T maxX, T maxY, T mid, SplitDir dir)
{
if (dir == SplitDir.X)
{
T dx = px - mid;
T dy = T.Max(T.Max(minY - py, T.Zero), py - maxY);
return dx * dx + dy * dy;
}
else
{
T dx = T.Max(T.Max(minX - px, T.Zero), px - maxX);
T dy = py - mid;
return dx * dx + dy * dy;
}
}
private int AddNewNode()
{
int idx = _nodes.Count;
_nodes.Add(Node.NewLeaf());
return idx;
}
private void ExtendTree(T px, T py)
{
int newRoot = AddNewNode();
int newLeaf = AddNewNode();
ref Node nr = ref CollectionsMarshal.AsSpan(_nodes)[newRoot];
switch (_rootDir)
{
case SplitDir.X:
_rootDir = SplitDir.Y;
if (py < _minY)
{
_minY -= _maxY - _minY;
nr.Child0 = newLeaf; nr.Child1 = _root;
}
else
{
_maxY += _maxY - _minY;
nr.Child0 = _root; nr.Child1 = newLeaf;
}
break;
case SplitDir.Y:
_rootDir = SplitDir.X;
if (px < _minX)
{
_minX -= _maxX - _minX;
nr.Child0 = newLeaf; nr.Child1 = _root;
}
else
{
_maxX += _maxX - _minX;
nr.Child0 = _root; nr.Child1 = newLeaf;
}
break;
}
_root = newRoot;
}
private void InitializeRootBox(ReadOnlySpan<V2d<T>> points)
{
Node rootNode = _nodes[_root];
T mxn = points[rootNode.Data![0]].X, myn = points[rootNode.Data[0]].Y;
T mxx = mxn, mxy = myn;
foreach (int ip in rootNode.Data)
{
T cx = points[ip].X, cy = points[ip].Y;
if (cx < mxn) mxn = cx;
if (cx > mxx) mxx = cx;
if (cy < myn) myn = cy;
if (cy > mxy) mxy = cy;
}
// Ensure non-zero size
T padding = T.One;
if (mxn == mxx) { mxn -= padding; mxx += padding; }
if (myn == mxy) { myn -= padding; mxy += padding; }
_minX = mxn; _minY = myn; _maxX = mxx; _maxY = mxy;
_boxInitialized = true;
}
}