@floless/app 0.144.0 → 0.145.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.
- package/dist/floless-server.cjs +1336 -1258
- package/dist/web/chat.css +17 -2
- package/dist/web/chat.js +2 -1
- package/dist/web/index.html +3 -3
- package/dist/web/model-measure.js +75 -18
- package/dist/web/model-pointer-dock.js +7 -2
- package/dist/web/model-snap-contract.js +14 -0
- package/dist/web/model-snapping.js +564 -139
- package/dist/web/model-viewport-revit-adapter.js +60 -0
- package/package.json +1 -1
|
@@ -1,31 +1,208 @@
|
|
|
1
1
|
// Provider-neutral mesh acquisition. Semantic endpoints/axes/grids are separate authenticated
|
|
2
2
|
// provider candidates; tessellation data is never relabelled as authored model meaning.
|
|
3
|
-
import {
|
|
4
|
-
|
|
3
|
+
import {
|
|
4
|
+
MODEL_SNAP_INDEX_POLICY_V1, MODEL_SNAP_KIND_ORDER, MODEL_SNAP_LIMITS_V1, MODEL_SNAP_SCHEMA,
|
|
5
|
+
} from './model-snap-contract.js';
|
|
6
|
+
import { projectPointOnSegment2d, projectPointOnSegment3d, SEG_DEGENERACY } from './steel-3d-core.js';
|
|
5
7
|
|
|
6
8
|
export const MODEL_SNAP_ACQUISITION_RADIUS_PX = MODEL_SNAP_LIMITS_V1.acquisitionRadiusCssPx;
|
|
7
9
|
export const MODEL_SNAP_TIE_EPSILON_PX = MODEL_SNAP_LIMITS_V1.distanceTieCssPx;
|
|
8
|
-
export const MODEL_SNAP_QUERY_CAP =
|
|
10
|
+
export const MODEL_SNAP_QUERY_CAP = MODEL_SNAP_INDEX_POLICY_V1.queryEvaluationCap;
|
|
11
|
+
// The RESIDENT budget of the on-demand index: the element tiles kept in memory at once. Both are
|
|
12
|
+
// exact accounting over typed arrays (#1747) — the old 96-bytes-per-object estimate under-counted
|
|
13
|
+
// the real cost roughly sixfold, so "256 MB" used to mean about 1 GB.
|
|
9
14
|
export const MODEL_SNAP_INDEX_MAX_CANDIDATES = 2_000_000;
|
|
10
15
|
export const MODEL_SNAP_INDEX_MAX_BYTES = 256 * 1024 * 1024;
|
|
11
16
|
|
|
12
17
|
const KIND_RANK = new Map(MODEL_SNAP_KIND_ORDER.map((kind, index) => [kind, index]));
|
|
13
18
|
const EDGE_CARRIER_KIND = 'mesh-edge-carrier';
|
|
14
|
-
const
|
|
19
|
+
const TILE_OVERHEAD_BYTES = 512;
|
|
20
|
+
// Elements above this many triangles are indexed in runs of this size (see buildModelSnapIndex).
|
|
21
|
+
const CHUNK_TRIANGLES = 16_384;
|
|
22
|
+
// The most topology one pointer move may index (in candidates) before it answers "not yet".
|
|
23
|
+
const MAX_BUILD_WORK_PER_QUERY = 262_144;
|
|
24
|
+
// The most snap readings one pointer event may test for being hidden. The check runs until the first
|
|
25
|
+
// visible reading; running out of tests first is a refusal ("too much here"), never a silent miss.
|
|
26
|
+
export const MODEL_SNAP_MAX_OCCLUSION_CHECKS = 24;
|
|
15
27
|
const finitePoint = (point) => Array.isArray(point) && point.length === 3 && point.every(Number.isFinite);
|
|
16
28
|
const frozenPoint = (point) => Object.freeze([...point]);
|
|
17
29
|
const midpoint = (a, b) => a.map((value, axis) => (value + b[axis]) / 2);
|
|
18
30
|
const interpolate = (a, b, t) => a.map((value, axis) => value + (b[axis] - value) * t);
|
|
19
31
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
32
|
+
/**
|
|
33
|
+
* The refusal of one pointer position. `reason` tells the UI which remedy is true: `crowded` clears
|
|
34
|
+
* by zooming in (the region shrinks with the zoom) or by hiding/clipping what is in the way (hidden
|
|
35
|
+
* and clipped geometry is never indexed); `pending` clears by itself within a few moves or frames (the
|
|
36
|
+
* region is still being indexed, a bounded amount per move); `element` clears by neither (one run of
|
|
37
|
+
* one element alone is larger than the whole budget — unreachable at the default budget).
|
|
38
|
+
*/
|
|
39
|
+
const REFUSALS = Object.freeze({
|
|
40
|
+
crowded: Object.freeze({ code: 'over-budget', reason: 'crowded',
|
|
41
|
+
message: 'Too much model detail is near the pointer to check every corner and edge at this zoom. Zoom in, or hide or section-box what is in the way, and snapping resumes.' }),
|
|
42
|
+
pending: Object.freeze({ code: 'over-budget', reason: 'pending',
|
|
43
|
+
message: 'The model around the pointer is still being read for snapping. Hold the pointer still for a moment and snapping resumes.' }),
|
|
44
|
+
element: Object.freeze({ code: 'over-budget', reason: 'element',
|
|
45
|
+
message: 'This element has more detail than snapping can hold, so its corners and edges cannot be snapped to. Zooming in will not change that.' }),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** World-transform reader: a typed matrix path for real meshes, `localToWorld` for plain doubles. */
|
|
49
|
+
function worldReader(mesh) {
|
|
50
|
+
mesh.updateWorldMatrix?.(true, false);
|
|
51
|
+
const e = mesh.matrixWorld?.elements;
|
|
52
|
+
if (e && e.length === 16 && Array.prototype.every.call(e, Number.isFinite)) {
|
|
53
|
+
// Identical to Vector3.applyMatrix4 (which localToWorld uses), including the projective divide.
|
|
54
|
+
return (x, y, z, out, offset) => {
|
|
55
|
+
const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
|
|
56
|
+
out[offset] = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
|
|
57
|
+
out[offset + 1] = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
|
|
58
|
+
out[offset + 2] = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const Vector = mesh.position?.constructor;
|
|
62
|
+
if (!Vector || typeof mesh.localToWorld !== 'function') return null;
|
|
63
|
+
return (x, y, z, out, offset) => {
|
|
64
|
+
const value = mesh.localToWorld(new Vector(x, y, z)).toArray();
|
|
65
|
+
out[offset] = value[0]; out[offset + 1] = value[1]; out[offset + 2] = value[2];
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const nextPowerOfTwo = (value) => 2 ** Math.ceil(Math.log2(Math.max(2, value)));
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* What building one chunk's tile can cost, known before allocating anything. `resident` is an upper
|
|
73
|
+
* bound on the kept tile (deduplication only shrinks it) and `transient` an upper bound on the peak of
|
|
74
|
+
* the build itself.
|
|
75
|
+
*/
|
|
76
|
+
function tileCost(entry) {
|
|
77
|
+
const indexed = !!entry.indices;
|
|
78
|
+
const triangles = entry.triEnd - entry.triStart;
|
|
79
|
+
const edgeSlots = triangles * 3;
|
|
80
|
+
const vertexSlots = indexed ? Math.min(entry.vertexCount, edgeSlots) : edgeSlots;
|
|
81
|
+
const tableSize = indexed ? nextPowerOfTwo(edgeSlots * 2) : 0;
|
|
82
|
+
const resident = TILE_OVERHEAD_BYTES + vertexSlots * (24 + 8) + edgeSlots * 13;
|
|
83
|
+
// Peak: the full-size working arrays AND their compacted copies exist together for a moment, plus the
|
|
84
|
+
// vertex remap (a Map, ~48 B per entry) and the edge hash table.
|
|
85
|
+
return { indexed, edgeSlots, vertexSlots, tableSize, resident, candidates: vertexSlots + edgeSlots,
|
|
86
|
+
transient: resident * 2 + (indexed ? vertexSlots * 48 + tableSize * 8 : 0) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Build the COMPLETE snap topology of one chunk (a run of an element's triangles) into compact typed
|
|
91
|
+
* arrays, or return null when it cannot fit. Feature ids are the ones the old whole-model index gave
|
|
92
|
+
* the same features (source vertex index, sorted source edge pair, or triangle:corner/edge for
|
|
93
|
+
* unindexed meshes), so the same vertex reached through two chunks is the same candidate.
|
|
94
|
+
*/
|
|
95
|
+
function buildTile(entry, maxCandidates, maxBytes) {
|
|
96
|
+
const { position, indices, vertexCount, transform, triStart, triEnd } = entry;
|
|
97
|
+
const { indexed, edgeSlots, vertexSlots, tableSize, transient } = tileCost(entry);
|
|
98
|
+
if (transient > maxBytes) return null; // its build alone would need more than the whole budget
|
|
99
|
+
const world = new Float64Array(vertexSlots * 3); // compacted: only the vertices this chunk uses
|
|
100
|
+
const vertexFeature = new Uint32Array(vertexSlots), vertexTriangle = new Uint32Array(vertexSlots);
|
|
101
|
+
const edgeA = new Uint32Array(edgeSlots), edgeB = new Uint32Array(edgeSlots);
|
|
102
|
+
const edgeTriangle = new Uint32Array(edgeSlots), edgeOrdinal = new Uint8Array(edgeSlots);
|
|
103
|
+
const local = indexed ? new Map() : null; // source vertex index → compacted slot
|
|
104
|
+
const tableKeys = indexed ? new Float64Array(tableSize) : null; // key + 1; 0 = empty slot
|
|
105
|
+
const scratch = new Float64Array(3);
|
|
106
|
+
let vertices = 0, edges = 0;
|
|
107
|
+
const source = [0, 0, 0], slots = [0, 0, 0];
|
|
108
|
+
for (let triangle = triStart; triangle < triEnd; triangle++) {
|
|
109
|
+
for (let corner = 0; corner < 3; corner++) source[corner] = indexed ? Number(indices[triangle * 3 + corner]) : triangle * 3 + corner;
|
|
110
|
+
if (indexed && !source.every((value) => Number.isInteger(value) && value >= 0 && value < vertexCount)) continue;
|
|
111
|
+
let finite = true;
|
|
112
|
+
for (let corner = 0; corner < 3 && finite; corner++) {
|
|
113
|
+
const known = indexed ? local.get(source[corner]) : undefined;
|
|
114
|
+
if (known !== undefined) { slots[corner] = known; continue; }
|
|
115
|
+
transform(position.getX(source[corner]), position.getY(source[corner]), position.getZ(source[corner]), scratch, 0);
|
|
116
|
+
finite = Number.isFinite(scratch[0]) && Number.isFinite(scratch[1]) && Number.isFinite(scratch[2]);
|
|
117
|
+
slots[corner] = -1;
|
|
118
|
+
}
|
|
119
|
+
if (!finite) continue;
|
|
120
|
+
for (let corner = 0; corner < 3; corner++) {
|
|
121
|
+
if (slots[corner] >= 0) continue;
|
|
122
|
+
// A degenerate triangle can repeat a corner ([5, 5, 6]): the second one is the vertex just added.
|
|
123
|
+
const repeated = indexed ? local.get(source[corner]) : undefined;
|
|
124
|
+
if (repeated !== undefined) { slots[corner] = repeated; continue; }
|
|
125
|
+
transform(position.getX(source[corner]), position.getY(source[corner]), position.getZ(source[corner]), world, vertices * 3);
|
|
126
|
+
if (indexed) local.set(source[corner], vertices);
|
|
127
|
+
vertexFeature[vertices] = source[corner]; vertexTriangle[vertices] = triangle; slots[corner] = vertices; vertices++;
|
|
128
|
+
}
|
|
129
|
+
for (let ordinal = 0; ordinal < 3; ordinal++) {
|
|
130
|
+
const next = (ordinal + 1) % 3;
|
|
131
|
+
if (indexed) {
|
|
132
|
+
const low = Math.min(source[ordinal], source[next]), high = Math.max(source[ordinal], source[next]);
|
|
133
|
+
const key = low * vertexCount + high + 1;
|
|
134
|
+
let probe = (Math.imul(low, 0x9e3779b1) ^ Math.imul(high, 0x85ebca6b)) & (tableSize - 1);
|
|
135
|
+
let duplicate = false;
|
|
136
|
+
while (tableKeys[probe] !== 0) {
|
|
137
|
+
if (tableKeys[probe] === key) { duplicate = true; break; }
|
|
138
|
+
probe = (probe + 1) & (tableSize - 1);
|
|
139
|
+
}
|
|
140
|
+
if (duplicate) continue;
|
|
141
|
+
tableKeys[probe] = key;
|
|
142
|
+
}
|
|
143
|
+
edgeA[edges] = slots[ordinal]; edgeB[edges] = slots[next]; edgeTriangle[edges] = triangle; edgeOrdinal[edges] = ordinal; edges++;
|
|
144
|
+
}
|
|
145
|
+
if (vertices + edges > maxCandidates) return null; // already too large: stop paying for the rest
|
|
146
|
+
}
|
|
147
|
+
const tile = {
|
|
148
|
+
indexed, world: world.slice(0, vertices * 3), vertices, edges,
|
|
149
|
+
vertexFeature: vertexFeature.slice(0, vertices), vertexTriangle: vertexTriangle.slice(0, vertices),
|
|
150
|
+
edgeA: edgeA.slice(0, edges), edgeB: edgeB.slice(0, edges),
|
|
151
|
+
edgeTriangle: edgeTriangle.slice(0, edges), edgeOrdinal: edgeOrdinal.slice(0, edges),
|
|
152
|
+
};
|
|
153
|
+
tile.candidates = vertices + edges;
|
|
154
|
+
tile.bytes = TILE_OVERHEAD_BYTES + tile.world.byteLength + tile.vertexFeature.byteLength + tile.vertexTriangle.byteLength
|
|
155
|
+
+ tile.edgeA.byteLength + tile.edgeB.byteLength + tile.edgeTriangle.byteLength + tile.edgeOrdinal.byteLength;
|
|
156
|
+
if (tile.candidates > maxCandidates || tile.bytes > maxBytes) return null;
|
|
157
|
+
return tile;
|
|
24
158
|
}
|
|
25
159
|
|
|
26
160
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
161
|
+
* Distance between 3D segments [a, b] and [c, d]. When the closest points of the two infinite lines fall
|
|
162
|
+
* inside both segments, that is the answer. Otherwise the minimum lies on the boundary of the parameter
|
|
163
|
+
* square, which is always an endpoint of one segment against the other — the shared clamped projection.
|
|
164
|
+
*/
|
|
165
|
+
export function segmentSegmentDistance(a, b, c, d) {
|
|
166
|
+
const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2];
|
|
167
|
+
const vx = d[0] - c[0], vy = d[1] - c[1], vz = d[2] - c[2];
|
|
168
|
+
const wx = a[0] - c[0], wy = a[1] - c[1], wz = a[2] - c[2];
|
|
169
|
+
const uu = ux * ux + uy * uy + uz * uz, vv = vx * vx + vy * vy + vz * vz, uv = ux * vx + uy * vy + uz * vz;
|
|
170
|
+
const uw = ux * wx + uy * wy + uz * wz, vw = vx * wx + vy * wy + vz * wz;
|
|
171
|
+
const denominator = uu * vv - uv * uv;
|
|
172
|
+
if (denominator > 1e-12 * uu * vv) {
|
|
173
|
+
const s = (uv * vw - vv * uw) / denominator, t = (uu * vw - uv * uw) / denominator;
|
|
174
|
+
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) return Math.hypot(wx + ux * s - vx * t, wy + uy * s - vy * t, wz + uz * s - vz * t);
|
|
175
|
+
}
|
|
176
|
+
const rule = SEG_DEGENERACY.atMost(0);
|
|
177
|
+
return Math.min(projectPointOnSegment3d(a, c, d, rule).distance, projectPointOnSegment3d(b, c, d, rule).distance,
|
|
178
|
+
projectPointOnSegment3d(c, a, b, rule).distance, projectPointOnSegment3d(d, a, b, rule).distance);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Does segment [a, b] meet the box [min, max] grown by `grow` on every side? A slab test on the grown
|
|
182
|
+
// box is a conservative superset of "within `grow` of the box" — safe for selecting what to index.
|
|
183
|
+
function segmentMeetsGrownBox(a, b, boxes, offset, grow) {
|
|
184
|
+
let enter = 0, exit = 1;
|
|
185
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
186
|
+
const low = boxes[offset + axis] - grow, high = boxes[offset + 3 + axis] + grow;
|
|
187
|
+
const start = a[axis], delta = b[axis] - start;
|
|
188
|
+
if (Math.abs(delta) < 1e-300) { if (start < low || start > high) return false; continue; }
|
|
189
|
+
let t0 = (low - start) / delta, t1 = (high - start) / delta;
|
|
190
|
+
if (t0 > t1) { const swap = t0; t0 = t1; t1 = swap; }
|
|
191
|
+
if (t0 > enter) enter = t0;
|
|
192
|
+
if (t1 < exit) exit = t1;
|
|
193
|
+
if (enter > exit) return false;
|
|
194
|
+
}
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Build an ON-DEMAND snap index (#1747). Building records only each element's world envelope, one
|
|
200
|
+
* typed pass over its vertices; an element's full topology is indexed the first time a pointer
|
|
201
|
+
* region reaches it and kept in a least-recently-used cache bounded by both limits.
|
|
202
|
+
*
|
|
203
|
+
* Completeness is per query, not per model: every element whose envelope meets the pointer's region
|
|
204
|
+
* is indexed completely, or the query is refused (`pointerRefusal()`), so a traversal prefix or a
|
|
205
|
+
* truncated neighbourhood is never exposed.
|
|
29
206
|
*/
|
|
30
207
|
export function buildModelSnapIndex(meshes, {
|
|
31
208
|
maxCandidates = MODEL_SNAP_INDEX_MAX_CANDIDATES,
|
|
@@ -34,170 +211,418 @@ export function buildModelSnapIndex(meshes, {
|
|
|
34
211
|
if (!Number.isSafeInteger(maxCandidates) || maxCandidates < 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1) {
|
|
35
212
|
throw new TypeError('Model snap index limits must be positive safe integers.');
|
|
36
213
|
}
|
|
37
|
-
const candidates = [];
|
|
38
214
|
const limits = Object.freeze({ maxCandidates, maxBytes });
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
215
|
+
const entries = [];
|
|
216
|
+
const envelopes = [];
|
|
217
|
+
const modelMin = [Infinity, Infinity, Infinity], modelMax = [-Infinity, -Infinity, -Infinity];
|
|
218
|
+
const scratch = new Float64Array(3);
|
|
43
219
|
for (const [meshOrdinal, mesh] of [...(meshes ?? [])].entries()) {
|
|
44
|
-
mesh
|
|
45
|
-
const position = mesh.geometry?.getAttribute?.('position');
|
|
220
|
+
const position = mesh?.geometry?.getAttribute?.('position');
|
|
46
221
|
if (!position?.count) continue;
|
|
47
|
-
const
|
|
48
|
-
if (!
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
};
|
|
222
|
+
const transform = worldReader(mesh);
|
|
223
|
+
if (!transform) continue;
|
|
224
|
+
const indices = mesh.geometry.index?.array ?? null;
|
|
225
|
+
const vertexCount = position.count;
|
|
226
|
+
const triangleCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertexCount / 3);
|
|
227
|
+
if (!triangleCount) continue;
|
|
54
228
|
const entityId = mesh.userData?.entityId ?? null;
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const source = indices
|
|
63
|
-
? [Number(indices[triangle * 3]), Number(indices[triangle * 3 + 1]), Number(indices[triangle * 3 + 2])]
|
|
64
|
-
: [triangle * 3, triangle * 3 + 1, triangle * 3 + 2];
|
|
65
|
-
const trianglePoints = source.map(pointAt);
|
|
66
|
-
if (!trianglePoints.every(finitePoint)) continue;
|
|
67
|
-
for (let corner = 0; corner < 3; corner++) {
|
|
68
|
-
const feature = indices ? String(source[corner]) : `${triangle}:${corner}`;
|
|
69
|
-
if (!vertexKeys.has(feature)) {
|
|
70
|
-
vertexKeys.add(feature);
|
|
71
|
-
if (!push({ id: `${meshId}:v:${feature}`, kind: 'mesh-vertex', point: frozenPoint(trianglePoints[corner]), entityId,
|
|
72
|
-
meshOrdinal, triangleOrdinal: triangle, featureOrdinal: indices ? source[corner] : corner })) {
|
|
73
|
-
return disabledIndex('over-budget', 'Mesh snapping is unavailable because the complete topology exceeds its fixed index budget.', limits);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
229
|
+
const base = { mesh, meshOrdinal, entityId, meshId: `${meshOrdinal}:${String(entityId ?? 'unowned')}`,
|
|
230
|
+
position, indices, vertexCount, transform };
|
|
231
|
+
const addEntry = (triStart, triEnd, min, max) => {
|
|
232
|
+
if (!Number.isFinite(min[0])) return;
|
|
233
|
+
entries.push({ ...base, triStart, triEnd }); envelopes.push(...min, ...max);
|
|
234
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
235
|
+
modelMin[axis] = Math.min(modelMin[axis], min[axis]); modelMax[axis] = Math.max(modelMax[axis], max[axis]);
|
|
76
236
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
237
|
+
};
|
|
238
|
+
const grow = (min, max, x, y, z) => {
|
|
239
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) return;
|
|
240
|
+
if (x < min[0]) min[0] = x; if (y < min[1]) min[1] = y; if (z < min[2]) min[2] = z;
|
|
241
|
+
if (x > max[0]) max[0] = x; if (y > max[1]) max[1] = y; if (z > max[2]) max[2] = z;
|
|
242
|
+
};
|
|
243
|
+
const pointCount = indices ? vertexCount : triangleCount * 3;
|
|
244
|
+
if (triangleCount <= CHUNK_TRIANGLES) {
|
|
245
|
+
// The common case — one Revit element, one modest mesh: one pass over its vertices.
|
|
246
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
247
|
+
for (let index = 0; index < pointCount; index++) {
|
|
248
|
+
transform(position.getX(index), position.getY(index), position.getZ(index), scratch, 0);
|
|
249
|
+
grow(min, max, scratch[0], scratch[1], scratch[2]);
|
|
250
|
+
}
|
|
251
|
+
addEntry(0, triangleCount, min, max);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
// A very large element is split into runs of triangles, each with its own envelope, so a pointer
|
|
255
|
+
// near one part of it indexes that part only (and one huge element cannot exceed the budget). Each
|
|
256
|
+
// corner is transformed where it is read, so no whole-element copy is held outside the budget.
|
|
257
|
+
for (let triStart = 0; triStart < triangleCount; triStart += CHUNK_TRIANGLES) {
|
|
258
|
+
const triEnd = Math.min(triangleCount, triStart + CHUNK_TRIANGLES);
|
|
259
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
260
|
+
for (let corner = triStart * 3; corner < triEnd * 3; corner++) {
|
|
261
|
+
const point = indices ? Number(indices[corner]) : corner;
|
|
262
|
+
if (!Number.isInteger(point) || point < 0 || point >= pointCount) continue;
|
|
263
|
+
transform(position.getX(point), position.getY(point), position.getZ(point), scratch, 0);
|
|
264
|
+
grow(min, max, scratch[0], scratch[1], scratch[2]);
|
|
91
265
|
}
|
|
266
|
+
addEntry(triStart, triEnd, min, max);
|
|
92
267
|
}
|
|
93
268
|
}
|
|
269
|
+
const boxes = Float64Array.from(envelopes);
|
|
270
|
+
const meshCount = new Set(entries.map((entry) => entry.meshOrdinal)).size;
|
|
271
|
+
const extent = entries.length
|
|
272
|
+
? Math.max(Math.hypot(modelMax[0] - modelMin[0], modelMax[1] - modelMin[1], modelMax[2] - modelMin[2]), 1e-6)
|
|
273
|
+
: 1;
|
|
274
|
+
|
|
275
|
+
const tiles = new Map(); // entry position → tile, least recently used first
|
|
276
|
+
const oversize = new Set();
|
|
277
|
+
// Exact size of every element built so far, kept after eviction (8 bytes per element), so a region
|
|
278
|
+
// can be judged against the budget before anything is built for it.
|
|
279
|
+
const knownCandidates = new Float64Array(entries.length).fill(-1);
|
|
280
|
+
const knownBytes = new Float64Array(entries.length).fill(-1);
|
|
281
|
+
let residentCandidates = 0, residentBytes = 0, builds = 0, evictions = 0, lastRefusal = null, regionMeshes = [];
|
|
282
|
+
const evict = (key) => {
|
|
283
|
+
const tile = tiles.get(key); if (!tile) return;
|
|
284
|
+
tiles.delete(key); residentCandidates -= tile.candidates; residentBytes -= tile.bytes; evictions++;
|
|
285
|
+
};
|
|
286
|
+
const touch = (key) => { const tile = tiles.get(key); tiles.delete(key); tiles.set(key, tile); return tile; };
|
|
287
|
+
const overBudget = () => residentCandidates > maxCandidates || residentBytes > maxBytes;
|
|
288
|
+
const refuse = (refusal) => { lastRefusal = refusal; return Object.freeze([]); };
|
|
289
|
+
|
|
290
|
+
const candidateAt = (entry, tile, kind, slot) => {
|
|
291
|
+
const { meshOrdinal, entityId, meshId } = entry; const world = tile.world;
|
|
292
|
+
const at = (point) => Object.freeze([world[point * 3], world[point * 3 + 1], world[point * 3 + 2]]);
|
|
293
|
+
if (kind === 'vertex') {
|
|
294
|
+
const feature = tile.vertexFeature[slot], triangle = tile.vertexTriangle[slot];
|
|
295
|
+
const key = tile.indexed ? String(feature) : `${triangle}:${feature - triangle * 3}`;
|
|
296
|
+
return Object.freeze({ id: `${meshId}:v:${key}`, kind: 'mesh-vertex', point: at(slot), entityId,
|
|
297
|
+
meshOrdinal, triangleOrdinal: triangle, featureOrdinal: tile.indexed ? feature : feature - triangle * 3 });
|
|
298
|
+
}
|
|
299
|
+
const left = tile.edgeA[slot], right = tile.edgeB[slot], triangle = tile.edgeTriangle[slot], ordinal = tile.edgeOrdinal[slot];
|
|
300
|
+
const sourceLeft = tile.vertexFeature[left], sourceRight = tile.vertexFeature[right];
|
|
301
|
+
const pair = tile.indexed ? [Math.min(sourceLeft, sourceRight), Math.max(sourceLeft, sourceRight)] : [ordinal, (ordinal + 1) % 3];
|
|
302
|
+
const edgeFeature = tile.indexed ? `${pair[0]}:${pair[1]}` : `${triangle}:${ordinal}`;
|
|
303
|
+
const a = at(left), b = at(right);
|
|
304
|
+
return Object.freeze({ id: `${meshId}:e:${edgeFeature}`, kind: EDGE_CARRIER_KIND, point: frozenPoint(midpoint(a, b)),
|
|
305
|
+
entityId, meshOrdinal, triangleOrdinal: triangle, featureOrdinal: ordinal,
|
|
306
|
+
sourceIndices: Object.freeze(pair), segment: Object.freeze([a, b]) });
|
|
307
|
+
};
|
|
94
308
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const cellSize = Math.max(diagonal / 16, 1e-6);
|
|
106
|
-
const cell = (point) => point.map((value, axis) => Math.floor((value - min[axis]) / cellSize));
|
|
107
|
-
const buckets = new Map();
|
|
108
|
-
frozen.forEach((candidate, index) => { const key = cell(candidate.point).join(','); const bucket = buckets.get(key) ?? []; bucket.push(index); buckets.set(key, bucket); });
|
|
109
|
-
const query = (hint, limit = MODEL_SNAP_QUERY_CAP) => {
|
|
309
|
+
/**
|
|
310
|
+
* Every candidate within `region.radius` of the segment from `region.origin` (or of `hint` alone
|
|
311
|
+
* when no origin is known) to `hint`. Returns [] and sets `pointerRefusal()` when that region cannot
|
|
312
|
+
* be checked completely within the budget; clears it otherwise.
|
|
313
|
+
* @param {readonly number[]} hint
|
|
314
|
+
* @param {number} [limit]
|
|
315
|
+
* @param {{radius:number, origin:readonly number[]|null}|null} [region]
|
|
316
|
+
*/
|
|
317
|
+
const query = (hint, limit = MODEL_SNAP_QUERY_CAP, region = null) => {
|
|
318
|
+
lastRefusal = null; regionMeshes = [];
|
|
110
319
|
if (!finitePoint(hint)) return Object.freeze([]);
|
|
320
|
+
const radius = Number.isFinite(region?.radius) && region.radius > 0 ? region.radius : null;
|
|
321
|
+
if (radius === null) return Object.freeze([]);
|
|
111
322
|
const cap = Math.max(1, Math.min(MODEL_SNAP_QUERY_CAP, Math.floor(limit) || MODEL_SNAP_QUERY_CAP));
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
323
|
+
const origin = finitePoint(region?.origin) ? region.origin : hint;
|
|
324
|
+
// The region runs from the ray origin through the surface hit and on past it by a few radii. On a
|
|
325
|
+
// surface seen at a grazing angle, the part of the snap circle that lies FURTHER from the eye than
|
|
326
|
+
// the hit sits on that surface well behind the hit point (tan(incidence) x the lateral radius); the
|
|
327
|
+
// reach covers it down to a few degrees of grazing (policy `behindHitReach`).
|
|
328
|
+
const along = [hint[0] - origin[0], hint[1] - origin[1], hint[2] - origin[2]];
|
|
329
|
+
const alongLength = Math.hypot(along[0], along[1], along[2]);
|
|
330
|
+
const reach = alongLength > 0 ? MODEL_SNAP_INDEX_POLICY_V1.behindHitReach * radius / alongLength : 0;
|
|
331
|
+
const end = [hint[0] + along[0] * reach, hint[1] + along[1] * reach, hint[2] + along[2] * reach];
|
|
332
|
+
const includeElement = typeof region?.includeElement === 'function' ? region.includeElement : null;
|
|
333
|
+
const selected = [];
|
|
334
|
+
for (let key = 0; key < entries.length; key++) {
|
|
335
|
+
if (!segmentMeetsGrownBox(origin, end, boxes, key * 6, radius)) continue;
|
|
336
|
+
// Hidden and section-clipped geometry is not snapped to and costs nothing: the caller's
|
|
337
|
+
// visibility (the same rule its surface pick uses) is asked per run, with the run's envelope.
|
|
338
|
+
if (includeElement && !includeElement(entries[key].mesh, boxes.subarray(key * 6, key * 6 + 3), boxes.subarray(key * 6 + 3, key * 6 + 6))) continue;
|
|
339
|
+
selected.push(key);
|
|
340
|
+
}
|
|
341
|
+
regionMeshes = [...new Set(selected.map((key) => entries[key].mesh))];
|
|
342
|
+
if (selected.some((key) => oversize.has(key))) return refuse(REFUSALS.element);
|
|
343
|
+
// Every verdict below is on EXACT sizes: a chunk's size is only known once it has been built (it is
|
|
344
|
+
// remembered after eviction). Already-known sizes can refuse the region before anything is built.
|
|
345
|
+
let knownTotal = 0, knownTotalBytes = 0;
|
|
346
|
+
for (const key of selected) if (knownCandidates[key] >= 0) { knownTotal += knownCandidates[key]; knownTotalBytes += knownBytes[key]; }
|
|
347
|
+
if (knownTotal > maxCandidates || knownTotalBytes > maxBytes) return refuse(REFUSALS.crowded);
|
|
348
|
+
const wanted = new Set(selected);
|
|
349
|
+
let work = 0, unfinished = false, overflow = false;
|
|
350
|
+
const ensure = (key) => {
|
|
351
|
+
if (tiles.has(key)) { touch(key); return true; }
|
|
352
|
+
// One pointer move builds a bounded amount; what it could not reach is built by the next moves
|
|
353
|
+
// (sizes are remembered), so a far zoom costs a few short moves, never one long freeze.
|
|
354
|
+
const cost = tileCost(entries[key]);
|
|
355
|
+
const size = knownCandidates[key] >= 0 ? knownCandidates[key] : cost.candidates;
|
|
356
|
+
if (work > 0 && work + size > MAX_BUILD_WORK_PER_QUERY) { unfinished = true; return true; }
|
|
357
|
+
work += size;
|
|
358
|
+
// Make room BEFORE building, from tiles this query does not need, least recently used first, so
|
|
359
|
+
// the resident set plus this build's peak stays inside the budget whenever that is possible.
|
|
360
|
+
for (const residentKey of [...tiles.keys()]) {
|
|
361
|
+
if (residentCandidates + cost.candidates <= maxCandidates && residentBytes + cost.transient <= maxBytes) break;
|
|
362
|
+
if (!wanted.has(residentKey)) evict(residentKey);
|
|
117
363
|
}
|
|
118
|
-
|
|
364
|
+
// Still no room in MEMORY: building now could exceed the byte budget at its peak, so the region
|
|
365
|
+
// cannot be checked within it. (Only the region's own resident runs remain at this point.) The
|
|
366
|
+
// candidate count is not judged here on the pre-deduplication bound; the exact count decides it.
|
|
367
|
+
if (tiles.size && residentBytes + cost.transient > maxBytes) { overflow = true; return true; }
|
|
368
|
+
const tile = buildTile(entries[key], maxCandidates, maxBytes); builds++;
|
|
369
|
+
if (!tile) { oversize.add(key); return false; }
|
|
370
|
+
tiles.set(key, tile); residentCandidates += tile.candidates; residentBytes += tile.bytes;
|
|
371
|
+
knownCandidates[key] = tile.vertices + tile.edges; knownBytes[key] = tile.bytes;
|
|
372
|
+
knownTotal += tile.candidates; knownTotalBytes += tile.bytes;
|
|
373
|
+
return true;
|
|
374
|
+
};
|
|
375
|
+
const restoreBound = () => {
|
|
376
|
+
// Unneeded tiles go first; only when this one region alone is larger than the budget, the least
|
|
377
|
+
// recently used of its own tiles as well.
|
|
378
|
+
for (const residentKey of [...tiles.keys()]) { if (!overBudget()) break; if (!wanted.has(residentKey)) evict(residentKey); }
|
|
379
|
+
for (const residentKey of [...tiles.keys()]) { if (!overBudget()) break; evict(residentKey); }
|
|
380
|
+
};
|
|
381
|
+
// Pass 1 — learn the size of every chunk in the region that has never been built.
|
|
382
|
+
for (const key of selected) {
|
|
383
|
+
if (knownCandidates[key] >= 0) continue;
|
|
384
|
+
if (!ensure(key)) { restoreBound(); return refuse(REFUSALS.element); }
|
|
385
|
+
if (knownTotal > maxCandidates || knownTotalBytes > maxBytes) { restoreBound(); return refuse(REFUSALS.crowded); }
|
|
119
386
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
387
|
+
if (overflow) { restoreBound(); return refuse(REFUSALS.crowded); }
|
|
388
|
+
// Part of the region was never measured: answering now would be a partial answer. It is not "too
|
|
389
|
+
// much detail" (the region may well fit) — the next moves, or the caller's retry, finish it.
|
|
390
|
+
if (unfinished) { restoreBound(); return refuse(REFUSALS.pending); }
|
|
391
|
+
// Pass 2 — the whole region fits: make every chunk of it resident (rebuilding any evicted ones).
|
|
392
|
+
for (const key of selected) if (!ensure(key)) { restoreBound(); return refuse(REFUSALS.element); }
|
|
393
|
+
restoreBound();
|
|
394
|
+
if (overflow) return refuse(REFUSALS.crowded);
|
|
395
|
+
if (unfinished || selected.some((key) => !tiles.has(key))) return refuse(REFUSALS.pending);
|
|
396
|
+
|
|
397
|
+
const [hx, hy, hz] = end, [ox, oy, oz] = origin;
|
|
398
|
+
// Candidates are materialised as they qualify. A vertex or edge on the seam between two chunks of
|
|
399
|
+
// one element qualifies in both with the same id and is kept once.
|
|
400
|
+
const found = [], ids = new Set();
|
|
401
|
+
const accept = (candidate) => {
|
|
402
|
+
if (ids.has(candidate.id)) return true;
|
|
403
|
+
if (found.length >= cap) return false;
|
|
404
|
+
ids.add(candidate.id); found.push(candidate); return true;
|
|
405
|
+
};
|
|
406
|
+
// The region's own box, grown by its radius: a cheap first test before the exact distance.
|
|
407
|
+
const low = [Math.min(ox, hx) - radius, Math.min(oy, hy) - radius, Math.min(oz, hz) - radius];
|
|
408
|
+
const high = [Math.max(ox, hx) + radius, Math.max(oy, hy) + radius, Math.max(oz, hz) + radius];
|
|
409
|
+
const axisSegment = [origin, end], exact = SEG_DEGENERACY.atMost(0);
|
|
410
|
+
// Second cheap test: distance to the region's axis LINE (never more than the distance to its
|
|
411
|
+
// segment, so nothing inside the region is rejected). No clamp, no allocation per feature.
|
|
412
|
+
const ux = hx - ox, uy = hy - oy, uz = hz - oz, uu = ux * ux + uy * uy + uz * uz;
|
|
413
|
+
const lineDistanceSq = (x, y, z) => {
|
|
414
|
+
const wx = x - ox, wy = y - oy, wz = z - oz, along = wx * ux + wy * uy + wz * uz;
|
|
415
|
+
return wx * wx + wy * wy + wz * wz - (uu > 0 ? along * along / uu : 0);
|
|
416
|
+
};
|
|
417
|
+
const radiusSq = radius * radius;
|
|
418
|
+
for (const key of selected) {
|
|
419
|
+
const entry = entries[key], tile = tiles.get(key), world = tile.world;
|
|
420
|
+
for (let slot = 0; slot < tile.vertices; slot++) {
|
|
421
|
+
const x = world[slot * 3], y = world[slot * 3 + 1], z = world[slot * 3 + 2];
|
|
422
|
+
if (x < low[0] || x > high[0] || y < low[1] || y > high[1] || z < low[2] || z > high[2]) continue;
|
|
423
|
+
if (lineDistanceSq(x, y, z) > radiusSq) continue;
|
|
424
|
+
if (projectPointOnSegment3d([x, y, z], axisSegment[0], axisSegment[1], exact).distance <= radius
|
|
425
|
+
&& !accept(candidateAt(entry, tile, 'vertex', slot))) return refuse(REFUSALS.crowded);
|
|
426
|
+
}
|
|
427
|
+
for (let slot = 0; slot < tile.edges; slot++) {
|
|
428
|
+
const a = tile.edgeA[slot] * 3, b = tile.edgeB[slot] * 3;
|
|
429
|
+
// An edge whose own box misses the region's box cannot be within the radius.
|
|
430
|
+
if (Math.max(world[a], world[b]) < low[0] || Math.min(world[a], world[b]) > high[0]
|
|
431
|
+
|| Math.max(world[a + 1], world[b + 1]) < low[1] || Math.min(world[a + 1], world[b + 1]) > high[1]
|
|
432
|
+
|| Math.max(world[a + 2], world[b + 2]) < low[2] || Math.min(world[a + 2], world[b + 2]) > high[2]) continue;
|
|
433
|
+
// Every point of the edge is within half its length of its midpoint, so an edge whose midpoint is
|
|
434
|
+
// further than radius + half-length from the axis line cannot come within the radius.
|
|
435
|
+
const mx = (world[a] + world[b]) / 2, my = (world[a + 1] + world[b + 1]) / 2, mz = (world[a + 2] + world[b + 2]) / 2;
|
|
436
|
+
const half = Math.hypot(world[b] - world[a], world[b + 1] - world[a + 1], world[b + 2] - world[a + 2]) / 2;
|
|
437
|
+
if (Math.sqrt(Math.max(0, lineDistanceSq(mx, my, mz))) > radius + half) continue;
|
|
438
|
+
const start = [world[a], world[a + 1], world[a + 2]], finish = [world[b], world[b + 1], world[b + 2]];
|
|
439
|
+
if (segmentSegmentDistance(start, finish, origin, end) <= radius
|
|
440
|
+
&& !accept(candidateAt(entry, tile, 'edge', slot))) return refuse(REFUSALS.crowded);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return Object.freeze(found);
|
|
123
444
|
};
|
|
124
|
-
|
|
445
|
+
|
|
446
|
+
return Object.freeze({
|
|
447
|
+
available: true, mode: 'on-demand', refusal: null, truncated: false, ...limits, extent, query,
|
|
448
|
+
/** The refusal of the most recent query, or null when it checked its whole region. */
|
|
449
|
+
pointerRefusal: () => lastRefusal,
|
|
450
|
+
/** The meshes the most recent query's region reached: every possible occluder of its candidates. */
|
|
451
|
+
regionMeshes: () => regionMeshes,
|
|
452
|
+
/** The caller could not finish checking this pointer's readings (their visibility): refuse it. */
|
|
453
|
+
refusePointer: (reason) => { lastRefusal = REFUSALS[reason] ?? REFUSALS.crowded; },
|
|
454
|
+
stats: () => Object.freeze({ elements: meshCount, chunks: entries.length, residentChunks: tiles.size, residentCandidates,
|
|
455
|
+
residentBytes, builds, evictions, oversizeChunks: oversize.size }),
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The pointer's sightline region for one event: the world radius of `radiusPx` at the surface under
|
|
461
|
+
* the pointer, grown by the policy margin, and the ray origin the pick used. Returns null when the
|
|
462
|
+
* camera projection cannot give a finite scale there (the caller then acquires nothing, exactly as
|
|
463
|
+
* for an off-screen hint).
|
|
464
|
+
*
|
|
465
|
+
* The caller's `project` is finite-differenced along the three world axes to get its 2x3 Jacobian J
|
|
466
|
+
* at the hint. J's smallest non-zero singular value is the LEAST screen movement per unit of world
|
|
467
|
+
* movement across the sightline (its null direction is the sightline itself, which the capsule covers
|
|
468
|
+
* lengthwise). Dividing the pixel radius by it therefore bounds every lateral offset that can still
|
|
469
|
+
* land inside the circle — for orthographic and perspective cameras alike, on or off the view axis.
|
|
470
|
+
* The margin absorbs the perspective change of that scale over the region's own depth.
|
|
471
|
+
*/
|
|
472
|
+
export function modelSnapRegion(index, project, worldHint, radiusPx, rayOrigin = null) {
|
|
473
|
+
if (!finitePoint(worldHint) || !Number.isFinite(radiusPx) || radiusPx <= 0) return null;
|
|
474
|
+
const at = (point) => { const value = project(point); return Number.isFinite(value?.x) && Number.isFinite(value?.y) ? value : null; };
|
|
475
|
+
const base = at(worldHint); if (!base) return null;
|
|
476
|
+
// The difference step must stay local to the hit: a millionth of its distance from the eye when that
|
|
477
|
+
// is known (so it never reaches the near plane), else of the model's size.
|
|
478
|
+
const depth = finitePoint(rayOrigin) ? Math.hypot(worldHint[0] - rayOrigin[0], worldHint[1] - rayOrigin[1], worldHint[2] - rayOrigin[2]) : 0;
|
|
479
|
+
const step = Math.max((depth > 0 ? depth : Number.isFinite(index?.extent) ? index.extent : 1) * 1e-6, 1e-12);
|
|
480
|
+
let xx = 0, xy = 0, yy = 0;
|
|
481
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
482
|
+
const moved = [...worldHint]; moved[axis] += step;
|
|
483
|
+
const value = at(moved); if (!value) return null;
|
|
484
|
+
const dx = (value.x - base.x) / step, dy = (value.y - base.y) / step;
|
|
485
|
+
xx += dx * dx; xy += dx * dy; yy += dy * dy;
|
|
486
|
+
}
|
|
487
|
+
// Eigenvalues of J·Jᵀ (2x2, symmetric) are the squared singular values of J.
|
|
488
|
+
const mean = (xx + yy) / 2, spread = Math.hypot((xx - yy) / 2, xy);
|
|
489
|
+
const leastScale = Math.sqrt(Math.max(0, mean - spread));
|
|
490
|
+
if (!(leastScale > 0) || !Number.isFinite(leastScale)) return null;
|
|
491
|
+
const radius = MODEL_SNAP_INDEX_POLICY_V1.neighbourhoodMargin * radiusPx / leastScale;
|
|
492
|
+
return Object.freeze({ radius, origin: finitePoint(rayOrigin) ? frozenPoint(rayOrigin) : null });
|
|
125
493
|
}
|
|
126
494
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
495
|
+
/**
|
|
496
|
+
* The point of 3D edge [a, b] whose projection is nearest the pointer. The edge is first clipped to
|
|
497
|
+
* the part the camera can see (an edge running behind the camera still snaps along its visible
|
|
498
|
+
* length), then the screen-space parameter is mapped back to the 3D parameter through the projected
|
|
499
|
+
* midpoint: under perspective, equal screen steps are not equal steps along the edge, and
|
|
500
|
+
* interpolating the 3D ends with the screen parameter lands off the pointer.
|
|
501
|
+
*/
|
|
502
|
+
function nearestOnProjectedEdge(a, b, client, project, seed, includePoint = null, reachPx = Infinity) {
|
|
503
|
+
// "Visible" is the camera's view AND what the viewer keeps (a section box): both are convex, so the
|
|
504
|
+
// usable part of an edge is one run, found by walking from a usable parameter to each limit.
|
|
505
|
+
const visibleAt = (t) => { const point = interpolate(a, b, t); return !!project(point)?.visible && (!includePoint || includePoint(point)); };
|
|
506
|
+
const boundary = (inside, outside) => {
|
|
507
|
+
for (let step = 0; step < 24; step++) { const middle = (inside + outside) / 2; if (visibleAt(middle)) inside = middle; else outside = middle; }
|
|
508
|
+
return inside;
|
|
509
|
+
};
|
|
510
|
+
const startVisible = visibleAt(0), endVisible = visibleAt(1);
|
|
511
|
+
// Wholly usable edge: its projection is a straight 2D segment, so its screen distance to the pointer
|
|
512
|
+
// is exact and cheap — beyond the reach there is nothing to find on it.
|
|
513
|
+
if (startVisible && endVisible && Number.isFinite(reachPx)) {
|
|
514
|
+
const pa = project(a), pb = project(b);
|
|
515
|
+
if (projectPointOnSegment2d([client.x, client.y], [pa.x, pa.y], [pb.x, pb.y], SEG_DEGENERACY.atMost(1e-12)).distance > reachPx) return null;
|
|
516
|
+
}
|
|
517
|
+
let low = 0, high = 1;
|
|
518
|
+
if (!startVisible && !endVisible) {
|
|
519
|
+
// Both ends out of view (behind the camera, beyond the far plane): the part near the surface
|
|
520
|
+
// under the pointer can still be in view. Grow the visible run outwards from there.
|
|
521
|
+
const inside = finitePoint(seed) ? projectPointOnSegment3d(seed, a, b, SEG_DEGENERACY.atMost(0)).t : 0.5;
|
|
522
|
+
if (!visibleAt(inside)) return null;
|
|
523
|
+
low = boundary(inside, 0); high = boundary(inside, 1);
|
|
524
|
+
} else if (startVisible !== endVisible) {
|
|
525
|
+
if (startVisible) high = boundary(0, 1); else low = boundary(1, 0);
|
|
130
526
|
}
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
527
|
+
const start = interpolate(a, b, low), end = interpolate(a, b, high);
|
|
528
|
+
const ps = project(start), pe = project(end);
|
|
529
|
+
if (!ps?.visible || !pe?.visible) return null;
|
|
530
|
+
const rule = SEG_DEGENERACY.atMost(1e-12);
|
|
531
|
+
const screenT = projectPointOnSegment2d([client.x, client.y], [ps.x, ps.y], [pe.x, pe.y], rule).t;
|
|
532
|
+
let t = screenT;
|
|
533
|
+
const pm = project(interpolate(start, end, 0.5));
|
|
534
|
+
if (Number.isFinite(pm?.x) && Number.isFinite(pm?.y)) {
|
|
535
|
+
const m = projectPointOnSegment2d([pm.x, pm.y], [ps.x, ps.y], [pe.x, pe.y], rule).t;
|
|
536
|
+
if (m > 1e-9 && m < 1 - 1e-9) { const k = m / (1 - m); t = screenT / (k * (1 - screenT) + screenT); }
|
|
537
|
+
}
|
|
538
|
+
const point = frozenPoint(interpolate(start, end, t)); const screen = project(point);
|
|
539
|
+
return screen?.visible && (!includePoint || includePoint(point)) ? { point, screen } : null;
|
|
134
540
|
}
|
|
135
541
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (
|
|
542
|
+
// The (kind, point, screen) readings of one stored candidate: a vertex is itself; an edge carrier is
|
|
543
|
+
// read as its midpoint and as its nearest point to the pointer. Objects are only built for a winner.
|
|
544
|
+
function candidateReadings(candidate, client, project, enabled, seed, includePoint, reachPx, visit) {
|
|
545
|
+
if (candidate.kind !== EDGE_CARRIER_KIND) {
|
|
546
|
+
if (enabled[candidate.kind] !== false) visit(candidate.kind, candidate.id, candidate.point, project(candidate.point));
|
|
547
|
+
return;
|
|
141
548
|
}
|
|
549
|
+
if (enabled['mesh-edge-midpoint'] !== false) visit('mesh-edge-midpoint', `${candidate.id}:midpoint`, candidate.point, project(candidate.point));
|
|
142
550
|
if (enabled['mesh-edge-nearest'] !== false && candidate.segment) {
|
|
143
|
-
const
|
|
144
|
-
if (
|
|
145
|
-
const t = projectPointOnSegment2d(
|
|
146
|
-
[client.x, client.y], [pa.x, pa.y], [pb.x, pb.y], SEG_DEGENERACY.atMost(1e-12),
|
|
147
|
-
).t;
|
|
148
|
-
const point = frozenPoint(interpolate(a, b, t)); const screen = project(point);
|
|
149
|
-
if (screen?.visible) variants.push({ ...candidate, id: `${candidate.id}:nearest`, kind: 'mesh-edge-nearest', point, screen });
|
|
150
|
-
}
|
|
551
|
+
const nearest = nearestOnProjectedEdge(candidate.segment[0], candidate.segment[1], client, project, seed, includePoint, reachPx);
|
|
552
|
+
if (nearest) visit('mesh-edge-nearest', `${candidate.id}:nearest`, nearest.point, nearest.screen);
|
|
151
553
|
}
|
|
152
|
-
return variants;
|
|
153
554
|
}
|
|
154
555
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
556
|
+
/**
|
|
557
|
+
* Order snap readings best first, independently of the order they were found in. Sorted by screen
|
|
558
|
+
* distance (a total order), then cut into tie groups — each group is every reading within the tie
|
|
559
|
+
* tolerance of the group's NEAREST one — and ordered inside a group by kind rank, then id. A pairwise
|
|
560
|
+
* "within 0.25 px" comparison is not transitive (0, 0.2 and 0.4 px can form a cycle), so it cannot
|
|
561
|
+
* be handed to a sort.
|
|
562
|
+
*/
|
|
563
|
+
export function orderModelSnapReadings(readings) {
|
|
564
|
+
const rank = (reading) => KIND_RANK.get(reading.kind) ?? Number.MAX_SAFE_INTEGER;
|
|
565
|
+
const byDistance = [...readings].sort((a, b) => a.distance - b.distance || rank(a) - rank(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
566
|
+
const ordered = [];
|
|
567
|
+
for (let start = 0; start < byDistance.length;) {
|
|
568
|
+
let end = start + 1;
|
|
569
|
+
while (end < byDistance.length && byDistance[end].distance - byDistance[start].distance <= MODEL_SNAP_TIE_EPSILON_PX) end++;
|
|
570
|
+
ordered.push(...byDistance.slice(start, end).sort((a, b) => rank(a) - rank(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
|
|
571
|
+
start = end;
|
|
572
|
+
}
|
|
573
|
+
return ordered;
|
|
161
574
|
}
|
|
162
575
|
|
|
163
576
|
/**
|
|
164
|
-
* Resolve
|
|
577
|
+
* Resolve the snap nearest the pointer on screen, with deterministic ties. The index is asked for
|
|
578
|
+
* everything in the pointer's sightline region (`modelSnapRegion`); when it cannot check that region
|
|
579
|
+
* completely it answers nothing and says why through `index.pointerRefusal()`, and so does this.
|
|
165
580
|
* @param {any} index
|
|
166
581
|
* @param {{x:number,y:number}} client
|
|
167
582
|
* @param {(point:readonly number[])=>any} project
|
|
168
583
|
* @param {Record<string,boolean>} enabled
|
|
169
584
|
* @param {number} radiusPx
|
|
170
|
-
* @param {readonly number[]|null} worldHint
|
|
585
|
+
* @param {readonly number[]|null} worldHint the surface point under the pointer
|
|
171
586
|
* @param {number} queryCap
|
|
587
|
+
* @param {readonly number[]|null} rayOrigin where the pick ray that found `worldHint` started
|
|
588
|
+
* @param {{element?:(mesh:any,min:ArrayLike<number>,max:ArrayLike<number>)=>boolean, point?:(point:readonly number[])=>boolean,
|
|
589
|
+
* occluded?:(point:readonly number[],origin:readonly number[]|null,meshes:any[])=>boolean}|null} visibility
|
|
590
|
+
* what the viewer currently shows (hidden elements, section boxes) — the same rule as its surface pick —
|
|
591
|
+
* and whether something nearer the eye hides a point
|
|
172
592
|
*/
|
|
173
|
-
export function closestModelSnap(index, client, project, enabled = {}, radiusPx = MODEL_SNAP_ACQUISITION_RADIUS_PX, worldHint = null, queryCap = MODEL_SNAP_QUERY_CAP) {
|
|
174
|
-
if (!index?.available
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
SEG_DEGENERACY.atMost(1e-12),
|
|
192
|
-
).t;
|
|
193
|
-
point = frozenPoint(interpolate(projected.a, projected.b, t)); screen = project(point);
|
|
194
|
-
if (!screen?.visible) continue;
|
|
195
|
-
}
|
|
196
|
-
const distance = Math.hypot(screen.x - client.x, screen.y - client.y);
|
|
197
|
-
const next = { ...candidate, point, screen, distance };
|
|
198
|
-
if (distance <= radiusPx && preferred(next, best)) best = next;
|
|
593
|
+
export function closestModelSnap(index, client, project, enabled = {}, radiusPx = MODEL_SNAP_ACQUISITION_RADIUS_PX, worldHint = null, queryCap = MODEL_SNAP_QUERY_CAP, rayOrigin = null, visibility = null) {
|
|
594
|
+
if (!index?.available) return null;
|
|
595
|
+
// Every exit that checks nothing still asks the index with no region, which answers nothing and
|
|
596
|
+
// clears the previous position's refusal, so a stale reason is never shown for this pointer.
|
|
597
|
+
const nothing = () => { index.query?.(worldHint, queryCap, null); return null; };
|
|
598
|
+
if (!finitePoint(worldHint) || !Number.isFinite(client?.x) || !Number.isFinite(client?.y)) return nothing();
|
|
599
|
+
// With every mesh snap switched off there is nothing to look for, and nothing to refuse.
|
|
600
|
+
if (!['mesh-vertex', 'mesh-edge-midpoint', 'mesh-edge-nearest'].some((kind) => enabled[kind] !== false)) return nothing();
|
|
601
|
+
const region = modelSnapRegion(index, project, worldHint, radiusPx, rayOrigin);
|
|
602
|
+
if (!region) return nothing();
|
|
603
|
+
const includePoint = typeof visibility?.point === 'function' ? visibility.point : null;
|
|
604
|
+
const readings = [];
|
|
605
|
+
for (const candidate of index.query(worldHint, queryCap, { ...region, includeElement: visibility?.element ?? null })) {
|
|
606
|
+
candidateReadings(candidate, client, project, enabled, worldHint, includePoint, radiusPx + 1, (kind, id, point, screen) => {
|
|
607
|
+
if (!screen?.visible || (includePoint && !includePoint(point))) return;
|
|
608
|
+
const distance = Math.hypot(screen.x - client.x, screen.y - client.y);
|
|
609
|
+
if (distance <= radiusPx) readings.push({ kind, id, point, screen, distance, candidate });
|
|
610
|
+
});
|
|
199
611
|
}
|
|
200
|
-
|
|
612
|
+
// Best first, then the first one nothing nearer to the eye hides. The region reaches past the surface
|
|
613
|
+
// under the pointer (grazing surfaces need it), so a hidden feature can be among the readings; any
|
|
614
|
+
// occluder of one lies in the region, so only the region's meshes are asked. The check runs until
|
|
615
|
+
// the first visible reading; if its budget runs out first, this pointer is refused, not answered.
|
|
616
|
+
const ordered = orderModelSnapReadings(readings);
|
|
617
|
+
const occluded = typeof visibility?.occluded === 'function' ? visibility.occluded : null;
|
|
618
|
+
const occluders = occluded ? index.regionMeshes?.() ?? [] : [];
|
|
619
|
+
for (const [tested, reading] of ordered.entries()) {
|
|
620
|
+
if (occluded && tested >= MODEL_SNAP_MAX_OCCLUSION_CHECKS) { index.refusePointer?.('crowded'); return null; }
|
|
621
|
+
if (occluded && occluded(reading.point, rayOrigin, occluders)) continue;
|
|
622
|
+
const { candidate, ...winner } = reading;
|
|
623
|
+
return Object.freeze({ ...candidate, ...winner });
|
|
624
|
+
}
|
|
625
|
+
return null;
|
|
201
626
|
}
|
|
202
627
|
|
|
203
628
|
const add = (a, b) => a.map((value, axis) => value + b[axis]);
|