@geoblocks/cesium-bvh 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +59 -2
  3. package/cesium-bvh.js +627 -0
  4. package/package.json +22 -4
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2020-present, camptocamp SA
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # Bounding volume hierarchy for triangles
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Rays and nearest-point queries against a triangle soup: the nearest hit along a ray, whether any lies within a distance, how many, every
4
+ one, and the closest triangle to a point; and, over line segments, those near a point or in a box. Flat typed arrays (a worker takes them as they are), no dependency: not Cesium, not three.js, not the
5
+ DOM. It serves a CesiumJS scene's picking, collisions and measuring, and anything else that asks questions of triangles.
6
+
7
+ - nodes packed depth first in typed arrays, the left child right after its parent
8
+ - a split chosen over binned surface areas (SAH); a ray walks the near child first, and a query that wants any hit stops at the first
9
+ - a ray hits both sides of a face; the least distance from its start, 0.1 mm by default, is yours to set (a negative one, `-Infinity`, counts a hit at the start)
10
+ - a hint (the triangle that blocked the last ray) is tried first: the rays of a point toward a sun five minutes on are near each other
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm i --save @geoblocks/cesium-bvh
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```js
21
+ import {buildBvh, bvhQueries} from '@geoblocks/cesium-bvh';
22
+
23
+ // a triangle each, nine numbers: its first corner, then its two edges from it (`trianglesOf(groups)` makes them of groups
24
+ // of `{vertices, triangles}`: x, y, z a vertex, three indices a triangle)
25
+ const tris = Float64Array.of(-5, -5, 0, 10, 0, 0, 0, 10, 0);
26
+ const bvh = buildBvh(tris); // a subset of the triangles by number: buildBvh(tris, [0, 2, 5])
27
+ const queries = bvhQueries(bvh, {min: 0.01}); // a ray starting on a surface is not to hit it
28
+
29
+ queries.nearest(0, 0, 3, 0, 0, -1, 100); // 3, the distance of the nearest hit within 100 m, or Infinity
30
+ queries.nearestHit(0, 0, 3, 0, 0, -1, 100); // {triangle: 0, distance: 3}, the same with its triangle, or undefined
31
+ queries.any(0, 0, 3, 0, 0, -1, 100); // 0, the number of a triangle hit, or -1
32
+ queries.count(0, 0, 3, 0, 0, -1, 100, 6); // 1, the hits, counted to 6
33
+ queries.hits(0, 0, 3, 0, 0, -1, 100); // [3], every hit, nearest first
34
+ queries.closest(0, 0, 0.5, 2); // {triangle: 0, distance: 0.5, point: [0, 0, 0]}, the nearest triangle within 2 m and its nearest point, or undefined
35
+ ```
36
+
37
+ Line segments (edges), a tree of their own:
38
+
39
+ ```js
40
+ import {buildSegmentBvh, segmentQueries} from '@geoblocks/cesium-bvh';
41
+
42
+ const segments = Float64Array.of(0, 0, 0, 1, 0, 0, 5, 5, 5, 6, 5, 5); // a segment each, six numbers: its two ends
43
+ const edges = segmentQueries(buildSegmentBvh(segments));
44
+
45
+ edges.near(5.5, 5, 5.05, 0.1); // [1], the segments within 0.1 m of a point
46
+ edges.overlapping(-1, -1, -1, 0.5, 1, 1); // [0], those whose boxes meet a box
47
+ ```
48
+
49
+ Triangles that moved (a piece dragged, a door opened), the tree kept: its boxes made again from the leaves up, in place, a few milliseconds for 45,000 triangles (a build takes 130):
50
+
51
+ ```js
52
+ refitBvh(bvh, movedTris); // the same triangles, the same numbers, new places; `queries` made of `bvh` follow
53
+ ```
54
+
55
+ The tree is plain arrays (`bounds`, `meta`, `data`, `ids`): send them to a worker, and make the queries there.
56
+
57
+ ## Not here
58
+
59
+ - A tree that restructures as triangles move: `refitBvh` keeps the shape, so it answers right but slower the farther triangles have gone; rebuild it then.
60
+ - Triangles by a box, a sphere or a capsule: the arrays are laid out to walk, as `closest` and the segments' queries do.
package/cesium-bvh.js ADDED
@@ -0,0 +1,627 @@
1
+ // A bounding volume hierarchy over triangles, for rays and for the nearest triangle to a point: the nearest hit along a ray, whether any lies
2
+ // within a distance, how many, every one; the closest triangle within a radius. Flat typed arrays (a worker takes them as they are), no dependency,
3
+ // no Cesium, no DOM: any scene, in Node and in the browser.
4
+ //
5
+ // The ideas are the established ones (three-mesh-bvh, flatbush, Aila and Laine): nodes packed depth first in typed arrays, the left child
6
+ // right after its parent; a split chosen over binned surface areas (SAH); a ray walks the near child first, by its sign on the split axis,
7
+ // and a query that wants any hit stops at the first.
8
+
9
+ const BINS = 16;
10
+ // a node's bins: a quarter of its triangles, from MIN_BINS to BINS
11
+ const MIN_BINS = 4;
12
+ // the cost of a box test against a triangle's, in the split's estimate
13
+ const TRAVERSAL = 0.5;
14
+ const STACK = 128;
15
+ const stackNode = new Int32Array(STACK);
16
+ const stackNear = new Float64Array(STACK);
17
+
18
+ /**
19
+ * The tree over primitives' boxes: the nodes, and the primitives' order, in leaves.
20
+ * @param {Float64Array} lo Each primitive's lowest corner, three numbers a primitive.
21
+ * @param {Float64Array} hi Its highest.
22
+ * @param {number} leaf The most primitives a leaf holds.
23
+ */
24
+ function buildTree(lo, hi, leaf) {
25
+ const n = lo.length / 3;
26
+ const mid = Float64Array.from(lo, (v, i) => (v + hi[i]) / 2);
27
+ // the triangles are permuted with their boxes: `at` says where each is
28
+ const at = Int32Array.from({length: n}, (_, i) => i);
29
+ const bounds = new Float64Array(Math.max(1, 2 * n) * 6);
30
+ const meta = new Int32Array(Math.max(1, 2 * n) * 3);
31
+ let nodes = 0;
32
+ const binCount = new Int32Array(BINS), binLo = new Float64Array(BINS * 3), binHi = new Float64Array(BINS * 3);
33
+ const rightArea = new Float64Array(BINS);
34
+ /**
35
+ * @param {number} x0
36
+ * @param {number} y0
37
+ * @param {number} z0
38
+ * @param {number} x1
39
+ * @param {number} y1
40
+ * @param {number} z1
41
+ */
42
+ const area = (x0, y0, z0, x1, y1, z1) => {
43
+ const [dx, dy, dz] = [x1 - x0, y1 - y0, z1 - z0];
44
+ return dx < 0 ? 0 : 2 * (dx * dy + dy * dz + dz * dx);
45
+ };
46
+
47
+ // the node over the triangles [from, to) of `at`; its index
48
+ /**
49
+ * @param {number} from
50
+ * @param {number} to
51
+ */
52
+ const build = (from, to) => {
53
+ const node = nodes++;
54
+ let [x0, y0, z0, x1, y1, z1] = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
55
+ let [cx0, cy0, cz0, cx1, cy1, cz1] = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
56
+ for (let k = from; k < to; k++) {
57
+ const t = at[k] * 3;
58
+ x0 = Math.min(x0, lo[t]); y0 = Math.min(y0, lo[t + 1]); z0 = Math.min(z0, lo[t + 2]);
59
+ x1 = Math.max(x1, hi[t]); y1 = Math.max(y1, hi[t + 1]); z1 = Math.max(z1, hi[t + 2]);
60
+ cx0 = Math.min(cx0, mid[t]); cy0 = Math.min(cy0, mid[t + 1]); cz0 = Math.min(cz0, mid[t + 2]);
61
+ cx1 = Math.max(cx1, mid[t]); cy1 = Math.max(cy1, mid[t + 1]); cz1 = Math.max(cz1, mid[t + 2]);
62
+ }
63
+ bounds.set([x0, y0, z0, x1, y1, z1], node * 6);
64
+ const count = to - from;
65
+ const makeLeaf = () => {
66
+ meta[node * 3] = from;
67
+ meta[node * 3 + 1] = count;
68
+ return node;
69
+ };
70
+ if (count <= leaf) {
71
+ return makeLeaf();
72
+ }
73
+ // the best split over the three axes: the surface areas of the two sides, by their triangles, over BINS bins of the centers
74
+ const [cmin, cmax] = [[cx0, cy0, cz0], [cx1, cy1, cz1]];
75
+ const whole = area(x0, y0, z0, x1, y1, z1);
76
+ // few triangles need few bins: the search over 16 is most of the build's time, in the many small nodes near the leaves
77
+ const bins = Math.max(MIN_BINS, Math.min(BINS, count >> 2));
78
+ let best = {cost: Infinity, axis: -1, bin: 0, bins};
79
+ for (let a = 0; a < 3; a++) {
80
+ const extent = cmax[a] - cmin[a];
81
+ if (!(extent > 1e-12)) {
82
+ continue;
83
+ }
84
+ binCount.fill(0, 0, bins);
85
+ binLo.fill(Infinity, 0, bins * 3);
86
+ binHi.fill(-Infinity, 0, bins * 3);
87
+ const scale = bins / extent;
88
+ for (let k = from; k < to; k++) {
89
+ const t = at[k] * 3;
90
+ const b = Math.min(bins - 1, Math.floor((mid[t + a] - cmin[a]) * scale));
91
+ binCount[b]++;
92
+ for (let c = 0; c < 3; c++) {
93
+ binLo[b * 3 + c] = Math.min(binLo[b * 3 + c], lo[t + c]);
94
+ binHi[b * 3 + c] = Math.max(binHi[b * 3 + c], hi[t + c]);
95
+ }
96
+ }
97
+ // from the right: each split's right area
98
+ let [rx0, ry0, rz0, rx1, ry1, rz1] = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
99
+ for (let b = bins - 1; b > 0; b--) {
100
+ rx0 = Math.min(rx0, binLo[b * 3]); ry0 = Math.min(ry0, binLo[b * 3 + 1]); rz0 = Math.min(rz0, binLo[b * 3 + 2]);
101
+ rx1 = Math.max(rx1, binHi[b * 3]); ry1 = Math.max(ry1, binHi[b * 3 + 1]); rz1 = Math.max(rz1, binHi[b * 3 + 2]);
102
+ rightArea[b] = area(rx0, ry0, rz0, rx1, ry1, rz1);
103
+ }
104
+ let [lx0, ly0, lz0, lx1, ly1, lz1] = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
105
+ let left = 0;
106
+ for (let b = 0; b < bins - 1; b++) {
107
+ lx0 = Math.min(lx0, binLo[b * 3]); ly0 = Math.min(ly0, binLo[b * 3 + 1]); lz0 = Math.min(lz0, binLo[b * 3 + 2]);
108
+ lx1 = Math.max(lx1, binHi[b * 3]); ly1 = Math.max(ly1, binHi[b * 3 + 1]); lz1 = Math.max(lz1, binHi[b * 3 + 2]);
109
+ left += binCount[b];
110
+ if (left === 0 || left === count) {
111
+ continue;
112
+ }
113
+ const cost = TRAVERSAL + (area(lx0, ly0, lz0, lx1, ly1, lz1) * left + rightArea[b + 1] * (count - left)) / (whole || 1);
114
+ if (cost < best.cost) {
115
+ best = {cost, axis: a, bin: b, bins};
116
+ }
117
+ }
118
+ }
119
+ if (best.axis < 0) {
120
+ // no split pays (or all the centers are one point): a leaf, however many, unless it is far over the size
121
+ if (count <= leaf * 4) {
122
+ return makeLeaf();
123
+ }
124
+ const half = from + (count >> 1);
125
+ meta[node * 3 + 2] = 0;
126
+ build(from, half);
127
+ meta[node * 3] = build(half, to);
128
+ return node;
129
+ }
130
+ // partition by the chosen bin
131
+ const scale = best.bins / (cmax[best.axis] - cmin[best.axis]);
132
+ let [i, j] = [from, to - 1];
133
+ while (i <= j) {
134
+ const b = Math.min(best.bins - 1, Math.floor((mid[at[i] * 3 + best.axis] - cmin[best.axis]) * scale));
135
+ if (b <= best.bin) {
136
+ i++;
137
+ } else {
138
+ [at[i], at[j]] = [at[j], at[i]];
139
+ j--;
140
+ }
141
+ }
142
+ // a split that left one side empty (rounding): the middle
143
+ const cut = i === from || i === to ? from + (count >> 1) : i;
144
+ meta[node * 3 + 2] = best.axis;
145
+ build(from, cut);
146
+ meta[node * 3] = build(cut, to);
147
+ return node;
148
+ };
149
+ build(0, n);
150
+ return {bounds: bounds.slice(0, nodes * 6), meta: meta.slice(0, nodes * 3), at, nodes};
151
+ }
152
+
153
+ const EMPTY = {bounds: new Float64Array(0), meta: new Int32Array(0), data: new Float64Array(0), ids: new Int32Array(0), nodes: 0};
154
+
155
+ /**
156
+ * The tree over some triangles.
157
+ * @param {Float64Array} tris A triangle each, nine numbers: its first corner, then its two edges from it.
158
+ * @param {Int32Array | number[]} [ids] The triangles to take; all by default.
159
+ * @param {{leaf?: number}} [options] `leaf`: the most triangles a leaf holds.
160
+ * @return {{bounds: Float64Array, meta: Int32Array, data: Float64Array, ids: Int32Array, nodes: number}} A node's box (six numbers) and
161
+ * `meta` (three: a leaf's first triangle and its count, else its right child, 0, its split axis); `data` the triangles in leaf order
162
+ * (the tris' layout), `ids` their numbers in `tris`.
163
+ */
164
+ export function buildBvh(tris, ids = Int32Array.from({length: tris.length / 9}, (_, i) => i), {leaf = 4} = {}) {
165
+ const n = ids.length;
166
+ if (n === 0) {
167
+ return EMPTY;
168
+ }
169
+ const order = Int32Array.from(ids);
170
+ const lo = new Float64Array(n * 3), hi = new Float64Array(n * 3);
171
+ for (let k = 0; k < n; k++) {
172
+ const o = order[k] * 9;
173
+ for (let a = 0; a < 3; a++) {
174
+ const p = tris[o + a], q = p + tris[o + 3 + a], r = p + tris[o + 6 + a];
175
+ lo[k * 3 + a] = Math.min(p, q, r);
176
+ hi[k * 3 + a] = Math.max(p, q, r);
177
+ }
178
+ }
179
+ const {bounds, meta, at, nodes} = buildTree(lo, hi, leaf);
180
+ const data = new Float64Array(n * 9);
181
+ const sorted = new Int32Array(n);
182
+ for (let k = 0; k < n; k++) {
183
+ sorted[k] = order[at[k]];
184
+ data.set(tris.subarray(sorted[k] * 9, sorted[k] * 9 + 9), k * 9);
185
+ }
186
+ return {bounds, meta, data, ids: sorted, nodes};
187
+ }
188
+
189
+ /**
190
+ * The triangles of groups of vertices and indices, as `buildBvh` takes them: nine numbers each, a corner and its two edges from it, the
191
+ * groups' triangles one after the other, so a triangle's number is its place in the groups' order.
192
+ * @param {{vertices: ArrayLike<number>, triangles: ArrayLike<number>}[]} groups x, y, z a vertex; three indices a triangle.
193
+ * @param {Float64Array} [result] Of the right size: filled instead of a new array, for triangles that moved (`refitBvh`).
194
+ * @return {Float64Array}
195
+ */
196
+ export function trianglesOf(groups, result) {
197
+ const tris = result ?? new Float64Array(9 * groups.reduce((sum, {triangles}) => sum + triangles.length / 3, 0));
198
+ let n = 0;
199
+ for (const {vertices: v, triangles: t} of groups) {
200
+ for (let k = 0; k < t.length; k += 3, n++) {
201
+ const [a, b, c] = [t[k] * 3, t[k + 1] * 3, t[k + 2] * 3];
202
+ tris[n * 9] = v[a];
203
+ tris[n * 9 + 1] = v[a + 1];
204
+ tris[n * 9 + 2] = v[a + 2];
205
+ tris[n * 9 + 3] = v[b] - v[a];
206
+ tris[n * 9 + 4] = v[b + 1] - v[a + 1];
207
+ tris[n * 9 + 5] = v[b + 2] - v[a + 2];
208
+ tris[n * 9 + 6] = v[c] - v[a];
209
+ tris[n * 9 + 7] = v[c + 1] - v[a + 1];
210
+ tris[n * 9 + 8] = v[c + 2] - v[a + 2];
211
+ }
212
+ }
213
+ return tris;
214
+ }
215
+
216
+ /**
217
+ * The tree kept for triangles that have moved: their new corners and edges taken, and every box made again from the leaves up, the
218
+ * tree's shape as it was. A few milliseconds for 45,000 triangles, where a build takes 130; the tree answers right at once, and
219
+ * the more the triangles have gone from where it was built for them the slower it answers (boxes grown to cover both places): build it
220
+ * again when many have moved far.
221
+ * @param {ReturnType<typeof buildBvh>} bvh A tree made by `buildBvh`, changed in place: the queries made of it follow.
222
+ * @param {Float64Array} tris The triangles the tree was built from, moved: the same layout and numbers.
223
+ * @return {ReturnType<typeof buildBvh>} The same tree.
224
+ */
225
+ export function refitBvh(bvh, tris) {
226
+ const {bounds, meta, data, ids, nodes} = bvh;
227
+ if (data.length !== ids.length * 9) {
228
+ throw new Error('refitBvh: not a tree of triangles (nine numbers an element)');
229
+ }
230
+ for (let k = 0; k < ids.length; k++) {
231
+ data.set(tris.subarray(ids[k] * 9, ids[k] * 9 + 9), k * 9);
232
+ }
233
+ // a node comes before its children: from the last, each node's children are done
234
+ for (let node = nodes - 1; node >= 0; node--) {
235
+ const b = node * 6;
236
+ const count = meta[node * 3 + 1];
237
+ if (count > 0) {
238
+ const first = meta[node * 3];
239
+ for (let a = 0; a < 3; a++) {
240
+ let [low, high] = [Infinity, -Infinity];
241
+ for (let k = first; k < first + count; k++) {
242
+ const p = data[k * 9 + a], q = p + data[k * 9 + 3 + a], r = p + data[k * 9 + 6 + a];
243
+ low = Math.min(low, p, q, r);
244
+ high = Math.max(high, p, q, r);
245
+ }
246
+ bounds[b + a] = low;
247
+ bounds[b + 3 + a] = high;
248
+ }
249
+ } else {
250
+ const [left, right] = [(node + 1) * 6, meta[node * 3] * 6];
251
+ for (let a = 0; a < 3; a++) {
252
+ bounds[b + a] = Math.min(bounds[left + a], bounds[right + a]);
253
+ bounds[b + 3 + a] = Math.max(bounds[left + 3 + a], bounds[right + 3 + a]);
254
+ }
255
+ }
256
+ }
257
+ return bvh;
258
+ }
259
+
260
+ /**
261
+ * The tree over some line segments, for `segmentQueries`.
262
+ * @param {Float64Array} segments A segment each, six numbers: its two ends.
263
+ * @param {Int32Array | number[]} [ids] The segments to take; all by default.
264
+ * @param {{leaf?: number}} [options] `leaf`: the most segments a leaf holds.
265
+ * @return {{bounds: Float64Array, meta: Int32Array, data: Float64Array, ids: Int32Array, nodes: number}} As `buildBvh`'s, `data` six numbers a segment.
266
+ */
267
+ export function buildSegmentBvh(segments, ids = Int32Array.from({length: segments.length / 6}, (_, i) => i), {leaf = 4} = {}) {
268
+ const n = ids.length;
269
+ if (n === 0) {
270
+ return EMPTY;
271
+ }
272
+ const order = Int32Array.from(ids);
273
+ const lo = new Float64Array(n * 3), hi = new Float64Array(n * 3);
274
+ for (let k = 0; k < n; k++) {
275
+ for (let a = 0; a < 3; a++) {
276
+ const [p, q] = [segments[order[k] * 6 + a], segments[order[k] * 6 + 3 + a]];
277
+ lo[k * 3 + a] = Math.min(p, q);
278
+ hi[k * 3 + a] = Math.max(p, q);
279
+ }
280
+ }
281
+ const {bounds, meta, at, nodes} = buildTree(lo, hi, leaf);
282
+ const data = new Float64Array(n * 6);
283
+ const sorted = new Int32Array(n);
284
+ for (let k = 0; k < n; k++) {
285
+ sorted[k] = order[at[k]];
286
+ data.set(segments.subarray(sorted[k] * 6, sorted[k] * 6 + 6), k * 6);
287
+ }
288
+ return {bounds, meta, data, ids: sorted, nodes};
289
+ }
290
+
291
+ /**
292
+ * The queries of a tree built by `buildBvh`: a ray from (px, py, pz) along the unit (dx, dy, dz), the triangles hit within `reach` meters,
293
+ * both sides of a face (a hit nearer than `min` is not one); the triangle nearest a point.
294
+ * @param {ReturnType<typeof buildBvh>} bvh
295
+ * @param {{min?: number}} [options] `min`: the least distance a hit is from the ray's start, 0.1 mm by default: a ray starting on a surface is
296
+ * not to hit it. A negative one (`-Infinity`) lets a hit at the start count: a mover standing on a floor.
297
+ */
298
+ export function bvhQueries({bounds, meta, data, ids, nodes}, {min = 1e-4} = {}) {
299
+ /**
300
+ * @param {number} k
301
+ * @param {number} px
302
+ * @param {number} py
303
+ * @param {number} pz
304
+ * @param {number} dx
305
+ * @param {number} dy
306
+ * @param {number} dz
307
+ */
308
+ const hit = (k, px, py, pz, dx, dy, dz) => {
309
+ const o = k * 9;
310
+ const e1x = data[o + 3], e1y = data[o + 4], e1z = data[o + 5], e2x = data[o + 6], e2y = data[o + 7], e2z = data[o + 8];
311
+ const hx = dy * e2z - dz * e2y, hy = dz * e2x - dx * e2z, hz = dx * e2y - dy * e2x;
312
+ const a = e1x * hx + e1y * hy + e1z * hz;
313
+ if (a > -1e-12 && a < 1e-12) {
314
+ return -1;
315
+ }
316
+ const f = 1 / a, sx = px - data[o], sy = py - data[o + 1], sz = pz - data[o + 2];
317
+ const u = f * (sx * hx + sy * hy + sz * hz);
318
+ if (u < 0 || u > 1) {
319
+ return -1;
320
+ }
321
+ const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x;
322
+ const v = f * (dx * qx + dy * qy + dz * qz);
323
+ if (v < 0 || u + v > 1) {
324
+ return -1;
325
+ }
326
+ const t = f * (e2x * qx + e2y * qy + e2z * qz);
327
+ return t > min ? t : -1;
328
+ };
329
+ // where a ray enters a node's box, or Infinity: the slab test, over the ray's inverse direction
330
+ /**
331
+ * @param {number} node
332
+ * @param {number} px
333
+ * @param {number} py
334
+ * @param {number} pz
335
+ * @param {number} ix
336
+ * @param {number} iy
337
+ * @param {number} iz
338
+ * @param {number} tmax
339
+ */
340
+ const enter = (node, px, py, pz, ix, iy, iz, tmax) => {
341
+ const b = node * 6;
342
+ let t0 = 0, t1 = tmax;
343
+ let a = (bounds[b] - px) * ix, c = (bounds[b + 3] - px) * ix;
344
+ t0 = Math.max(t0, a < c ? a : c);
345
+ t1 = Math.min(t1, a < c ? c : a);
346
+ a = (bounds[b + 1] - py) * iy;
347
+ c = (bounds[b + 4] - py) * iy;
348
+ t0 = Math.max(t0, a < c ? a : c);
349
+ t1 = Math.min(t1, a < c ? c : a);
350
+ a = (bounds[b + 2] - pz) * iz;
351
+ c = (bounds[b + 5] - pz) * iz;
352
+ t0 = Math.max(t0, a < c ? a : c);
353
+ t1 = Math.min(t1, a < c ? c : a);
354
+ return t0 <= t1 ? t0 : Infinity;
355
+ };
356
+
357
+ // a ray's way down the tree. A node's box is tested when the node is reached, with the reach the ray has by then; the child the ray
358
+ // meets first (by its sign on the split axis) is walked, the other left on the stack: a query that stops early never tests it.
359
+ /**
360
+ * @param {number} px
361
+ * @param {number} py
362
+ * @param {number} pz
363
+ * @param {number} dx
364
+ * @param {number} dy
365
+ * @param {number} dz
366
+ * @param {number} reach
367
+ * @param {(k: number, t: number, reach: number) => number} found
368
+ */
369
+ const unit = (px, py, pz, dx, dy, dz, reach, found) => {
370
+ // `found(k, t, reach)` per triangle hit: the reach to go on with, or a negative number to stop; called for each triangle in a leaf reached
371
+ if (nodes === 0) {
372
+ return;
373
+ }
374
+ const [ix, iy, iz] = [1 / dx, 1 / dy, 1 / dz];
375
+ let tmax = reach;
376
+ let top = 0;
377
+ let node = 0;
378
+ for (;;) {
379
+ if (enter(node, px, py, pz, ix, iy, iz, tmax) !== Infinity) {
380
+ const count = meta[node * 3 + 1];
381
+ if (count > 0) {
382
+ const first = meta[node * 3];
383
+ for (let k = first; k < first + count; k++) {
384
+ const t = hit(k, px, py, pz, dx, dy, dz);
385
+ if (t >= 0 && t <= tmax) {
386
+ tmax = found(k, t, tmax);
387
+ if (tmax < 0) {
388
+ return;
389
+ }
390
+ }
391
+ }
392
+ } else {
393
+ const axis = meta[node * 3 + 2];
394
+ const negative = axis === 0 ? dx < 0 : axis === 1 ? dy < 0 : dz < 0;
395
+ const right = meta[node * 3];
396
+ stackNode[top++] = negative ? node + 1 : right;
397
+ node = negative ? right : node + 1;
398
+ continue;
399
+ }
400
+ }
401
+ if (top === 0) {
402
+ return;
403
+ }
404
+ node = stackNode[--top];
405
+ }
406
+ };
407
+
408
+ // the squared distance from a point to a node's box
409
+ /**
410
+ * @param {number} node
411
+ * @param {number} px
412
+ * @param {number} py
413
+ * @param {number} pz
414
+ */
415
+ const boxDistance2 = (node, px, py, pz) => {
416
+ const b = node * 6;
417
+ const dx = Math.max(bounds[b] - px, 0, px - bounds[b + 3]);
418
+ const dy = Math.max(bounds[b + 1] - py, 0, py - bounds[b + 4]);
419
+ const dz = Math.max(bounds[b + 2] - pz, 0, pz - bounds[b + 5]);
420
+ return dx * dx + dy * dy + dz * dz;
421
+ };
422
+ // the offset from a triangle's corner to the nearest point of it, as triangleDistance2 last found it
423
+ const offset = new Float64Array(3);
424
+ // the squared distance from a point to a triangle: to the nearest point of it, by the region the point falls in (Ericson's)
425
+ /**
426
+ * @param {number} k
427
+ * @param {number} px
428
+ * @param {number} py
429
+ * @param {number} pz
430
+ */
431
+ const triangleDistance2 = (k, px, py, pz) => {
432
+ const o = k * 9;
433
+ const [abx, aby, abz, acx, acy, acz] = [data[o + 3], data[o + 4], data[o + 5], data[o + 6], data[o + 7], data[o + 8]];
434
+ const [apx, apy, apz] = [px - data[o], py - data[o + 1], pz - data[o + 2]];
435
+ const to = (/** @type {number} */ x, /** @type {number} */ y, /** @type {number} */ z) => {
436
+ offset[0] = x;
437
+ offset[1] = y;
438
+ offset[2] = z;
439
+ return (apx - x) ** 2 + (apy - y) ** 2 + (apz - z) ** 2;
440
+ };
441
+ const d1 = abx * apx + aby * apy + abz * apz, d2 = acx * apx + acy * apy + acz * apz;
442
+ if (d1 <= 0 && d2 <= 0) {
443
+ return to(0, 0, 0);
444
+ }
445
+ const [bpx, bpy, bpz] = [apx - abx, apy - aby, apz - abz];
446
+ const d3 = abx * bpx + aby * bpy + abz * bpz, d4 = acx * bpx + acy * bpy + acz * bpz;
447
+ if (d3 >= 0 && d4 <= d3) {
448
+ return to(abx, aby, abz);
449
+ }
450
+ const vc = d1 * d4 - d3 * d2;
451
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {
452
+ const v = d1 / (d1 - d3);
453
+ return to(abx * v, aby * v, abz * v);
454
+ }
455
+ const [cpx, cpy, cpz] = [apx - acx, apy - acy, apz - acz];
456
+ const d5 = abx * cpx + aby * cpy + abz * cpz, d6 = acx * cpx + acy * cpy + acz * cpz;
457
+ if (d6 >= 0 && d5 <= d6) {
458
+ return to(acx, acy, acz);
459
+ }
460
+ const vb = d5 * d2 - d1 * d6;
461
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {
462
+ const w = d2 / (d2 - d6);
463
+ return to(acx * w, acy * w, acz * w);
464
+ }
465
+ const va = d3 * d6 - d5 * d4;
466
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
467
+ const w = (d4 - d3) / (d4 - d3 + d5 - d6);
468
+ return to(abx + (acx - abx) * w, aby + (acy - aby) * w, abz + (acz - abz) * w);
469
+ }
470
+ const denominator = 1 / (va + vb + vc);
471
+ const [v, w] = [vb * denominator, vc * denominator];
472
+ return to(abx * v + acx * w, aby * v + acy * w, abz * v + acz * w);
473
+ };
474
+
475
+ return {
476
+ /** The distance to the nearest hit within `reach`, or Infinity. */
477
+ nearest(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ dx, /** @type {number} */ dy, /** @type {number} */ dz, /** @type {number} */ reach) {
478
+ let best = Infinity;
479
+ unit(px, py, pz, dx, dy, dz, reach, (_k, t) => ((best = t), t));
480
+ return best;
481
+ },
482
+ /** The nearest hit within `reach`: its triangle's number (in the `tris` the tree was built from) and its distance; none: undefined. */
483
+ nearestHit(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ dx, /** @type {number} */ dy, /** @type {number} */ dz, /** @type {number} */ reach) {
484
+ let [best, found] = [Infinity, -1];
485
+ unit(px, py, pz, dx, dy, dz, reach, (k, t) => ((best = t), (found = k), t));
486
+ return found < 0 ? undefined : {triangle: ids[found], distance: best};
487
+ },
488
+ /**
489
+ * A triangle hit within `reach`, its number, or -1 if none is. `hint`, a triangle that blocked a ray before, is tried first: the rays of
490
+ * one point toward a sun five minutes on are near the last, and the same triangle most often stops them.
491
+ */
492
+ any(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ dx, /** @type {number} */ dy, /** @type {number} */ dz, /** @type {number} */ reach, /** @type {number} */ hint = -1) {
493
+ if (hint >= 0) {
494
+ const t = hit(hint, px, py, pz, dx, dy, dz);
495
+ if (t >= 0 && t <= reach) {
496
+ return hint;
497
+ }
498
+ }
499
+ let found = -1;
500
+ unit(px, py, pz, dx, dy, dz, reach, k => ((found = k), -1));
501
+ return found;
502
+ },
503
+ /** How many triangles are hit within `reach`, to `cap`. */
504
+ count(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ dx, /** @type {number} */ dy, /** @type {number} */ dz, /** @type {number} */ reach, /** @type {number} */ cap = Infinity) {
505
+ let n = 0;
506
+ unit(px, py, pz, dx, dy, dz, reach, (_k, _t, tmax) => (++n >= cap ? -1 : tmax));
507
+ return n;
508
+ },
509
+ /** The distances of every hit within `reach`, nearest first. */
510
+ hits(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ dx, /** @type {number} */ dy, /** @type {number} */ dz, /** @type {number} */ reach) {
511
+ /** @type {number[]} */
512
+ const found = [];
513
+ unit(px, py, pz, dx, dy, dz, reach, (_k, t, tmax) => (found.push(t), tmax));
514
+ return found.sort((a, b) => a - b);
515
+ },
516
+ /** The triangle nearest a point within `radius` meters, its number (in the `tris` the tree was built from), its distance and the nearest point of it; none: undefined. */
517
+ closest(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ radius) {
518
+ if (nodes === 0) {
519
+ return undefined;
520
+ }
521
+ let [best, found, top, node, near] = [radius * radius, -1, 0, 0, boxDistance2(0, px, py, pz)];
522
+ for (;;) {
523
+ if (near <= best) {
524
+ const count = meta[node * 3 + 1];
525
+ if (count > 0) {
526
+ const first = meta[node * 3];
527
+ for (let k = first; k < first + count; k++) {
528
+ const d = triangleDistance2(k, px, py, pz);
529
+ if (d <= best) {
530
+ [best, found] = [d, k];
531
+ }
532
+ }
533
+ } else {
534
+ const [left, right] = [node + 1, meta[node * 3]];
535
+ const [dl, dr] = [boxDistance2(left, px, py, pz), boxDistance2(right, px, py, pz)];
536
+ const [first, second, df, ds] = dl <= dr ? [left, right, dl, dr] : [right, left, dr, dl];
537
+ if (ds <= best) {
538
+ stackNode[top] = second;
539
+ stackNear[top++] = ds;
540
+ }
541
+ [node, near] = [first, df];
542
+ continue;
543
+ }
544
+ }
545
+ do {
546
+ if (top === 0) {
547
+ if (found < 0) {
548
+ return undefined;
549
+ }
550
+ triangleDistance2(found, px, py, pz);
551
+ const o = found * 9;
552
+ const point = [0, 1, 2].map(a => data[o + a] + offset[a]);
553
+ return {triangle: ids[found], distance: Math.sqrt(best), point};
554
+ }
555
+ top--;
556
+ [node, near] = [stackNode[top], stackNear[top]];
557
+ } while (near > best);
558
+ }
559
+ },
560
+ };
561
+ }
562
+
563
+ /**
564
+ * The queries of a tree built by `buildSegmentBvh`: the segments within a distance of a point, and those whose boxes meet a box. Each gives the
565
+ * segments' numbers in the array the tree was built from, in no order.
566
+ * @param {ReturnType<typeof buildSegmentBvh>} bvh
567
+ */
568
+ export function segmentQueries({bounds, meta, data, ids, nodes}) {
569
+ // walks the nodes whose boxes `reaches` says, and gives the leaves' segments `takes` says
570
+ /**
571
+ * @param {(node: number) => boolean} reaches A node's offset in `bounds`.
572
+ * @param {(segment: number) => boolean} takes A segment's offset in `data`.
573
+ */
574
+ const walk = (reaches, takes) => {
575
+ /** @type {number[]} */
576
+ const found = [];
577
+ if (nodes === 0) {
578
+ return found;
579
+ }
580
+ let [top, node] = [0, 0];
581
+ for (;;) {
582
+ if (reaches(node * 6)) {
583
+ const count = meta[node * 3 + 1];
584
+ if (count > 0) {
585
+ for (let k = meta[node * 3]; k < meta[node * 3] + count; k++) {
586
+ if (takes(k * 6)) {
587
+ found.push(ids[k]);
588
+ }
589
+ }
590
+ } else {
591
+ stackNode[top++] = meta[node * 3];
592
+ node += 1;
593
+ continue;
594
+ }
595
+ }
596
+ if (top === 0) {
597
+ return found;
598
+ }
599
+ node = stackNode[--top];
600
+ }
601
+ };
602
+ return {
603
+ /** The segments within `radius` meters of a point. */
604
+ near(/** @type {number} */ px, /** @type {number} */ py, /** @type {number} */ pz, /** @type {number} */ radius) {
605
+ const r2 = radius * radius;
606
+ return walk(b => {
607
+ const dx = Math.max(bounds[b] - px, 0, px - bounds[b + 3]);
608
+ const dy = Math.max(bounds[b + 1] - py, 0, py - bounds[b + 4]);
609
+ const dz = Math.max(bounds[b + 2] - pz, 0, pz - bounds[b + 5]);
610
+ return dx * dx + dy * dy + dz * dz <= r2;
611
+ }, o => {
612
+ const [ax, ay, az] = [data[o], data[o + 1], data[o + 2]];
613
+ const [rx, ry, rz] = [data[o + 3] - ax, data[o + 4] - ay, data[o + 5] - az];
614
+ const length = rx * rx + ry * ry + rz * rz;
615
+ const t = length > 0 ? Math.min(1, Math.max(0, ((px - ax) * rx + (py - ay) * ry + (pz - az) * rz) / length)) : 0;
616
+ const [dx, dy, dz] = [px - ax - t * rx, py - ay - t * ry, pz - az - t * rz];
617
+ return dx * dx + dy * dy + dz * dz <= r2;
618
+ });
619
+ },
620
+ /** The segments whose boxes (an end to the other) meet the box from (x0, y0, z0) to (x1, y1, z1). */
621
+ overlapping(/** @type {number} */ x0, /** @type {number} */ y0, /** @type {number} */ z0, /** @type {number} */ x1, /** @type {number} */ y1, /** @type {number} */ z1) {
622
+ return walk(b => bounds[b] <= x1 && bounds[b + 3] >= x0 && bounds[b + 1] <= y1 && bounds[b + 4] >= y0 && bounds[b + 2] <= z1 && bounds[b + 5] >= z0,
623
+ o => Math.min(data[o], data[o + 3]) <= x1 && Math.max(data[o], data[o + 3]) >= x0 && Math.min(data[o + 1], data[o + 4]) <= y1
624
+ && Math.max(data[o + 1], data[o + 4]) >= y0 && Math.min(data[o + 2], data[o + 5]) <= z1 && Math.max(data[o + 2], data[o + 5]) >= z0);
625
+ },
626
+ };
627
+ }
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@geoblocks/cesium-bvh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "BSD-3-Clause",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/geoblocks/cesium-helpers/",
9
+ "directory": "packages/cesium-bvh"
10
+ },
11
+ "main": "cesium-bvh.js",
12
+ "module": "cesium-bvh.js",
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": "./cesium-bvh.js"
16
+ },
17
+ "files": [
18
+ "cesium-bvh.js"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "gitHead": "c1e407611f437b0da1057ef0373c74ace28ad58a"
24
+ }