-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
nd-quadtree-map.ts
398 lines (358 loc) · 8.75 KB
/
nd-quadtree-map.ts
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import type { Fn, ICopy, IEmpty, Maybe, Pair } from "@thi.ng/api";
import { equivArrayLike } from "@thi.ng/equiv";
import { assert } from "@thi.ng/errors/assert";
import { pointInCenteredBox } from "@thi.ng/geom-isec/point";
import { testCenteredBoxSphere } from "@thi.ng/geom-isec/rect-circle";
import { Heap } from "@thi.ng/heaps/heap";
import { EPS } from "@thi.ng/math/api";
import { iterate } from "@thi.ng/transducers/iterate";
import { map } from "@thi.ng/transducers/map";
import { permutations } from "@thi.ng/transducers/permutations";
import { repeat } from "@thi.ng/transducers/repeat";
import { take } from "@thi.ng/transducers/take";
import type { DistanceFn, MultiVecOpRoVV, ReadonlyVec } from "@thi.ng/vectors";
import { addmN } from "@thi.ng/vectors/addmn";
import { distSq } from "@thi.ng/vectors/distsq";
import { madd } from "@thi.ng/vectors/madd";
import { mulN } from "@thi.ng/vectors/muln";
import { submN } from "@thi.ng/vectors/submn";
import { vop } from "@thi.ng/vectors/vop";
import type { IRegionQuery, ISpatialMap } from "./api.js";
import { CMP, __addResults, __into } from "./utils.js";
type MaybeNdQtNode<K extends ReadonlyVec, V> = Maybe<NdQtNode<K, V>>;
export class NdQtNode<K extends ReadonlyVec, V> {
pos: ReadonlyVec;
ext: ReadonlyVec;
parent?: NdQtNode<K, V>;
children?: NdQtNode<K, V>[];
numC: number;
k?: K;
v?: V;
constructor(
parent: MaybeNdQtNode<K, V>,
pos: ReadonlyVec,
ext: ReadonlyVec
) {
this.parent = parent;
this.pos = pos;
this.ext = ext;
this.numC = 0;
}
clear() {
delete this.children;
delete this.k;
delete this.v;
this.numC = 0;
}
set(p: K, val: V, eps: number, distFn: DistanceFn): boolean {
return (
(eps <= 0 || !this.queryKeys(p, eps, 1, [], distFn).length) &&
this.containsPoint(p) &&
this.setUnsafe(p, val)
);
}
setUnsafe(p: K, val: V): boolean {
if (this.k) {
if (equivArrayLike(this.k, p)) {
this.v = val;
return false;
}
this.ensureChild(__childID(this.k, this.pos)).setUnsafe(
this.k,
this.v!
);
delete this.k;
delete this.v;
}
if (this.children) {
return this.ensureChild(__childID(p, this.pos)).setUnsafe(p, val);
} else {
this.k = p;
this.v = val;
}
return true;
}
query<T>(
fn: Fn<NdQtNode<K, V>, T>,
p: K,
r: number,
max: number,
acc: T[],
distFn: DistanceFn
) {
return __addResults(
fn,
this.doQuery(
p,
r,
max,
new Heap<[number, NdQtNode<K, V>?]>([[r * r]], {
compare: CMP,
}),
distFn
).values,
acc
);
}
queryKeys(p: K, r: number, max: number, acc: K[], distFn: DistanceFn): K[] {
return this.query((n) => <K>n.k, p, r, max, acc, distFn);
}
queryValues(
p: K,
r: number,
max: number,
acc: V[],
distFn: DistanceFn
): V[] {
return this.query((n) => <V>n.v, p, r, max, acc, distFn);
}
containsPoint(p: K) {
return pointInCenteredBox(p, this.pos, this.ext);
}
nodeForPoint(p: K): MaybeNdQtNode<K, V> {
if (this.k && equivArrayLike(this.k, p)) {
return this;
}
if (this.children) {
const child = this.children[__childID(p, this.pos)];
return child ? child.nodeForPoint(p) : undefined;
}
}
protected doQuery(
p: K,
r: number,
max: number,
acc: Heap<[number, NdQtNode<K, V>?]>,
distFn: DistanceFn
): Heap<[number, NdQtNode<K, V>?]> {
if (!testCenteredBoxSphere(this.pos, this.ext, p, r)) return acc;
if (this.k) {
const d = distFn(this.k, p);
if (d <= acc.values[0][0]) {
acc.length >= max
? acc.pushPop([d, this])
: acc.push([d, this]);
}
} else if (this.children) {
for (
let i = MAX_CHILDREN[this.pos.length], j = this.numC;
i-- > 0 && j > 0;
) {
if (this.children[i]) {
this.children[i].doQuery(p, r, max, acc, distFn);
j--;
}
}
}
return acc;
}
protected ensureChild(id: number) {
!this.children && (this.children = []);
let c = this.children[id];
if (!c) {
const csize = mulN([], this.ext, 0.5);
this.children[id] = c = new NdQtNode(
this,
madd([], csize, CHILD_OFFSETS[csize.length][id], this.pos),
csize
);
this.numC++;
}
return c;
}
}
/**
* Point-based quadtree for nD keys and optional value association. Supports
* radial range queries and key removal with tree pruning. See
* {@link NdQuadtreeMap.fromMinMax}.
*
* @remarks
* Partially ported from Clojure version of thi.ng/geom.
*/
export class NdQuadtreeMap<K extends ReadonlyVec, V>
implements
ICopy<NdQuadtreeMap<K, V>>,
IEmpty<NdQuadtreeMap<K, V>>,
IRegionQuery<K, V, number>,
ISpatialMap<K, V>
{
static readonly MAX_DIM = 16;
/**
* Returns a new point-based `NdQuadtreeMap` for nD keys in given region
* defined by `min` / `max` coordinates. The dimensionality of the tree is
* implicitly defined by the provided coordinates. Only points within that
* region can be indexed.
*
* @remarks
* Due to exponentially growing lookup tables, currently only supports up to
* 16 dimensions.
*/
static fromMinMax<K extends ReadonlyVec, V>(
min: ReadonlyVec,
max: ReadonlyVec
) {
return new NdQuadtreeMap<K, V>(
addmN([], min, max, 0.5),
submN([], max, min, 0.5)
);
}
root: NdQtNode<K, V>;
protected _size: number;
constructor(
pos: ReadonlyVec,
ext: ReadonlyVec,
pairs?: Iterable<Pair<K, V>>,
public readonly distanceFn: DistanceFn = distSq
) {
const dim = pos.length;
assert(
dim > 0 && dim <= NdQuadtreeMap.MAX_DIM,
`illegal dimension: ${dim}`
);
assert(ext.length === dim, `pos/ext dimensions must be equal`);
__initChildOffsets(dim);
this.root = new NdQtNode(undefined, pos, ext);
this._size = 0;
pairs && this.into(pairs, -1);
}
get size() {
return this._size;
}
[Symbol.iterator](): IterableIterator<Pair<K, V>> {
return map((n) => [n.k!, n.v!], this.nodes());
}
keys() {
return map((n) => <K>n.k, this.nodes());
}
values() {
return map((n) => <V>n.v, this.nodes());
}
*nodes(all = false) {
let queue: NdQtNode<K, V>[] = [this.root];
while (queue.length) {
const n = queue.pop();
if (n) {
if (all || n.k) yield n;
if (n.children) queue = queue.concat(n.children);
}
}
}
copy(): NdQuadtreeMap<K, V> {
const tree = new NdQuadtreeMap<K, V>(
this.root.pos,
this.root.ext,
this,
this.distanceFn
);
return tree;
}
clear() {
this.root.clear();
this._size = 0;
}
empty() {
return new NdQuadtreeMap<K, V>(
this.root.pos,
this.root.ext,
undefined,
this.distanceFn
);
}
set(key: K, val: V, eps = EPS) {
if (this.root.set(key, val, eps, this.distanceFn)) {
this._size++;
return true;
}
return false;
}
into(pairs: Iterable<Pair<K, V>>, eps = EPS) {
return __into(this, pairs, eps);
}
remove(p: K) {
let node = this.root.nodeForPoint(p);
if (!node) return false;
this._size--;
delete node.k;
delete node.v;
let doPrune = true;
while (node.parent) {
node = node!.parent;
delete node.children![__childID(p, node.pos)];
doPrune = --node.numC === 0;
if (doPrune) delete node.children;
else break;
}
return true;
}
has(p: K, eps = EPS) {
return !!(eps <= 0
? this.root.nodeForPoint(p)
: this.root.queryKeys(p, eps, 1, [], this.distanceFn).length);
}
get(p: K, eps = EPS) {
if (eps <= 0) {
const node = this.root.nodeForPoint(p);
return node ? node.v : undefined;
}
return this.root.queryValues(p, eps, 1, [], this.distanceFn)[0];
}
query(p: K, r: number, max = 1, acc: Pair<K, V>[] = []) {
return this.root.query(
(n) => <Pair<K, V>>[n.k, n.v],
p,
r,
max,
acc,
this.distanceFn
);
}
queryKeys(p: K, r: number, max = 1, acc: K[] = []) {
return this.root.queryKeys(p, r, max, acc, this.distanceFn);
}
queryValues(p: K, r: number, max = 1, acc: V[] = []) {
return this.root.queryValues(p, r, max, acc, this.distanceFn);
}
containsPoint(p: K) {
return this.root.containsPoint(p);
}
nodeForPoint(p: K): MaybeNdQtNode<K, V> {
return this.root.nodeForPoint(p);
}
}
/** @internal */
const MAX_CHILDREN = [
...take(
NdQuadtreeMap.MAX_DIM + 1,
iterate((x) => x * 2, 1)
),
];
/** @internal */
const CHILD_OFFSETS: ReadonlyVec[][] = [];
/** @internal */
const __initChildOffsets = (dim: number) =>
CHILD_OFFSETS[dim] ||
(CHILD_OFFSETS[dim] = [...permutations(...repeat([-1, 1], dim))]);
/** @internal */
const __childID: MultiVecOpRoVV<number> = vop(0);
__childID.add(1, (p, q) => (p[0] >= q[0] ? 1 : 0));
__childID.add(2, (p, q) => (p[0] >= q[0] ? 2 : 0) | (p[1] >= q[1] ? 1 : 0));
__childID.add(
3,
(p, q) =>
(p[0] >= q[0] ? 4 : 0) | (p[1] >= q[1] ? 2 : 0) | (p[2] >= q[2] ? 1 : 0)
);
__childID.add(
4,
(p, q) =>
(p[0] >= q[0] ? 8 : 0) |
(p[1] >= q[1] ? 4 : 0) |
(p[2] >= q[2] ? 2 : 0) |
(p[3] >= q[3] ? 1 : 0)
);
__childID.default((p, q) => {
let id = 0;
for (let i = 0, n = p.length - 1, bit = 1 << n; i <= n; i++, bit >>>= 1) {
p[i] >= q[i] && (id += bit);
}
return id;
});