fast-mesh-wasm 0.1.0 → 0.3.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/README.md +493 -23
- package/dist/api-BUy7FRx7.js +64 -0
- package/dist/client-Bp9FRd70.js +2278 -0
- package/dist/client-m2zSdFlu.d.ts +305 -0
- package/dist/colormap-D_xH5hI5.js +303 -0
- package/dist/core-Cke_kZ2e.js +113 -0
- package/dist/core-D2X9GPfK.d.ts +15 -0
- package/dist/engine-B-ZEzR1c.js +1818 -0
- package/dist/mesh-B16gV3oX.d.ts +130 -0
- package/dist/mesh-B8pae8WA.js +428 -0
- package/dist/node.d.ts +6 -4
- package/dist/node.js +9 -5
- package/dist/protocol-CAUYm1gd.js +68 -0
- package/dist/protocol-W9R-iGl5.d.ts +293 -0
- package/dist/r3f.d.ts +59 -0
- package/dist/r3f.js +165 -0
- package/dist/react-CTADh3NN.js +124 -0
- package/dist/react.d.ts +65 -0
- package/dist/react.js +1 -0
- package/dist/scene-BG3EEyfw.js +1243 -0
- package/dist/scene-like-B_3qm0u6.d.ts +925 -0
- package/dist/snapshot-Cf6NgDl7.js +104 -0
- package/dist/store-D3ErV6o-.js +1379 -0
- package/dist/store-DNnHN33A.d.ts +285 -0
- package/dist/store.d.ts +61 -0
- package/dist/store.js +105 -0
- package/dist/three.d.ts +118 -0
- package/dist/three.js +390 -0
- package/dist/views-BaZqBxlX.js +189 -0
- package/dist/wasm/fast_mesh_wasm.d.ts +450 -31
- package/dist/wasm/fast_mesh_wasm.js +1122 -49
- package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +76 -7
- package/dist/wasm-threads/fast_mesh_wasm.d.ts +540 -0
- package/dist/wasm-threads/fast_mesh_wasm.js +1513 -0
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +93 -0
- package/dist/wasm-threads/package.json +7 -0
- package/dist/wasm-threads/snippets/fast-mesh-wasm-ae14781a92c2789e/inline0.js +16 -0
- package/dist/wasm-threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +107 -0
- package/dist/web.d.ts +3 -2
- package/dist/web.js +6 -3
- package/dist/worker-engine.d.ts +248 -0
- package/dist/worker-engine.js +1 -0
- package/dist/worker-entry.d.ts +1 -0
- package/dist/worker-entry.js +11 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +1 -0
- package/package.json +55 -4
|
@@ -0,0 +1,2278 @@
|
|
|
1
|
+
import { o as reportListenerError, t as FastMeshError } from "./core-Cke_kZ2e.js";
|
|
2
|
+
import { a as FieldHandle, c as rotationMatrix, l as targetsOf, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-BaZqBxlX.js";
|
|
3
|
+
import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-CAUYm1gd.js";
|
|
4
|
+
//#region src/worker/client.ts
|
|
5
|
+
/**
|
|
6
|
+
* Starts a Worker running the scene engine and resolves once it is ready.
|
|
7
|
+
* Rejects with `INSTANCE_POISONED` when the Worker could not load fast-mesh.
|
|
8
|
+
*/
|
|
9
|
+
async function createWorkerScene(options = {}) {
|
|
10
|
+
if (options.threads !== void 0 && !Number.isInteger(options.threads)) throw invalid(`threads must be an integer (got ${options.threads})`);
|
|
11
|
+
const threads = options.threads === void 0 ? void 0 : Math.min(Math.max(options.threads, 1), 64);
|
|
12
|
+
const background = options.backgroundAddTriangles;
|
|
13
|
+
if (background !== void 0 && (typeof background !== "number" || Number.isNaN(background) || background < 0)) throw invalid(`backgroundAddTriangles must be a number, 0 or more (got ${String(background)})`);
|
|
14
|
+
const make = () => options.createWorker?.() ?? (options.workerUrl === void 0 ? new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" }) : new Worker(options.workerUrl, { type: "module" }));
|
|
15
|
+
const dev = import.meta.env?.DEV === true;
|
|
16
|
+
const debug = (options.debug ?? false) || dev;
|
|
17
|
+
const skipped = threadsUnavailable && threads !== 1;
|
|
18
|
+
const [scene, started] = createScene(make, {
|
|
19
|
+
debug: options.debug ?? false,
|
|
20
|
+
init: {
|
|
21
|
+
kind: "init",
|
|
22
|
+
threads: skipped ? 1 : threads,
|
|
23
|
+
debug,
|
|
24
|
+
...background === void 0 ? {} : { backgroundAddTriangles: background }
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
await started;
|
|
29
|
+
} catch (e) {
|
|
30
|
+
scene.terminate();
|
|
31
|
+
throw e;
|
|
32
|
+
}
|
|
33
|
+
if (skipped && debug) console.warn(THREADS_UNAVAILABLE);
|
|
34
|
+
return scene;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Set by `WorkerScene`'s static block: makes a scene (the constructor is
|
|
38
|
+
* private) and returns it with its first Worker's start.
|
|
39
|
+
*/
|
|
40
|
+
let createScene;
|
|
41
|
+
/** Elements per slot of each buffer. */
|
|
42
|
+
const STRIDE = {
|
|
43
|
+
positions: 3,
|
|
44
|
+
normals: 3,
|
|
45
|
+
colors: 4,
|
|
46
|
+
values: 1,
|
|
47
|
+
indices: 3
|
|
48
|
+
};
|
|
49
|
+
const BUFFERS = Object.keys(STRIDE);
|
|
50
|
+
const MAKE = {
|
|
51
|
+
positions: (b) => new Float32Array(b),
|
|
52
|
+
normals: (b) => new Float32Array(b),
|
|
53
|
+
colors: (b) => new Uint8Array(b),
|
|
54
|
+
values: (b) => new Float32Array(b),
|
|
55
|
+
indices: (b) => new Uint32Array(b)
|
|
56
|
+
};
|
|
57
|
+
const IDENTITY = [
|
|
58
|
+
1,
|
|
59
|
+
0,
|
|
60
|
+
0,
|
|
61
|
+
0,
|
|
62
|
+
1,
|
|
63
|
+
0,
|
|
64
|
+
0,
|
|
65
|
+
0,
|
|
66
|
+
1
|
|
67
|
+
];
|
|
68
|
+
/** The buffers a batch transfers: those of its mesh adds. */
|
|
69
|
+
function transferOf(batch) {
|
|
70
|
+
const transfer = [];
|
|
71
|
+
for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
|
|
72
|
+
return transfer;
|
|
73
|
+
}
|
|
74
|
+
/** The most failed requests kept for `restart()`. */
|
|
75
|
+
const FAILED_LOG_LIMIT = 1e4;
|
|
76
|
+
/** `placement · translate(origin)`, column-major, as `Scene.matrix4`. */
|
|
77
|
+
function poseOf(rotation, translation, origin) {
|
|
78
|
+
const r = rotation;
|
|
79
|
+
const o = origin;
|
|
80
|
+
const m = /* @__PURE__ */ new Float64Array(16);
|
|
81
|
+
for (let row = 0; row < 3; row++) {
|
|
82
|
+
for (let col = 0; col < 3; col++) m[4 * col + row] = r[3 * row + col];
|
|
83
|
+
m[12 + row] = r[3 * row] * o[0] + r[3 * row + 1] * o[1] + r[3 * row + 2] * o[2] + translation[row];
|
|
84
|
+
}
|
|
85
|
+
m[15] = 1;
|
|
86
|
+
return {
|
|
87
|
+
rotation,
|
|
88
|
+
translation,
|
|
89
|
+
matrix4: m
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function samePose(a, b) {
|
|
93
|
+
return a.matrix4.every((v, k) => v === b.matrix4[k]) && a.translation.every((v, k) => v === b.translation[k]);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The engine's default origin, the bounding-box centre, or `undefined` when
|
|
97
|
+
* the positions are malformed (the engine then reports the error).
|
|
98
|
+
*/
|
|
99
|
+
function boxCentre(p) {
|
|
100
|
+
if (p.length % 3 !== 0) return;
|
|
101
|
+
const min = [
|
|
102
|
+
Infinity,
|
|
103
|
+
Infinity,
|
|
104
|
+
Infinity
|
|
105
|
+
];
|
|
106
|
+
const max = [
|
|
107
|
+
-Infinity,
|
|
108
|
+
-Infinity,
|
|
109
|
+
-Infinity
|
|
110
|
+
];
|
|
111
|
+
for (let k = 0; k < p.length; k++) {
|
|
112
|
+
const v = p[k];
|
|
113
|
+
if (!Number.isFinite(v)) return;
|
|
114
|
+
const axis = k % 3;
|
|
115
|
+
min[axis] = Math.min(min[axis], v);
|
|
116
|
+
max[axis] = Math.max(max[axis], v);
|
|
117
|
+
}
|
|
118
|
+
if (p.length === 0) return [
|
|
119
|
+
0,
|
|
120
|
+
0,
|
|
121
|
+
0
|
|
122
|
+
];
|
|
123
|
+
return [
|
|
124
|
+
(min[0] + max[0]) * .5,
|
|
125
|
+
(min[1] + max[1]) * .5,
|
|
126
|
+
(min[2] + max[2]) * .5
|
|
127
|
+
];
|
|
128
|
+
}
|
|
129
|
+
/** Ascending, merged union of two range lists; `"all"` wins. */
|
|
130
|
+
function mergeRanges(a, b) {
|
|
131
|
+
if (a === "all" || b === "all") return "all";
|
|
132
|
+
if (a.length === 0) return b;
|
|
133
|
+
if (b.length === 0) return a;
|
|
134
|
+
const sorted = [...a, ...b].sort((x, y) => x[0] - y[0]);
|
|
135
|
+
const out = [];
|
|
136
|
+
for (const [start, count] of sorted) {
|
|
137
|
+
const last = out[out.length - 1];
|
|
138
|
+
if (last !== void 0 && start <= last[0] + last[1]) last[1] = Math.max(last[1], start + count - last[0]);
|
|
139
|
+
else out.push([start, count]);
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
function union(a, b) {
|
|
144
|
+
return b.every((x) => a.includes(x)) ? a : [...a, ...b.filter((x) => !a.includes(x))];
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Drops each last-wins request that a later queued request with the same key
|
|
148
|
+
* supersedes, as the engine does: never edits, adds, removals or history.
|
|
149
|
+
*/
|
|
150
|
+
function coalesce(queue) {
|
|
151
|
+
return queue.filter((req, k) => {
|
|
152
|
+
if (!isLastWins(req)) return true;
|
|
153
|
+
const key = keyOf(req);
|
|
154
|
+
for (let j = k + 1; j < queue.length; j++) if (keyOf(queue[j]) === key) return !supersedes(queue[j], req);
|
|
155
|
+
return true;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function invalid(message) {
|
|
159
|
+
return new FastMeshError("INVALID_ARGUMENT", message);
|
|
160
|
+
}
|
|
161
|
+
function fromWire(e) {
|
|
162
|
+
return new FastMeshError(e.code, e.message);
|
|
163
|
+
}
|
|
164
|
+
function sortOf(req) {
|
|
165
|
+
const base = {
|
|
166
|
+
key: keyOf(req),
|
|
167
|
+
rev: req.rev,
|
|
168
|
+
covers: []
|
|
169
|
+
};
|
|
170
|
+
if (req.kind === "addMesh") return {
|
|
171
|
+
...base,
|
|
172
|
+
kind: "add"
|
|
173
|
+
};
|
|
174
|
+
if (req.kind === "removeMesh" || (req.kind === "field" || req.kind === "section") && req.op === "remove") return {
|
|
175
|
+
...base,
|
|
176
|
+
kind: "removal"
|
|
177
|
+
};
|
|
178
|
+
if (req.kind === "setPlacement" || req.kind === "drag" || req.kind === "coloring" || req.kind === "field" || req.kind === "section") return {
|
|
179
|
+
...base,
|
|
180
|
+
kind: "declarative",
|
|
181
|
+
covers: coversOf(req)
|
|
182
|
+
};
|
|
183
|
+
return {
|
|
184
|
+
...base,
|
|
185
|
+
kind: "lost"
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The keys a declarative request's outcome depends on after a restart: the
|
|
190
|
+
* mesh or section the replay re-creates for it.
|
|
191
|
+
*/
|
|
192
|
+
function coversOf(req) {
|
|
193
|
+
switch (req.kind) {
|
|
194
|
+
case "setPlacement":
|
|
195
|
+
case "drag":
|
|
196
|
+
case "coloring": return [`mesh:${req.id}`];
|
|
197
|
+
case "section": return [`section:${req.section}`];
|
|
198
|
+
case "field": return req.desc === void 0 ? [] : [`mesh:${req.desc.on}`, ...req.desc.to.map((m) => `mesh:${m}`)];
|
|
199
|
+
default: return [];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/** A stand-in for a retired Worker: nothing sent to it goes anywhere. */
|
|
203
|
+
const INERT = {
|
|
204
|
+
postMessage() {},
|
|
205
|
+
addEventListener() {},
|
|
206
|
+
terminate() {}
|
|
207
|
+
};
|
|
208
|
+
/** Crash channels made so far (part of each name, which must be unique). */
|
|
209
|
+
let crashChannels = 0;
|
|
210
|
+
/**
|
|
211
|
+
* Set once a Worker reported that this browser cannot run the threaded
|
|
212
|
+
* engine (`probeFailed`): the page's later scenes start at one thread, so
|
|
213
|
+
* the probe never runs again.
|
|
214
|
+
*/
|
|
215
|
+
let threadsUnavailable = false;
|
|
216
|
+
/** The development warning of a scene started at one thread because of {@link threadsUnavailable}. */
|
|
217
|
+
const THREADS_UNAVAILABLE = "fast-mesh-wasm: the multithreaded engine cannot run in this browser (found by an earlier Worker scene on this page); running single-threaded. See \"Multithreading (COOP/COEP)\" in the fast-mesh-wasm README.";
|
|
218
|
+
/** Set by `WorkerScene`'s static block: the internal {@link addFieldKeyed}. */
|
|
219
|
+
let addFieldKeyedOf;
|
|
220
|
+
/** Set by `WorkerScene`'s static block: the internal {@link watchStatusKeys}. */
|
|
221
|
+
let watchStatusKeysOf;
|
|
222
|
+
/**
|
|
223
|
+
* A scene whose engine runs in a Worker, from {@link createWorkerScene}. It
|
|
224
|
+
* mirrors `Scene` (always `"eager"`) with these differences:
|
|
225
|
+
*
|
|
226
|
+
* - Handles are returned synchronously; the Worker catches up in order.
|
|
227
|
+
* - State changes return `void` and are tracked by key through
|
|
228
|
+
* {@link WorkerScene.status}; calls that return data return promises.
|
|
229
|
+
* - Requests are sent once per frame by {@link WorkerScene.commitFrame},
|
|
230
|
+
* in call order, and "last wins" changes (colouring, section
|
|
231
|
+
* plane/meshes/fill, drag moves) superseded within the batch are dropped.
|
|
232
|
+
* Calls returning a promise wait for the next `commitFrame()` too, or are
|
|
233
|
+
* sent on their own after 100 ms when no frame comes;
|
|
234
|
+
* before the first `commitFrame()` (no frame loop) they are sent on the
|
|
235
|
+
* next microtask.
|
|
236
|
+
* - `views`, `placement`, `matrix4`, `section` and `sectionPlane` read
|
|
237
|
+
* main-thread mirrors, updated as results arrive and reported by the next
|
|
238
|
+
* `commitFrame()`. Views follow the same fresh-view rule as `Scene`: get
|
|
239
|
+
* them right before use. A mesh has 0 slots until its add is processed.
|
|
240
|
+
* - Drags are optimistic: `move` shows the pose at once, `end` and `cancel`
|
|
241
|
+
* are synchronous here, and the pose is held until the Worker has the drag.
|
|
242
|
+
* - {@link WorkerScene.restart} replaces the Worker and replays the scene
|
|
243
|
+
* into it (the way back from `INSTANCE_POISONED`); handles keep working.
|
|
244
|
+
* Unlike other promise calls, its replay is sent at once, not with the
|
|
245
|
+
* next `commitFrame()`.
|
|
246
|
+
*/
|
|
247
|
+
var WorkerScene = class WorkerScene {
|
|
248
|
+
/** Creates a Worker: the first, and one per `restart()`. */
|
|
249
|
+
#make;
|
|
250
|
+
/** The current Worker; only its messages are heard. */
|
|
251
|
+
#worker;
|
|
252
|
+
#guard;
|
|
253
|
+
#rev = 0;
|
|
254
|
+
#qid = 0;
|
|
255
|
+
#nextMesh = 0;
|
|
256
|
+
#nextField = 0;
|
|
257
|
+
#nextSection = 0;
|
|
258
|
+
#meshes = /* @__PURE__ */ new Map();
|
|
259
|
+
#byMesh = /* @__PURE__ */ new Map();
|
|
260
|
+
/** Handles of removed meshes whose state was pruned: they give `UNKNOWN_MESH`. */
|
|
261
|
+
#tombstones = /* @__PURE__ */ new WeakSet();
|
|
262
|
+
/** Handles of removed fields and sections whose state was pruned. */
|
|
263
|
+
#fieldTombstones = /* @__PURE__ */ new WeakSet();
|
|
264
|
+
#sectionTombstones = /* @__PURE__ */ new WeakSet();
|
|
265
|
+
/**
|
|
266
|
+
* Removed fields and sections to forget once the result of their removal
|
|
267
|
+
* (revision `rev`) is applied, or at a restart.
|
|
268
|
+
*/
|
|
269
|
+
#prunes = [];
|
|
270
|
+
#fields = /* @__PURE__ */ new Map();
|
|
271
|
+
#byField = /* @__PURE__ */ new Map();
|
|
272
|
+
#sections = /* @__PURE__ */ new Map();
|
|
273
|
+
#bySection = /* @__PURE__ */ new Map();
|
|
274
|
+
/** This frame's requests, not sent yet. */
|
|
275
|
+
#queue = [];
|
|
276
|
+
#flushScheduled = false;
|
|
277
|
+
/** `commitFrame()` has been called: promise calls wait for the next frame. */
|
|
278
|
+
#frameLoop = false;
|
|
279
|
+
/** Sends queued promise calls when no frame comes. */
|
|
280
|
+
#fallback;
|
|
281
|
+
/** Sent batches awaiting their result (the engine posts one per batch, in order). */
|
|
282
|
+
#inflight = [];
|
|
283
|
+
/**
|
|
284
|
+
* Requests that did not apply because the engine is poisoned (from a
|
|
285
|
+
* poisoned result, a Worker error, or failed here without being sent),
|
|
286
|
+
* until `restart()`, which clears it. They have surfaced already (statuses
|
|
287
|
+
* and rejected promises). Only never-sent `addMesh` requests are replayable
|
|
288
|
+
* as they are: a sent one had its buffers transferred (they are detached
|
|
289
|
+
* here). `restart()` finds those through each mesh's `add`, and rebuilds
|
|
290
|
+
* acknowledged meshes from the mirrors instead. Capped at
|
|
291
|
+
* {@link FAILED_LOG_LIMIT} entries, oldest dropped (`#failedDropped`
|
|
292
|
+
* counts them).
|
|
293
|
+
*/
|
|
294
|
+
#failed = [];
|
|
295
|
+
#failedDropped = 0;
|
|
296
|
+
/**
|
|
297
|
+
* The keys of removals and declarative requests dropped from `#failed`
|
|
298
|
+
* (latest per key), so a restart still settles them.
|
|
299
|
+
*/
|
|
300
|
+
#failedKeys = /* @__PURE__ */ new Map();
|
|
301
|
+
/** Keys a failed replay left in error, for the next restart to settle. */
|
|
302
|
+
#unsettled = /* @__PURE__ */ new Map();
|
|
303
|
+
/** The poses a failed replay had, for its retry. */
|
|
304
|
+
#retryPoses;
|
|
305
|
+
#replies = /* @__PURE__ */ new Map();
|
|
306
|
+
/** Change records of results received since the last `commitFrame`, merged per mesh. */
|
|
307
|
+
#changes = /* @__PURE__ */ new Map();
|
|
308
|
+
/** Meshes whose shown pose changed here (drags), for the next `commitFrame`. */
|
|
309
|
+
#optimistic = /* @__PURE__ */ new Set();
|
|
310
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
311
|
+
#statusListeners = /* @__PURE__ */ new Set();
|
|
312
|
+
#status = /* @__PURE__ */ new Map();
|
|
313
|
+
/** Called with each key whose status is set or forgotten, at once (see {@link watchStatusKeys}). */
|
|
314
|
+
#statusSinks = /* @__PURE__ */ new Set();
|
|
315
|
+
/** The latest revision requested per key. */
|
|
316
|
+
#latest = /* @__PURE__ */ new Map();
|
|
317
|
+
#statusScheduled = false;
|
|
318
|
+
#history = {
|
|
319
|
+
canUndo: false,
|
|
320
|
+
canRedo: false
|
|
321
|
+
};
|
|
322
|
+
/** The values mirror is on (a `values()` read asked for it). */
|
|
323
|
+
#values = false;
|
|
324
|
+
#drag;
|
|
325
|
+
#poison;
|
|
326
|
+
#terminated = false;
|
|
327
|
+
/** The current Worker's start. */
|
|
328
|
+
#ready;
|
|
329
|
+
/** Batches whose result settles a promise: a restart's replay. */
|
|
330
|
+
#batchDone = /* @__PURE__ */ new Map();
|
|
331
|
+
/** The restart under way, until its replay's result is applied. */
|
|
332
|
+
#restarting;
|
|
333
|
+
/**
|
|
334
|
+
* The message starting each Worker's engine. Its `threads` becomes 1 once a
|
|
335
|
+
* Worker's thread pool failed to start, or its probe found that this
|
|
336
|
+
* browser cannot run threads: later Workers (restarts) never try again.
|
|
337
|
+
*/
|
|
338
|
+
#init;
|
|
339
|
+
/** The current Worker's thread count, from its ready message (1 until then). */
|
|
340
|
+
#threads = 1;
|
|
341
|
+
/**
|
|
342
|
+
* A Worker whose thread pool failed to start, while it still gives back
|
|
343
|
+
* batches sent to it (`remaining` more): batches sent meanwhile are held
|
|
344
|
+
* (`held`, cloned with their buffers) and go to the current Worker after
|
|
345
|
+
* those, keeping the order.
|
|
346
|
+
*/
|
|
347
|
+
#handoff;
|
|
348
|
+
/** Whether the start-up warning was logged (once per scene). */
|
|
349
|
+
#warned = false;
|
|
350
|
+
/** The current Worker's crash channel (see `#watch`), while it may run threaded. */
|
|
351
|
+
#crashWatch;
|
|
352
|
+
/** Use {@link createWorkerScene}. */
|
|
353
|
+
constructor(make, options) {
|
|
354
|
+
this.#make = make;
|
|
355
|
+
this.#guard = options.debug ? new ViewGuard() : void 0;
|
|
356
|
+
this.#init = options.init;
|
|
357
|
+
this.#worker = this.#attach(make());
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Listens to a new Worker and sends it the init message. Only the current
|
|
361
|
+
* Worker is heard, and a handed-off one (its batches given back; its
|
|
362
|
+
* errors poison the scene): a replaced one's late messages and errors are
|
|
363
|
+
* ignored. `keepReady` keeps the start
|
|
364
|
+
* under way (a Worker replacing one whose thread pool failed).
|
|
365
|
+
*/
|
|
366
|
+
#attach(worker, keepReady = false) {
|
|
367
|
+
this.#threads = 1;
|
|
368
|
+
if (!keepReady) {
|
|
369
|
+
let ready;
|
|
370
|
+
const promise = new Promise((resolve, reject) => {
|
|
371
|
+
ready = {
|
|
372
|
+
resolve,
|
|
373
|
+
reject
|
|
374
|
+
};
|
|
375
|
+
});
|
|
376
|
+
promise.catch(() => {});
|
|
377
|
+
this.#ready = {
|
|
378
|
+
...ready,
|
|
379
|
+
promise,
|
|
380
|
+
settled: false
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
worker.addEventListener("message", (e) => {
|
|
384
|
+
const msg = e.data;
|
|
385
|
+
if ("kind" in msg && msg.kind === "fallback") this.#onFallback(worker, msg);
|
|
386
|
+
else if (worker === this.#worker) this.#receive(msg);
|
|
387
|
+
});
|
|
388
|
+
worker.addEventListener("error", (e) => {
|
|
389
|
+
if (worker !== this.#worker && worker !== this.#handoff?.old) return;
|
|
390
|
+
this.#detach();
|
|
391
|
+
this.#poisonAll({
|
|
392
|
+
code: "INSTANCE_POISONED",
|
|
393
|
+
message: `the Worker failed${e?.message ? ` (${e.message})` : ""}; the Worker scene can no longer be used`
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
worker.addEventListener("messageerror", () => {
|
|
397
|
+
if (worker !== this.#worker && worker !== this.#handoff?.old) return;
|
|
398
|
+
this.#detach();
|
|
399
|
+
this.#poisonAll({
|
|
400
|
+
code: "INSTANCE_POISONED",
|
|
401
|
+
message: "a message from the Worker could not be read; the Worker scene can no longer be used"
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
this.#unwatch();
|
|
405
|
+
try {
|
|
406
|
+
worker.postMessage(this.#watch(worker));
|
|
407
|
+
} catch (e) {
|
|
408
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
409
|
+
this.#ready.settled = true;
|
|
410
|
+
this.#ready.reject(new FastMeshError("INSTANCE_POISONED", `the Worker could not be started (${cause})`));
|
|
411
|
+
}
|
|
412
|
+
return worker;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* The init message for `worker`, naming a crash channel when its engine
|
|
416
|
+
* may run threaded (more than one thread asked for, on a cross-origin
|
|
417
|
+
* isolated page). A panic or trap on a pool thread kills only that nested
|
|
418
|
+
* Worker; the engine Worker stays blocked waiting for it and never
|
|
419
|
+
* answers. So the pool's threads report the crash on this channel, and it
|
|
420
|
+
* poisons the scene as a Worker error does. Nothing is listened to on
|
|
421
|
+
* other pages (single-threaded engines report their own traps).
|
|
422
|
+
*/
|
|
423
|
+
#watch(worker) {
|
|
424
|
+
const isolated = globalThis.crossOriginIsolated === true;
|
|
425
|
+
if (this.#init.threads === 1 || !isolated || typeof BroadcastChannel !== "function") return this.#init;
|
|
426
|
+
const name = `fast-mesh-wasm:pool-crash:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:${++crashChannels}`;
|
|
427
|
+
const channel = new BroadcastChannel(name);
|
|
428
|
+
channel.onmessage = (e) => {
|
|
429
|
+
const msg = e.data;
|
|
430
|
+
if (msg?.kind !== "poolCrash" || worker !== this.#worker) return;
|
|
431
|
+
this.#detach();
|
|
432
|
+
this.#poisonAll({
|
|
433
|
+
code: "INSTANCE_POISONED",
|
|
434
|
+
message: `a thread of the Worker's pool crashed (${String(msg.detail)}); the Worker scene can no longer be used`
|
|
435
|
+
});
|
|
436
|
+
};
|
|
437
|
+
this.#crashWatch = channel;
|
|
438
|
+
return {
|
|
439
|
+
...this.#init,
|
|
440
|
+
crashChannel: name
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
/** Stops listening to the current Worker's crash channel. */
|
|
444
|
+
#unwatch() {
|
|
445
|
+
this.#crashWatch?.close();
|
|
446
|
+
this.#crashWatch = void 0;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Stops hearing the current Worker and terminates it: after an error its
|
|
450
|
+
* late results (for batches already failed here) must not apply.
|
|
451
|
+
*/
|
|
452
|
+
#detach() {
|
|
453
|
+
const old = this.#worker;
|
|
454
|
+
this.#worker = INERT;
|
|
455
|
+
old.terminate();
|
|
456
|
+
this.#unwatch();
|
|
457
|
+
this.#dropHandoff();
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* A Worker's thread pool failed to start: it leaves a threaded instance
|
|
461
|
+
* and nested Workers behind, so it is terminated and replaced by a
|
|
462
|
+
* single-threaded Worker (this scene's later ones too), which gets the
|
|
463
|
+
* batches it gives back, in order. The scene's start (or restart) goes on
|
|
464
|
+
* with the new Worker.
|
|
465
|
+
*/
|
|
466
|
+
#onFallback(worker, msg) {
|
|
467
|
+
if (this.#terminated) return;
|
|
468
|
+
if (worker === this.#worker) {
|
|
469
|
+
if (msg.warning !== void 0 && !this.#warned) {
|
|
470
|
+
this.#warned = true;
|
|
471
|
+
console.warn(msg.warning);
|
|
472
|
+
}
|
|
473
|
+
this.#init = {
|
|
474
|
+
...this.#init,
|
|
475
|
+
threads: 1
|
|
476
|
+
};
|
|
477
|
+
let next;
|
|
478
|
+
try {
|
|
479
|
+
next = this.#make();
|
|
480
|
+
} catch (e) {
|
|
481
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
482
|
+
this.#detach();
|
|
483
|
+
this.#poisonAll({
|
|
484
|
+
code: "INSTANCE_POISONED",
|
|
485
|
+
message: `a new Worker could not be created (${cause})`
|
|
486
|
+
});
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
this.#handoff = {
|
|
490
|
+
old: worker,
|
|
491
|
+
remaining: this.#inflight.length,
|
|
492
|
+
held: []
|
|
493
|
+
};
|
|
494
|
+
this.#worker = this.#attach(next, true);
|
|
495
|
+
} else if (worker !== this.#handoff?.old) return;
|
|
496
|
+
const handoff = this.#handoff;
|
|
497
|
+
handoff.remaining -= msg.batches.length;
|
|
498
|
+
for (const batch of msg.batches) this.#post(batch, transferOf(batch));
|
|
499
|
+
if (handoff.remaining <= 0 && this.#handoff === handoff) {
|
|
500
|
+
this.#handoff = void 0;
|
|
501
|
+
handoff.old.terminate();
|
|
502
|
+
for (const { batch, transfer } of handoff.held) this.#post(batch, transfer);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/** Posts a batch already counted in flight; one that cannot go poisons the scene. */
|
|
506
|
+
#post(batch, transfer) {
|
|
507
|
+
try {
|
|
508
|
+
this.#worker.postMessage(batch, transfer);
|
|
509
|
+
} catch (e) {
|
|
510
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
511
|
+
this.#detach();
|
|
512
|
+
this.#poisonAll({
|
|
513
|
+
code: "INSTANCE_POISONED",
|
|
514
|
+
message: `requests could not be passed to the single-threaded Worker (${cause})`
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/** Ends a handoff (restart, error, termination): the old Worker goes. */
|
|
519
|
+
#dropHandoff() {
|
|
520
|
+
this.#handoff?.old.terminate();
|
|
521
|
+
this.#handoff = void 0;
|
|
522
|
+
}
|
|
523
|
+
#alive() {
|
|
524
|
+
if (this.#terminated) throw invalid("the Worker scene is terminated");
|
|
525
|
+
}
|
|
526
|
+
/** Queues a request; a keyed one puts its key into "computing". Returns its revision. */
|
|
527
|
+
#push(req) {
|
|
528
|
+
this.#queue.push(req);
|
|
529
|
+
const key = keyOf(req);
|
|
530
|
+
if (key !== void 0) {
|
|
531
|
+
this.#latest.set(key, req.rev);
|
|
532
|
+
this.#setStatus(key, {
|
|
533
|
+
status: "computing",
|
|
534
|
+
revision: req.rev
|
|
535
|
+
});
|
|
536
|
+
this.#statusChanged();
|
|
537
|
+
}
|
|
538
|
+
return req.rev;
|
|
539
|
+
}
|
|
540
|
+
/** Queues a request with a reply and sends soon; resolves with `map(value)`. */
|
|
541
|
+
#ask(make, map) {
|
|
542
|
+
return new Promise((resolve, reject) => {
|
|
543
|
+
this.#alive();
|
|
544
|
+
const qid = ++this.#qid;
|
|
545
|
+
const req = make(++this.#rev, qid);
|
|
546
|
+
this.#replies.set(qid, {
|
|
547
|
+
resolve: (v) => {
|
|
548
|
+
try {
|
|
549
|
+
resolve(map(v));
|
|
550
|
+
} catch (e) {
|
|
551
|
+
reject(e);
|
|
552
|
+
}
|
|
553
|
+
},
|
|
554
|
+
reject
|
|
555
|
+
});
|
|
556
|
+
this.#push(req);
|
|
557
|
+
this.#scheduleFlush();
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Makes sure a queued promise call gets sent: with a frame loop, by the
|
|
562
|
+
* next `commitFrame()` or else the fallback timer, so pointer-rate queries
|
|
563
|
+
* never send the frame's moves early; without one, on a microtask.
|
|
564
|
+
*/
|
|
565
|
+
#scheduleFlush() {
|
|
566
|
+
if (this.#frameLoop) {
|
|
567
|
+
this.#fallback ??= setTimeout(() => {
|
|
568
|
+
this.#fallback = void 0;
|
|
569
|
+
this.#flush();
|
|
570
|
+
}, 100);
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (!this.#flushScheduled) {
|
|
574
|
+
this.#flushScheduled = true;
|
|
575
|
+
queueMicrotask(() => {
|
|
576
|
+
this.#flushScheduled = false;
|
|
577
|
+
this.#flush();
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
/** A query by name, with its reply mapped. */
|
|
582
|
+
#query(name, args, map) {
|
|
583
|
+
return this.#ask((rev, qid) => ({
|
|
584
|
+
kind: "query",
|
|
585
|
+
rev,
|
|
586
|
+
qid,
|
|
587
|
+
name,
|
|
588
|
+
args: args()
|
|
589
|
+
}), (v) => map(v));
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Sends the queued requests as one batch, coalesced; returns it when it
|
|
593
|
+
* went to the Worker. A batch that cannot be posted (`postMessage` threw,
|
|
594
|
+
* say a `DataCloneError`) never reached the Worker: it fails here with
|
|
595
|
+
* `INVALID_ARGUMENT`, and nothing else changes.
|
|
596
|
+
*/
|
|
597
|
+
#flush() {
|
|
598
|
+
if (this.#queue.length === 0 || this.#terminated) return;
|
|
599
|
+
const batch = coalesce(this.#queue);
|
|
600
|
+
this.#queue = [];
|
|
601
|
+
if (this.#poison !== void 0) {
|
|
602
|
+
this.#fail(batch, this.#poison);
|
|
603
|
+
this.#statusChanged();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const transfer = [];
|
|
607
|
+
for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
|
|
608
|
+
try {
|
|
609
|
+
if (this.#handoff !== void 0) {
|
|
610
|
+
const held = structuredClone(batch, { transfer });
|
|
611
|
+
this.#handoff.held.push({
|
|
612
|
+
batch: held,
|
|
613
|
+
transfer: transferOf(held)
|
|
614
|
+
});
|
|
615
|
+
} else this.#worker.postMessage(batch, transfer);
|
|
616
|
+
} catch (e) {
|
|
617
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
618
|
+
this.#fail(batch, invalid(`the requests could not be sent to the Worker (${cause})`), false);
|
|
619
|
+
this.#statusChanged();
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
for (const req of batch) if (req.kind === "addMesh") {
|
|
623
|
+
const st = this.#meshes.get(req.id);
|
|
624
|
+
if (st?.add === req) st.sent = true;
|
|
625
|
+
}
|
|
626
|
+
this.#inflight.push(batch);
|
|
627
|
+
return batch;
|
|
628
|
+
}
|
|
629
|
+
/** Marks requests failed with `error`: their statuses and promises (logged for `restart()` when `log`). */
|
|
630
|
+
#fail(batch, error, log = true) {
|
|
631
|
+
for (const req of batch) {
|
|
632
|
+
if (log) this.#logFailed(req);
|
|
633
|
+
const key = keyOf(req);
|
|
634
|
+
if (key !== void 0 && this.#latest.get(key) === req.rev) this.#setStatus(key, {
|
|
635
|
+
status: "error",
|
|
636
|
+
revision: req.rev,
|
|
637
|
+
error
|
|
638
|
+
});
|
|
639
|
+
const qid = req.qid;
|
|
640
|
+
if (qid !== void 0) {
|
|
641
|
+
this.#replies.get(qid)?.reject(error);
|
|
642
|
+
this.#replies.delete(qid);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
#logFailed(req) {
|
|
647
|
+
this.#failed.push(req);
|
|
648
|
+
if (this.#failed.length > FAILED_LOG_LIMIT) {
|
|
649
|
+
const drop = this.#failed.length - FAILED_LOG_LIMIT / 2;
|
|
650
|
+
for (const req of this.#failed.splice(0, drop)) {
|
|
651
|
+
const { key, ...rest } = sortOf(req);
|
|
652
|
+
if (key !== void 0 && (rest.kind === "removal" || rest.kind === "declarative")) this.#failedKeys.set(key, rest);
|
|
653
|
+
}
|
|
654
|
+
this.#failedDropped += drop;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Poisoned: drops the drag hold and pending placements, so the shown poses
|
|
659
|
+
* are the engine's last known ones (a restart begins clean).
|
|
660
|
+
*/
|
|
661
|
+
#releaseHolds() {
|
|
662
|
+
if (this.#drag !== void 0) {
|
|
663
|
+
this.#drag.active = false;
|
|
664
|
+
this.#drag = void 0;
|
|
665
|
+
}
|
|
666
|
+
for (const st of this.#meshes.values()) {
|
|
667
|
+
if (st.local !== void 0 && !samePose(st.local, st.pose)) this.#optimistic.add(st);
|
|
668
|
+
st.local = void 0;
|
|
669
|
+
st.localUntil = 0;
|
|
670
|
+
st.requested = void 0;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/** The engine is gone (a Worker error, or it could not start): fail everything in flight. */
|
|
674
|
+
#poisonAll(error) {
|
|
675
|
+
const e = fromWire(error);
|
|
676
|
+
this.#poison ??= e;
|
|
677
|
+
if (!this.#ready.settled) {
|
|
678
|
+
this.#ready.settled = true;
|
|
679
|
+
this.#ready.reject(e);
|
|
680
|
+
}
|
|
681
|
+
for (const batch of this.#inflight.splice(0)) {
|
|
682
|
+
this.#fail(batch, e);
|
|
683
|
+
this.#batchDone.get(batch)?.reject(e);
|
|
684
|
+
this.#batchDone.delete(batch);
|
|
685
|
+
}
|
|
686
|
+
this.#releaseHolds();
|
|
687
|
+
this.#statusChanged();
|
|
688
|
+
}
|
|
689
|
+
#receive(msg) {
|
|
690
|
+
if (this.#terminated) return;
|
|
691
|
+
if ("kind" in msg) {
|
|
692
|
+
if (msg.kind === "ready") {
|
|
693
|
+
this.#threads = msg.threads ?? 1;
|
|
694
|
+
if (msg.probeFailed === true) {
|
|
695
|
+
this.#init = {
|
|
696
|
+
...this.#init,
|
|
697
|
+
threads: 1
|
|
698
|
+
};
|
|
699
|
+
threadsUnavailable = true;
|
|
700
|
+
}
|
|
701
|
+
if (this.#threads === 1) this.#unwatch();
|
|
702
|
+
if (msg.warning !== void 0 && !this.#warned) {
|
|
703
|
+
this.#warned = true;
|
|
704
|
+
console.warn(msg.warning);
|
|
705
|
+
}
|
|
706
|
+
this.#ready.settled = true;
|
|
707
|
+
this.#ready.resolve();
|
|
708
|
+
} else if (msg.kind === "fatal") this.#poisonAll(msg.error);
|
|
709
|
+
else if (msg.kind === "update") this.#apply(msg.result, []);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const batch = this.#inflight.shift() ?? [];
|
|
713
|
+
this.#apply(msg, batch);
|
|
714
|
+
this.#runPrunes(msg.rev);
|
|
715
|
+
const done = this.#batchDone.get(batch);
|
|
716
|
+
if (done !== void 0) {
|
|
717
|
+
this.#batchDone.delete(batch);
|
|
718
|
+
if (msg.poisoned) done.reject(this.#poison);
|
|
719
|
+
else done.resolve(void 0);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/** Applies one batch's result: mirrors, change records, statuses, replies. */
|
|
723
|
+
#apply(r, batch) {
|
|
724
|
+
if (r.poisoned) {
|
|
725
|
+
const first = r.status[0]?.error ?? r.replies[0]?.error;
|
|
726
|
+
this.#poison ??= fromWire(first ?? {
|
|
727
|
+
code: "INSTANCE_POISONED",
|
|
728
|
+
message: "the Worker engine stopped"
|
|
729
|
+
});
|
|
730
|
+
for (const req of batch) this.#logFailed(req);
|
|
731
|
+
this.#releaseHolds();
|
|
732
|
+
this.#applyStatus(r);
|
|
733
|
+
this.#applyReplies(r);
|
|
734
|
+
for (const req of batch) {
|
|
735
|
+
const qid = req.qid;
|
|
736
|
+
if (qid !== void 0) {
|
|
737
|
+
this.#replies.get(qid)?.reject(this.#poison);
|
|
738
|
+
this.#replies.delete(qid);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
this.#statusChanged();
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
for (const { id, rev } of r.colorings) {
|
|
745
|
+
const st = this.#meshes.get(id);
|
|
746
|
+
if (st === void 0) continue;
|
|
747
|
+
if (st.pendingRules.has(rev)) st.shown = st.pendingRules.get(rev) ?? null;
|
|
748
|
+
for (const k of st.pendingRules.keys()) if (k <= rev) st.pendingRules.delete(k);
|
|
749
|
+
}
|
|
750
|
+
for (const c of r.changes) this.#applyChange(c);
|
|
751
|
+
for (const st of this.#meshes.values()) if (st.colors === null) st.shown = null;
|
|
752
|
+
for (const p of r.placements) {
|
|
753
|
+
const st = this.#meshes.get(p.id);
|
|
754
|
+
if (st !== void 0) st.pose = {
|
|
755
|
+
rotation: p.rotation,
|
|
756
|
+
translation: p.translation,
|
|
757
|
+
matrix4: Float64Array.from(p.matrix4)
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
for (const s of r.sections) {
|
|
761
|
+
const st = this.#sections.get(s.section);
|
|
762
|
+
if (st === void 0) continue;
|
|
763
|
+
if (s.result === null) st.results.delete(s.mesh);
|
|
764
|
+
else st.results.set(s.mesh, s.result);
|
|
765
|
+
}
|
|
766
|
+
for (const st of this.#meshes.values()) {
|
|
767
|
+
if (st.requested !== void 0 && r.rev >= st.requestedUntil) st.requested = void 0;
|
|
768
|
+
if (st.local !== void 0 && r.rev >= st.localUntil) {
|
|
769
|
+
const shown = st.local;
|
|
770
|
+
st.local = void 0;
|
|
771
|
+
if (!samePose(shown, st.pose)) this.#optimistic.add(st);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (r.history.canUndo !== this.#history.canUndo || r.history.canRedo !== this.#history.canRedo) {
|
|
775
|
+
this.#history = { ...r.history };
|
|
776
|
+
this.#statusChanged();
|
|
777
|
+
}
|
|
778
|
+
this.#applyStatus(r);
|
|
779
|
+
this.#applyReplies(r);
|
|
780
|
+
}
|
|
781
|
+
#applyStatus(r) {
|
|
782
|
+
for (const s of r.status) {
|
|
783
|
+
const latest = this.#latest.get(s.key) ?? 0;
|
|
784
|
+
if (s.rev < latest) continue;
|
|
785
|
+
this.#setStatus(s.key, s.status === "ready" ? {
|
|
786
|
+
status: "ready",
|
|
787
|
+
revision: s.rev
|
|
788
|
+
} : {
|
|
789
|
+
status: "error",
|
|
790
|
+
revision: s.rev,
|
|
791
|
+
error: fromWire(s.error)
|
|
792
|
+
});
|
|
793
|
+
this.#statusChanged();
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
#applyReplies(r) {
|
|
797
|
+
for (const reply of r.replies) {
|
|
798
|
+
const p = this.#replies.get(reply.qid);
|
|
799
|
+
if (p === void 0) continue;
|
|
800
|
+
this.#replies.delete(reply.qid);
|
|
801
|
+
if (reply.ok) p.resolve(reply.value);
|
|
802
|
+
else p.reject(fromWire(reply.error));
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
/** Applies a change record's bytes to the mesh's mirrors and merges the record for delivery. */
|
|
806
|
+
#applyChange(c) {
|
|
807
|
+
const st = this.#meshes.get(c.id);
|
|
808
|
+
if (st === void 0) return;
|
|
809
|
+
if (c.removed) {
|
|
810
|
+
st.live = false;
|
|
811
|
+
this.#clearMirrors(st);
|
|
812
|
+
} else {
|
|
813
|
+
if (c.added) {
|
|
814
|
+
st.live = true;
|
|
815
|
+
st.add = void 0;
|
|
816
|
+
}
|
|
817
|
+
for (const name of BUFFERS) this.#applyBuffer(st, name, c);
|
|
818
|
+
}
|
|
819
|
+
const record = {
|
|
820
|
+
mesh: st.handle,
|
|
821
|
+
added: c.added,
|
|
822
|
+
removed: c.removed,
|
|
823
|
+
placementChanged: c.placementChanged,
|
|
824
|
+
capacityChanged: c.capacityChanged,
|
|
825
|
+
positions: c.positions,
|
|
826
|
+
normals: c.normals,
|
|
827
|
+
colors: c.colors,
|
|
828
|
+
indices: c.indices,
|
|
829
|
+
fieldsChanged: c.fields.flatMap((id) => this.#fields.get(id)?.handle ?? []),
|
|
830
|
+
sectionsChanged: c.sections.flatMap((id) => this.#sections.get(id)?.handle ?? [])
|
|
831
|
+
};
|
|
832
|
+
const prev = this.#changes.get(st);
|
|
833
|
+
this.#changes.set(st, prev === void 0 ? record : merge(prev, record));
|
|
834
|
+
}
|
|
835
|
+
#clearMirrors(st) {
|
|
836
|
+
st.positions = /* @__PURE__ */ new Float32Array(0);
|
|
837
|
+
st.indices = /* @__PURE__ */ new Uint32Array(0);
|
|
838
|
+
st.normals = null;
|
|
839
|
+
st.colors = null;
|
|
840
|
+
st.values = null;
|
|
841
|
+
st.shown = null;
|
|
842
|
+
this.#guard?.bump();
|
|
843
|
+
}
|
|
844
|
+
#applyBuffer(st, name, c) {
|
|
845
|
+
const bytes = c.bytes[name];
|
|
846
|
+
const ranges = c[name === "values" ? "colors" : name];
|
|
847
|
+
if (bytes === null) {
|
|
848
|
+
if ((name === "normals" || name === "colors" || name === "values") && st[name] !== null) {
|
|
849
|
+
st[name] = null;
|
|
850
|
+
this.#guard?.bump();
|
|
851
|
+
}
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
const src = MAKE[name](bytes);
|
|
855
|
+
const length = STRIDE[name] * (name === "indices" ? c.triangleSlots : c.vertexSlots);
|
|
856
|
+
let dst = st[name];
|
|
857
|
+
if (ranges === "all" && src.length === length) {
|
|
858
|
+
if (dst !== null && dst.length === length) dst.set(src);
|
|
859
|
+
else {
|
|
860
|
+
st[name] = src;
|
|
861
|
+
this.#guard?.bump();
|
|
862
|
+
}
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
if (dst === null || dst.length !== length) {
|
|
866
|
+
const grown = MAKE[name](length);
|
|
867
|
+
if (dst !== null) grown.set(dst.subarray(0, Math.min(dst.length, length)));
|
|
868
|
+
dst = grown;
|
|
869
|
+
st[name] = grown;
|
|
870
|
+
this.#guard?.bump();
|
|
871
|
+
}
|
|
872
|
+
if (ranges === "all") {
|
|
873
|
+
dst.set(src.subarray(0, Math.min(src.length, length)));
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
const stride = STRIDE[name];
|
|
877
|
+
let at = 0;
|
|
878
|
+
for (const [start, count] of ranges) {
|
|
879
|
+
const n = count * stride;
|
|
880
|
+
dst.set(src.subarray(at, at + n), start * stride);
|
|
881
|
+
at += n;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
/** Sets a key's status and tells the sinks. */
|
|
885
|
+
#setStatus(key, status) {
|
|
886
|
+
this.#status.set(key, status);
|
|
887
|
+
for (const sink of this.#statusSinks) sink(key);
|
|
888
|
+
}
|
|
889
|
+
/** Forgets a key's status and tells the sinks. */
|
|
890
|
+
#deleteStatus(key) {
|
|
891
|
+
if (this.#status.delete(key)) for (const sink of this.#statusSinks) sink(key);
|
|
892
|
+
}
|
|
893
|
+
#statusChanged() {
|
|
894
|
+
if (this.#statusScheduled) return;
|
|
895
|
+
this.#statusScheduled = true;
|
|
896
|
+
queueMicrotask(() => {
|
|
897
|
+
this.#statusScheduled = false;
|
|
898
|
+
let failure;
|
|
899
|
+
for (const listener of [...this.#statusListeners]) try {
|
|
900
|
+
listener();
|
|
901
|
+
} catch (error) {
|
|
902
|
+
failure ??= { error };
|
|
903
|
+
}
|
|
904
|
+
if (failure !== void 0) reportListenerError(failure.error);
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
/** The state of a mesh handle of this scene (removed ones included). */
|
|
908
|
+
#state(mesh) {
|
|
909
|
+
const st = mesh instanceof MeshHandle ? this.#byMesh.get(mesh) : void 0;
|
|
910
|
+
if (st === void 0) {
|
|
911
|
+
if (mesh instanceof MeshHandle && this.#tombstones.has(mesh)) throw new FastMeshError("UNKNOWN_MESH", "the mesh was removed");
|
|
912
|
+
throw invalid("not a mesh handle of this Worker scene");
|
|
913
|
+
}
|
|
914
|
+
return st;
|
|
915
|
+
}
|
|
916
|
+
/** A mesh that may still be changed: not removed. */
|
|
917
|
+
#live(mesh) {
|
|
918
|
+
this.#alive();
|
|
919
|
+
const st = this.#state(mesh);
|
|
920
|
+
if (st.removed) throw new FastMeshError("UNKNOWN_MESH", "the mesh was removed");
|
|
921
|
+
return st;
|
|
922
|
+
}
|
|
923
|
+
/** A mesh whose mirrors may be read: its removal not delivered yet. */
|
|
924
|
+
#mirrored(mesh) {
|
|
925
|
+
const st = this.#state(mesh);
|
|
926
|
+
if (st.gone) throw new FastMeshError("UNKNOWN_MESH", "the mesh was removed");
|
|
927
|
+
return st;
|
|
928
|
+
}
|
|
929
|
+
#field(field) {
|
|
930
|
+
this.#alive();
|
|
931
|
+
const st = field instanceof FieldHandle ? this.#byField.get(field) : void 0;
|
|
932
|
+
if (st === void 0) {
|
|
933
|
+
if (field instanceof FieldHandle && this.#fieldTombstones.has(field)) throw new FastMeshError("UNKNOWN_FIELD", "the field was removed");
|
|
934
|
+
throw invalid("not a field handle of this Worker scene");
|
|
935
|
+
}
|
|
936
|
+
if (st.removed) throw new FastMeshError("UNKNOWN_FIELD", "the field was removed");
|
|
937
|
+
return st;
|
|
938
|
+
}
|
|
939
|
+
#section(section) {
|
|
940
|
+
const st = section instanceof SectionHandle ? this.#bySection.get(section) : void 0;
|
|
941
|
+
if (st === void 0) {
|
|
942
|
+
if (section instanceof SectionHandle && this.#sectionTombstones.has(section)) throw new FastMeshError("UNKNOWN_SECTION", "the section was removed");
|
|
943
|
+
throw invalid("not a section handle of this Worker scene");
|
|
944
|
+
}
|
|
945
|
+
if (st.removed) throw new FastMeshError("UNKNOWN_SECTION", "the section was removed");
|
|
946
|
+
return st;
|
|
947
|
+
}
|
|
948
|
+
#meshList(meshes) {
|
|
949
|
+
if (!Array.isArray(meshes)) throw invalid("meshes must be an array of mesh handles");
|
|
950
|
+
return meshes.map((m) => this.#live(m));
|
|
951
|
+
}
|
|
952
|
+
/** A shown pose: the drag's, or the engine's. */
|
|
953
|
+
#shown(st) {
|
|
954
|
+
return st.local ?? st.pose;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Adds a mesh from world positions and returns its handle at once. The
|
|
958
|
+
* origin defaults to the bounding-box centre, computed here. The mesh has
|
|
959
|
+
* no slots until the Worker has added it; a failed add shows as an error
|
|
960
|
+
* on `status("mesh:<id>")`, and later calls on it fail with `UNKNOWN_MESH`.
|
|
961
|
+
*
|
|
962
|
+
* A mesh of {@link WorkerSceneOptions.backgroundAddTriangles} triangles or
|
|
963
|
+
* more (65,536 by default) is added in the background: requests sent after
|
|
964
|
+
* it that do not need it run meanwhile, so a reply to one of them can
|
|
965
|
+
* arrive before the mesh. Until it lands, `status("mesh:<id>")` reads
|
|
966
|
+
* `"computing"` and its views are empty; its buffers arrive with that
|
|
967
|
+
* status turning `"ready"`.
|
|
968
|
+
*/
|
|
969
|
+
addMesh(positions, indices, options = {}) {
|
|
970
|
+
this.#alive();
|
|
971
|
+
const p = copyArray(positions, "positions", (x) => x instanceof Float32Array ? x.slice() : Float64Array.from(x));
|
|
972
|
+
const i = copyArray(indices, "indices", (x) => Uint32Array.from(x));
|
|
973
|
+
const origin = options.origin === void 0 ? boxCentre(p) : [
|
|
974
|
+
options.origin[0],
|
|
975
|
+
options.origin[1],
|
|
976
|
+
options.origin[2]
|
|
977
|
+
];
|
|
978
|
+
const id = ++this.#nextMesh;
|
|
979
|
+
const handle = new MeshHandle();
|
|
980
|
+
const known = origin ?? [
|
|
981
|
+
0,
|
|
982
|
+
0,
|
|
983
|
+
0
|
|
984
|
+
];
|
|
985
|
+
const st = {
|
|
986
|
+
id,
|
|
987
|
+
handle,
|
|
988
|
+
origin: known,
|
|
989
|
+
positions: /* @__PURE__ */ new Float32Array(0),
|
|
990
|
+
normals: null,
|
|
991
|
+
colors: null,
|
|
992
|
+
values: null,
|
|
993
|
+
shown: null,
|
|
994
|
+
pendingRules: /* @__PURE__ */ new Map(),
|
|
995
|
+
indices: /* @__PURE__ */ new Uint32Array(0),
|
|
996
|
+
pose: poseOf(IDENTITY, [
|
|
997
|
+
0,
|
|
998
|
+
0,
|
|
999
|
+
0
|
|
1000
|
+
], known),
|
|
1001
|
+
local: void 0,
|
|
1002
|
+
localUntil: 0,
|
|
1003
|
+
requested: void 0,
|
|
1004
|
+
requestedUntil: 0,
|
|
1005
|
+
removed: false,
|
|
1006
|
+
gone: false,
|
|
1007
|
+
coloring: null,
|
|
1008
|
+
live: false,
|
|
1009
|
+
normalsOn: options.normals ?? true,
|
|
1010
|
+
add: void 0,
|
|
1011
|
+
sent: false
|
|
1012
|
+
};
|
|
1013
|
+
this.#meshes.set(id, st);
|
|
1014
|
+
this.#byMesh.set(handle, st);
|
|
1015
|
+
st.add = {
|
|
1016
|
+
kind: "addMesh",
|
|
1017
|
+
rev: ++this.#rev,
|
|
1018
|
+
id,
|
|
1019
|
+
positions: p.buffer,
|
|
1020
|
+
f64: !(p instanceof Float32Array),
|
|
1021
|
+
indices: i.buffer,
|
|
1022
|
+
options: {
|
|
1023
|
+
origin,
|
|
1024
|
+
normals: st.normalsOn
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
this.#push(st.add);
|
|
1028
|
+
return handle;
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Removes a mesh, ending an active drag of it first. Later calls on it give
|
|
1032
|
+
* `UNKNOWN_MESH`; its mirrors stay readable until the removal is delivered
|
|
1033
|
+
* by `commitFrame()`.
|
|
1034
|
+
*/
|
|
1035
|
+
removeMesh(mesh) {
|
|
1036
|
+
const st = this.#live(mesh);
|
|
1037
|
+
if (this.#drag?.mesh === st) this.#drag.end();
|
|
1038
|
+
st.removed = true;
|
|
1039
|
+
const rev = ++this.#rev;
|
|
1040
|
+
for (const f of this.#fields.values()) {
|
|
1041
|
+
if (f.removed) continue;
|
|
1042
|
+
if (f.desc.on === st.id || f.desc.to.length === 1 && f.desc.to[0] === st.id) this.#fieldRemoved(f, rev);
|
|
1043
|
+
else if (f.desc.to.includes(st.id)) f.desc = {
|
|
1044
|
+
...f.desc,
|
|
1045
|
+
to: f.desc.to.filter((m) => m !== st.id)
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
for (const s of this.#sections.values()) if (!s.removed) s.meshes = s.meshes.filter((m) => m !== st);
|
|
1049
|
+
this.#push({
|
|
1050
|
+
kind: "removeMesh",
|
|
1051
|
+
rev,
|
|
1052
|
+
id: st.id
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
/** Sets a mesh's placement (one undo step); `placement()` follows when the result arrives. */
|
|
1056
|
+
setPlacement(mesh, placement) {
|
|
1057
|
+
const st = this.#live(mesh);
|
|
1058
|
+
const rotation = rotationMatrix(placement.rotation);
|
|
1059
|
+
const t = placement.translation;
|
|
1060
|
+
if (t?.length !== 3) throw invalid("translation must be 3 numbers");
|
|
1061
|
+
const translation = [
|
|
1062
|
+
t[0],
|
|
1063
|
+
t[1],
|
|
1064
|
+
t[2]
|
|
1065
|
+
];
|
|
1066
|
+
st.requested = poseOf(rotation, translation, st.origin);
|
|
1067
|
+
st.requestedUntil = this.#push({
|
|
1068
|
+
kind: "setPlacement",
|
|
1069
|
+
rev: ++this.#rev,
|
|
1070
|
+
id: st.id,
|
|
1071
|
+
rotation,
|
|
1072
|
+
translation,
|
|
1073
|
+
key: `placement:${st.id}`
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
/** The mesh's placement as mirrored (a drag's pose while it is held). */
|
|
1077
|
+
placement(mesh) {
|
|
1078
|
+
const p = this.#shown(this.#mirrored(mesh));
|
|
1079
|
+
return {
|
|
1080
|
+
rotation: [...p.rotation],
|
|
1081
|
+
translation: [...p.translation]
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
/** The column-major world matrix of the mesh's local render coordinates, as mirrored. */
|
|
1085
|
+
matrix4(mesh) {
|
|
1086
|
+
return this.#shown(this.#mirrored(mesh)).matrix4.slice();
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* The mirrors of the mesh's render buffers, at full slot length. Each
|
|
1090
|
+
* getter returns the current mirror; a mirror is replaced when the slot
|
|
1091
|
+
* count changes or a buffer turns on or off, so get views right before use.
|
|
1092
|
+
*/
|
|
1093
|
+
views(mesh) {
|
|
1094
|
+
const st = this.#mirrored(mesh);
|
|
1095
|
+
const guard = this.#guard;
|
|
1096
|
+
const wrap = (v) => guard === void 0 ? v : guard.wrap(v);
|
|
1097
|
+
return {
|
|
1098
|
+
positions: () => wrap(st.positions),
|
|
1099
|
+
normals: () => st.normals === null ? null : wrap(st.normals),
|
|
1100
|
+
colors: () => st.colors === null ? null : wrap(st.colors),
|
|
1101
|
+
values: () => {
|
|
1102
|
+
this.#wantValues();
|
|
1103
|
+
return st.values === null ? null : wrap(st.values);
|
|
1104
|
+
},
|
|
1105
|
+
indices: () => wrap(st.indices)
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Turns the values mirror on, at the first `values()` read: until then
|
|
1110
|
+
* results carry no value bytes, so scenes drawn with vertex colours pay
|
|
1111
|
+
* nothing for it. The mirror fills with the next result.
|
|
1112
|
+
*/
|
|
1113
|
+
#wantValues() {
|
|
1114
|
+
if (!this.#values) {
|
|
1115
|
+
this.#values = true;
|
|
1116
|
+
this.#push({
|
|
1117
|
+
kind: "values",
|
|
1118
|
+
rev: ++this.#rev
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* The rule the mirrored colours and values are made by (a frozen copy of
|
|
1124
|
+
* the one given to `setColoring`, the same object until another rule is
|
|
1125
|
+
* applied), or `null` without colouring. It follows the
|
|
1126
|
+
* results: a new rule shows with the batch that applies it, a rejected one
|
|
1127
|
+
* never, and a removed field's colouring goes when the removal is applied.
|
|
1128
|
+
*/
|
|
1129
|
+
coloring(mesh) {
|
|
1130
|
+
return this.#mirrored(mesh).shown;
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Starts an optimistic drag. `move` shows the pose here at once and sends
|
|
1134
|
+
* at most one move per batch; `end` and `cancel` are synchronous here.
|
|
1135
|
+
* `cancel` puts the start pose back and records nothing.
|
|
1136
|
+
*/
|
|
1137
|
+
drag(mesh) {
|
|
1138
|
+
const st = this.#live(mesh);
|
|
1139
|
+
if (this.#drag?.active) throw invalid("a drag is already active; end or cancel it first");
|
|
1140
|
+
const start = st.requested !== void 0 && (st.local === void 0 || st.requestedUntil > st.localUntil) ? st.requested : st.local ?? st.pose;
|
|
1141
|
+
const key = `placement:${st.id}`;
|
|
1142
|
+
this.#push({
|
|
1143
|
+
kind: "drag",
|
|
1144
|
+
rev: ++this.#rev,
|
|
1145
|
+
id: st.id,
|
|
1146
|
+
phase: "begin",
|
|
1147
|
+
key
|
|
1148
|
+
});
|
|
1149
|
+
st.local = start;
|
|
1150
|
+
st.localUntil = Number.POSITIVE_INFINITY;
|
|
1151
|
+
const finish = (phase) => {
|
|
1152
|
+
if (!d.active) return false;
|
|
1153
|
+
d.active = false;
|
|
1154
|
+
this.#drag = void 0;
|
|
1155
|
+
if (this.#terminated) return true;
|
|
1156
|
+
st.localUntil = this.#push({
|
|
1157
|
+
kind: "drag",
|
|
1158
|
+
rev: ++this.#rev,
|
|
1159
|
+
id: st.id,
|
|
1160
|
+
phase,
|
|
1161
|
+
key
|
|
1162
|
+
});
|
|
1163
|
+
return true;
|
|
1164
|
+
};
|
|
1165
|
+
const d = {
|
|
1166
|
+
mesh: st,
|
|
1167
|
+
active: true,
|
|
1168
|
+
end: () => {
|
|
1169
|
+
finish("end");
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
this.#drag = d;
|
|
1173
|
+
return {
|
|
1174
|
+
get active() {
|
|
1175
|
+
return d.active;
|
|
1176
|
+
},
|
|
1177
|
+
move: (placement) => {
|
|
1178
|
+
if (!d.active) throw invalid("the drag is over");
|
|
1179
|
+
this.#alive();
|
|
1180
|
+
const rotation = rotationMatrix(placement.rotation);
|
|
1181
|
+
const t = placement.translation;
|
|
1182
|
+
if (t?.length !== 3) throw invalid("translation must be 3 numbers");
|
|
1183
|
+
const translation = [
|
|
1184
|
+
t[0],
|
|
1185
|
+
t[1],
|
|
1186
|
+
t[2]
|
|
1187
|
+
];
|
|
1188
|
+
st.local = poseOf(rotation, translation, st.origin);
|
|
1189
|
+
this.#optimistic.add(st);
|
|
1190
|
+
this.#push({
|
|
1191
|
+
kind: "drag",
|
|
1192
|
+
rev: ++this.#rev,
|
|
1193
|
+
id: st.id,
|
|
1194
|
+
phase: "move",
|
|
1195
|
+
rotation,
|
|
1196
|
+
translation,
|
|
1197
|
+
key
|
|
1198
|
+
});
|
|
1199
|
+
},
|
|
1200
|
+
end: d.end,
|
|
1201
|
+
cancel: () => {
|
|
1202
|
+
if (finish("cancel")) {
|
|
1203
|
+
st.local = start;
|
|
1204
|
+
this.#optimistic.add(st);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
/** Edits a mesh's geometry (one undo step); resolves with the ids added. */
|
|
1210
|
+
edit(mesh, ops) {
|
|
1211
|
+
return this.#ask((rev, qid) => ({
|
|
1212
|
+
kind: "edit",
|
|
1213
|
+
rev,
|
|
1214
|
+
id: this.#live(mesh).id,
|
|
1215
|
+
payload: copyInput(ops, "ops"),
|
|
1216
|
+
qid
|
|
1217
|
+
}), (v) => v);
|
|
1218
|
+
}
|
|
1219
|
+
/** Compacts a mesh's slots (its slot counts change). */
|
|
1220
|
+
compact(mesh) {
|
|
1221
|
+
const st = this.#live(mesh);
|
|
1222
|
+
this.#push({
|
|
1223
|
+
kind: "compact",
|
|
1224
|
+
rev: ++this.#rev,
|
|
1225
|
+
id: st.id
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
/** A report of the mesh's defects; see `Scene.analyze`. */
|
|
1229
|
+
analyze(mesh, options) {
|
|
1230
|
+
return this.#query("analyze", () => ({
|
|
1231
|
+
mesh: this.#live(mesh).id,
|
|
1232
|
+
options
|
|
1233
|
+
}), (v) => v);
|
|
1234
|
+
}
|
|
1235
|
+
repair(mesh, op) {
|
|
1236
|
+
return this.#ask((rev, qid) => ({
|
|
1237
|
+
kind: "repair",
|
|
1238
|
+
rev,
|
|
1239
|
+
id: this.#live(mesh).id,
|
|
1240
|
+
payload: copyInput(op, "op"),
|
|
1241
|
+
qid
|
|
1242
|
+
}), (v) => v);
|
|
1243
|
+
}
|
|
1244
|
+
/** Undoes the latest step; an active drag is ended first. */
|
|
1245
|
+
undo() {
|
|
1246
|
+
this.#alive();
|
|
1247
|
+
this.#drag?.end();
|
|
1248
|
+
this.#forgetRequested();
|
|
1249
|
+
this.#push({
|
|
1250
|
+
kind: "undo",
|
|
1251
|
+
rev: ++this.#rev
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
/** Redoes the latest undone step; an active drag is ended first. */
|
|
1255
|
+
redo() {
|
|
1256
|
+
this.#alive();
|
|
1257
|
+
this.#drag?.end();
|
|
1258
|
+
this.#forgetRequested();
|
|
1259
|
+
this.#push({
|
|
1260
|
+
kind: "redo",
|
|
1261
|
+
rev: ++this.#rev
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* An undo or redo is queued: requested placements and the poses held for
|
|
1266
|
+
* ended drags no longer say where the meshes will be. The engine's pose is
|
|
1267
|
+
* shown (and a new drag starts from it) until the results arrive.
|
|
1268
|
+
*/
|
|
1269
|
+
#forgetRequested() {
|
|
1270
|
+
for (const st of this.#meshes.values()) {
|
|
1271
|
+
st.requested = void 0;
|
|
1272
|
+
if (st.local !== void 0 && st.localUntil !== Number.POSITIVE_INFINITY) {
|
|
1273
|
+
if (!samePose(st.local, st.pose)) this.#optimistic.add(st);
|
|
1274
|
+
st.local = void 0;
|
|
1275
|
+
st.localUntil = 0;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* The threads the engine computes with: more than 1 when the threaded
|
|
1281
|
+
* engine runs (see {@link WorkerSceneOptions.threads}), 1 when
|
|
1282
|
+
* single-threaded. As of the current Worker's start (1 until it is ready).
|
|
1283
|
+
*/
|
|
1284
|
+
get threads() {
|
|
1285
|
+
return this.#threads;
|
|
1286
|
+
}
|
|
1287
|
+
/** Whether there is a step to undo, as of the latest result. */
|
|
1288
|
+
get canUndo() {
|
|
1289
|
+
return this.#history.canUndo;
|
|
1290
|
+
}
|
|
1291
|
+
/** Whether there is a step to redo, as of the latest result. */
|
|
1292
|
+
get canRedo() {
|
|
1293
|
+
return this.#history.canRedo;
|
|
1294
|
+
}
|
|
1295
|
+
/** Adds a signed distance field; see `Scene.addDistanceField`. */
|
|
1296
|
+
addDistanceField(desc) {
|
|
1297
|
+
return this.#addField(desc, void 0);
|
|
1298
|
+
}
|
|
1299
|
+
/** A field add, under `key` when given (see {@link addFieldKeyed}). */
|
|
1300
|
+
#addField(desc, key) {
|
|
1301
|
+
this.#alive();
|
|
1302
|
+
const desc2 = {
|
|
1303
|
+
name: desc.name,
|
|
1304
|
+
on: this.#live(desc.on).id,
|
|
1305
|
+
to: targetsOf(desc.to).map((m) => this.#live(m).id),
|
|
1306
|
+
maxDistance: desc.maxDistance,
|
|
1307
|
+
sign: desc.sign
|
|
1308
|
+
};
|
|
1309
|
+
const id = ++this.#nextField;
|
|
1310
|
+
const handle = new FieldHandle();
|
|
1311
|
+
const st = {
|
|
1312
|
+
id,
|
|
1313
|
+
handle,
|
|
1314
|
+
desc: desc2,
|
|
1315
|
+
removed: false
|
|
1316
|
+
};
|
|
1317
|
+
this.#fields.set(id, st);
|
|
1318
|
+
this.#byField.set(handle, st);
|
|
1319
|
+
this.#push(key === void 0 ? {
|
|
1320
|
+
kind: "field",
|
|
1321
|
+
rev: ++this.#rev,
|
|
1322
|
+
field: id,
|
|
1323
|
+
op: "add",
|
|
1324
|
+
desc: desc2
|
|
1325
|
+
} : {
|
|
1326
|
+
kind: "field",
|
|
1327
|
+
rev: ++this.#rev,
|
|
1328
|
+
field: id,
|
|
1329
|
+
op: "add",
|
|
1330
|
+
desc: desc2,
|
|
1331
|
+
key
|
|
1332
|
+
});
|
|
1333
|
+
return handle;
|
|
1334
|
+
}
|
|
1335
|
+
/** Removes a field, and a colouring by it. */
|
|
1336
|
+
removeField(field) {
|
|
1337
|
+
const st = this.#field(field);
|
|
1338
|
+
const rev = ++this.#rev;
|
|
1339
|
+
this.#fieldRemoved(st, rev);
|
|
1340
|
+
this.#push({
|
|
1341
|
+
kind: "field",
|
|
1342
|
+
rev,
|
|
1343
|
+
field: st.id,
|
|
1344
|
+
op: "remove"
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
/** A field is removed (by request `rev`): its colourings go, and its state once that is applied. */
|
|
1348
|
+
#fieldRemoved(st, rev) {
|
|
1349
|
+
st.removed = true;
|
|
1350
|
+
for (const m of this.#meshes.values()) if (m.coloring?.field === st.handle) m.coloring = null;
|
|
1351
|
+
this.#prunes.push({
|
|
1352
|
+
rev,
|
|
1353
|
+
run: () => {
|
|
1354
|
+
this.#fields.delete(st.id);
|
|
1355
|
+
this.#byField.delete(st.handle);
|
|
1356
|
+
this.#fieldTombstones.add(st.handle);
|
|
1357
|
+
this.#forgetKeys([`field:${st.id}`], []);
|
|
1358
|
+
}
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* Runs the prunes whose removal is applied (revision `rev` or older).
|
|
1363
|
+
* Their keys are forgotten: `status()` gives `"idle"` for them.
|
|
1364
|
+
*/
|
|
1365
|
+
#runPrunes(rev) {
|
|
1366
|
+
if (this.#prunes.length === 0) return;
|
|
1367
|
+
const due = this.#prunes.filter((p) => p.rev <= rev);
|
|
1368
|
+
if (due.length === 0) return;
|
|
1369
|
+
this.#prunes = this.#prunes.filter((p) => p.rev > rev);
|
|
1370
|
+
for (const p of due) p.run();
|
|
1371
|
+
this.#statusChanged();
|
|
1372
|
+
}
|
|
1373
|
+
/** Forgets the statuses of `exact` keys and of keys starting with a `prefixes` entry. */
|
|
1374
|
+
#forgetKeys(exact, prefixes) {
|
|
1375
|
+
for (const key of exact) {
|
|
1376
|
+
this.#deleteStatus(key);
|
|
1377
|
+
this.#latest.delete(key);
|
|
1378
|
+
}
|
|
1379
|
+
if (prefixes.length > 0) {
|
|
1380
|
+
for (const key of [...this.#latest.keys()]) if (prefixes.some((p) => key.startsWith(p))) {
|
|
1381
|
+
this.#deleteStatus(key);
|
|
1382
|
+
this.#latest.delete(key);
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Colours a mesh from one of its fields, or turns colouring off with
|
|
1388
|
+
* `null`. Last wins: of several calls for a mesh in one frame, only the
|
|
1389
|
+
* last is sent. Tracked by `status("display:<id>")`.
|
|
1390
|
+
*/
|
|
1391
|
+
setColoring(mesh, rule) {
|
|
1392
|
+
const st = this.#live(mesh);
|
|
1393
|
+
const copy = rule === null ? null : copyRule(rule);
|
|
1394
|
+
const wire = copy === null ? null : {
|
|
1395
|
+
...copy,
|
|
1396
|
+
field: this.#field(copy.field).id
|
|
1397
|
+
};
|
|
1398
|
+
st.coloring = copy;
|
|
1399
|
+
const rev = ++this.#rev;
|
|
1400
|
+
st.pendingRules.set(rev, copy);
|
|
1401
|
+
this.#push({
|
|
1402
|
+
kind: "coloring",
|
|
1403
|
+
rev,
|
|
1404
|
+
id: st.id,
|
|
1405
|
+
rule: wire,
|
|
1406
|
+
key: `display:${st.id}`
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
/** A copy of the field's values as of its last update, one per vertex slot. */
|
|
1410
|
+
fetchFieldValues(field) {
|
|
1411
|
+
return this.#ask((rev, qid) => ({
|
|
1412
|
+
kind: "fetchFieldValues",
|
|
1413
|
+
rev,
|
|
1414
|
+
qid,
|
|
1415
|
+
field: this.#field(field).id
|
|
1416
|
+
}), (v) => v);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* The field's nearest-target indices as of its last update (the index in
|
|
1420
|
+
* its `to`, `0xffffffff` for none); see `Scene.fieldNearest`. A target
|
|
1421
|
+
* removed since shifts the later indices down.
|
|
1422
|
+
*/
|
|
1423
|
+
fetchFieldNearest(field) {
|
|
1424
|
+
return this.#query("fieldNearest", () => ({ field: this.#field(field).id }), (v) => v);
|
|
1425
|
+
}
|
|
1426
|
+
/** What the sign data found out about each of the field's targets; see `Scene.fieldTargetStatus`. */
|
|
1427
|
+
fieldTargetStatus(field) {
|
|
1428
|
+
return this.#query("fieldTargetStatus", () => ({ field: this.#field(field).id }), (v) => v);
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Whether the field is current, and what its sign data found out about the
|
|
1432
|
+
* targets together; see `Scene.fieldStatus`.
|
|
1433
|
+
*/
|
|
1434
|
+
fieldStatus(field) {
|
|
1435
|
+
return this.#query("fieldStatus", () => ({ field: this.#field(field).id }), (v) => v);
|
|
1436
|
+
}
|
|
1437
|
+
/** Adds a plane section; its results arrive with the next results. */
|
|
1438
|
+
addSection(desc) {
|
|
1439
|
+
this.#alive();
|
|
1440
|
+
const plane = checkPlane(desc.plane);
|
|
1441
|
+
const meshes = this.#meshList(desc.meshes);
|
|
1442
|
+
const id = ++this.#nextSection;
|
|
1443
|
+
const handle = new SectionHandle();
|
|
1444
|
+
const st = {
|
|
1445
|
+
id,
|
|
1446
|
+
handle,
|
|
1447
|
+
plane: normalised(plane),
|
|
1448
|
+
meshes,
|
|
1449
|
+
fill: desc.fill ?? false,
|
|
1450
|
+
removed: false,
|
|
1451
|
+
results: /* @__PURE__ */ new Map()
|
|
1452
|
+
};
|
|
1453
|
+
this.#sections.set(id, st);
|
|
1454
|
+
this.#bySection.set(handle, st);
|
|
1455
|
+
const wire = {
|
|
1456
|
+
plane,
|
|
1457
|
+
meshes: meshes.map((m) => m.id),
|
|
1458
|
+
fill: st.fill
|
|
1459
|
+
};
|
|
1460
|
+
this.#push({
|
|
1461
|
+
kind: "section",
|
|
1462
|
+
rev: ++this.#rev,
|
|
1463
|
+
section: id,
|
|
1464
|
+
op: "add",
|
|
1465
|
+
desc: wire
|
|
1466
|
+
});
|
|
1467
|
+
return handle;
|
|
1468
|
+
}
|
|
1469
|
+
#setSection(section, desc, apply) {
|
|
1470
|
+
this.#alive();
|
|
1471
|
+
const st = this.#section(section);
|
|
1472
|
+
apply(st);
|
|
1473
|
+
this.#push({
|
|
1474
|
+
kind: "section",
|
|
1475
|
+
rev: ++this.#rev,
|
|
1476
|
+
section: st.id,
|
|
1477
|
+
op: "set",
|
|
1478
|
+
desc
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
/** Moves a section's plane; `sectionPlane()` returns it at once. Last wins per frame. */
|
|
1482
|
+
setSectionPlane(section, plane) {
|
|
1483
|
+
const p = checkPlane(plane);
|
|
1484
|
+
this.#setSection(section, { plane: p }, (st) => {
|
|
1485
|
+
st.plane = normalised(p);
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
/** Changes the meshes a section cuts. Last wins per frame. */
|
|
1489
|
+
setSectionMeshes(section, meshes) {
|
|
1490
|
+
const list = this.#meshList(meshes);
|
|
1491
|
+
this.#setSection(section, { meshes: list.map((m) => m.id) }, (st) => {
|
|
1492
|
+
st.meshes = list;
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
/** Turns a section's fill on or off. Last wins per frame. */
|
|
1496
|
+
setSectionFill(section, fill) {
|
|
1497
|
+
this.#setSection(section, { fill }, (st) => {
|
|
1498
|
+
st.fill = fill;
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
/** Removes a section. Its handle then gives `UNKNOWN_SECTION`. */
|
|
1502
|
+
removeSection(section) {
|
|
1503
|
+
this.#alive();
|
|
1504
|
+
const st = this.#section(section);
|
|
1505
|
+
st.removed = true;
|
|
1506
|
+
st.results.clear();
|
|
1507
|
+
const rev = ++this.#rev;
|
|
1508
|
+
this.#prunes.push({
|
|
1509
|
+
rev,
|
|
1510
|
+
run: () => {
|
|
1511
|
+
this.#sections.delete(st.id);
|
|
1512
|
+
this.#bySection.delete(st.handle);
|
|
1513
|
+
this.#sectionTombstones.add(st.handle);
|
|
1514
|
+
this.#forgetKeys([`section:${st.id}`], [`section:${st.id}:`]);
|
|
1515
|
+
}
|
|
1516
|
+
});
|
|
1517
|
+
this.#push({
|
|
1518
|
+
kind: "section",
|
|
1519
|
+
rev,
|
|
1520
|
+
section: st.id,
|
|
1521
|
+
op: "remove"
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* The section's latest result for a mesh as mirrored (empty and `"stale"`
|
|
1526
|
+
* until the first arrives). Do not modify it.
|
|
1527
|
+
*
|
|
1528
|
+
* @throws `INVALID_ARGUMENT` when the section does not cut `mesh`.
|
|
1529
|
+
*/
|
|
1530
|
+
section(section, mesh) {
|
|
1531
|
+
const s = this.#section(section);
|
|
1532
|
+
const m = this.#mirrored(mesh);
|
|
1533
|
+
const result = s.results.get(m.id);
|
|
1534
|
+
if (result !== void 0) return result;
|
|
1535
|
+
if (!s.meshes.includes(m)) throw invalid("the section does not cut this mesh");
|
|
1536
|
+
return {
|
|
1537
|
+
status: "stale",
|
|
1538
|
+
contours: [],
|
|
1539
|
+
length: 0,
|
|
1540
|
+
area: 0
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
/** The section's plane as last set here, the normal normalised. */
|
|
1544
|
+
sectionPlane(section) {
|
|
1545
|
+
const p = this.#section(section).plane;
|
|
1546
|
+
return {
|
|
1547
|
+
origin: [...p.origin],
|
|
1548
|
+
normal: [...p.normal]
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1551
|
+
/** The closest pair between two meshes' contours in a section; see `Scene.sectionGap`. */
|
|
1552
|
+
sectionGap(section, a, b) {
|
|
1553
|
+
return this.#query("sectionGap", () => ({
|
|
1554
|
+
section: this.#section(section).id,
|
|
1555
|
+
a: this.#live(a).id,
|
|
1556
|
+
b: this.#live(b).id
|
|
1557
|
+
}), (v) => v);
|
|
1558
|
+
}
|
|
1559
|
+
/** The nearest hit of a world ray over every mesh, or `null`; see `Scene.raycast`. */
|
|
1560
|
+
raycast(origin, direction, options) {
|
|
1561
|
+
return this.#query("raycast", () => ({
|
|
1562
|
+
origin: [...origin],
|
|
1563
|
+
direction: [...direction],
|
|
1564
|
+
options
|
|
1565
|
+
}), (v) => v === null ? null : {
|
|
1566
|
+
...v,
|
|
1567
|
+
mesh: this.#handleOf(v.mesh)
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
/** The surface point nearest to a world point, or `null`; see `Scene.closestPoint`. */
|
|
1571
|
+
closestPoint(point, options = {}) {
|
|
1572
|
+
return this.#query("closestPoint", () => ({
|
|
1573
|
+
point: [...point],
|
|
1574
|
+
options: {
|
|
1575
|
+
maxDistance: options.maxDistance,
|
|
1576
|
+
mesh: options.mesh === void 0 ? void 0 : this.#live(options.mesh).id
|
|
1577
|
+
}
|
|
1578
|
+
}), (v) => v === null ? null : {
|
|
1579
|
+
...v,
|
|
1580
|
+
mesh: this.#handleOf(v.mesh)
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
/** The distance between two meshes' surfaces, or `null`; see `Scene.meshDistance`. */
|
|
1584
|
+
meshDistance(a, b, options) {
|
|
1585
|
+
return this.#query("meshDistance", () => ({
|
|
1586
|
+
a: this.#live(a).id,
|
|
1587
|
+
b: this.#live(b).id,
|
|
1588
|
+
options
|
|
1589
|
+
}), (v) => v);
|
|
1590
|
+
}
|
|
1591
|
+
/** Whether two meshes intersect or touch as placed. */
|
|
1592
|
+
intersects(a, b) {
|
|
1593
|
+
return this.#query("intersects", () => ({
|
|
1594
|
+
a: this.#live(a).id,
|
|
1595
|
+
b: this.#live(b).id
|
|
1596
|
+
}), (v) => v);
|
|
1597
|
+
}
|
|
1598
|
+
/** Every mesh pair (or every pair of `pairs`) within `margin`; see `Scene.findContacts`. */
|
|
1599
|
+
findContacts(options = {}) {
|
|
1600
|
+
return this.#query("findContacts", () => ({
|
|
1601
|
+
margin: options.margin,
|
|
1602
|
+
pairs: options.pairs?.map(([x, y]) => [this.#live(x).id, this.#live(y).id])
|
|
1603
|
+
}), (v) => v.map((c) => ({
|
|
1604
|
+
...c,
|
|
1605
|
+
a: this.#handleOf(c.a),
|
|
1606
|
+
b: this.#handleOf(c.b)
|
|
1607
|
+
})));
|
|
1608
|
+
}
|
|
1609
|
+
#handleOf(id) {
|
|
1610
|
+
const st = this.#meshes.get(id);
|
|
1611
|
+
if (st === void 0) throw new FastMeshError("UNKNOWN_MESH", `no mesh with client id ${id}`);
|
|
1612
|
+
return st.handle;
|
|
1613
|
+
}
|
|
1614
|
+
/** Registers a listener for {@link WorkerScene.commitFrame}; returns the function that removes it. */
|
|
1615
|
+
onChanges(listener) {
|
|
1616
|
+
this.#alive();
|
|
1617
|
+
this.#listeners.add(listener);
|
|
1618
|
+
return () => {
|
|
1619
|
+
this.#listeners.delete(listener);
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Call once per animation frame. Sends this frame's requests to the Worker
|
|
1624
|
+
* as one batch, then delivers to every listener, and returns, the change
|
|
1625
|
+
* records of the results received since the last call (already applied to
|
|
1626
|
+
* the mirrors) plus the drags' pose changes made here. Every listener runs
|
|
1627
|
+
* even if one throws; the first error is rethrown afterwards.
|
|
1628
|
+
*/
|
|
1629
|
+
commitFrame() {
|
|
1630
|
+
this.#alive();
|
|
1631
|
+
this.#frameLoop = true;
|
|
1632
|
+
if (this.#fallback !== void 0) {
|
|
1633
|
+
clearTimeout(this.#fallback);
|
|
1634
|
+
this.#fallback = void 0;
|
|
1635
|
+
}
|
|
1636
|
+
this.#flush();
|
|
1637
|
+
for (const st of this.#optimistic) {
|
|
1638
|
+
const record = {
|
|
1639
|
+
mesh: st.handle,
|
|
1640
|
+
added: false,
|
|
1641
|
+
removed: false,
|
|
1642
|
+
placementChanged: true,
|
|
1643
|
+
capacityChanged: false,
|
|
1644
|
+
positions: [],
|
|
1645
|
+
normals: [],
|
|
1646
|
+
colors: [],
|
|
1647
|
+
indices: [],
|
|
1648
|
+
fieldsChanged: [],
|
|
1649
|
+
sectionsChanged: []
|
|
1650
|
+
};
|
|
1651
|
+
const prev = this.#changes.get(st);
|
|
1652
|
+
if (prev === void 0) this.#changes.set(st, record);
|
|
1653
|
+
else if (!prev.removed) prev.placementChanged = true;
|
|
1654
|
+
}
|
|
1655
|
+
this.#optimistic.clear();
|
|
1656
|
+
const changes = [...this.#changes.values()];
|
|
1657
|
+
this.#changes.clear();
|
|
1658
|
+
for (const c of changes) if (c.removed) {
|
|
1659
|
+
const st = this.#byMesh.get(c.mesh);
|
|
1660
|
+
if (st === void 0) continue;
|
|
1661
|
+
st.gone = true;
|
|
1662
|
+
if (st.removed) {
|
|
1663
|
+
this.#meshes.delete(st.id);
|
|
1664
|
+
this.#byMesh.delete(st.handle);
|
|
1665
|
+
this.#tombstones.add(st.handle);
|
|
1666
|
+
const id = st.id;
|
|
1667
|
+
this.#forgetKeys([
|
|
1668
|
+
`mesh:${id}`,
|
|
1669
|
+
`placement:${id}`,
|
|
1670
|
+
`edit:${id}`,
|
|
1671
|
+
`display:${id}`
|
|
1672
|
+
], []);
|
|
1673
|
+
this.#statusChanged();
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
let failure;
|
|
1677
|
+
for (const listener of [...this.#listeners]) try {
|
|
1678
|
+
listener(changes);
|
|
1679
|
+
} catch (error) {
|
|
1680
|
+
failure ??= { error };
|
|
1681
|
+
}
|
|
1682
|
+
if (failure !== void 0) throw failure.error;
|
|
1683
|
+
return changes;
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* The state of a request key: `mesh:<id>`, `placement:<id>`, `edit:<id>`,
|
|
1687
|
+
* `display:<id>`, `field:<id>`, `section:<id>` (add and remove),
|
|
1688
|
+
* `section:<id>:plane` / `:meshes` / `:fill`, `history`. A result sets
|
|
1689
|
+
* `"ready"` or `"error"` only when no newer request for the key is pending.
|
|
1690
|
+
* A status covers only requests made under its key: a drag or edit does
|
|
1691
|
+
* not mark the `display:` or `section:` keys of the colours and sections
|
|
1692
|
+
* that catch up after it. Returns a copy.
|
|
1693
|
+
*/
|
|
1694
|
+
status(key) {
|
|
1695
|
+
const st = this.#status.get(key);
|
|
1696
|
+
return st === void 0 ? {
|
|
1697
|
+
status: "idle",
|
|
1698
|
+
revision: 0
|
|
1699
|
+
} : { ...st };
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Registers a listener called (on a microtask) when any status or the
|
|
1703
|
+
* undo/redo state changes; returns the function that removes it.
|
|
1704
|
+
*/
|
|
1705
|
+
onStatus(listener) {
|
|
1706
|
+
this.#statusListeners.add(listener);
|
|
1707
|
+
return () => {
|
|
1708
|
+
this.#statusListeners.delete(listener);
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
/** The client id behind a handle, as used in status keys. */
|
|
1712
|
+
idOf(handle) {
|
|
1713
|
+
if (handle instanceof MeshHandle) return this.#state(handle).id;
|
|
1714
|
+
const st = handle instanceof FieldHandle ? this.#byField.get(handle) : this.#bySection.get(handle);
|
|
1715
|
+
if (st === void 0) {
|
|
1716
|
+
if (handle instanceof FieldHandle && this.#fieldTombstones.has(handle)) throw new FastMeshError("UNKNOWN_FIELD", "the field was removed");
|
|
1717
|
+
if (handle instanceof SectionHandle && this.#sectionTombstones.has(handle)) throw new FastMeshError("UNKNOWN_SECTION", "the section was removed");
|
|
1718
|
+
throw invalid("not a handle of this Worker scene");
|
|
1719
|
+
}
|
|
1720
|
+
return st.id;
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Stops the Worker, starts a new one and replays the scene into it; this
|
|
1724
|
+
* is how a scene recovers after `INSTANCE_POISONED`. Resolves once the
|
|
1725
|
+
* replay's results are applied (reported by the next `commitFrame()`).
|
|
1726
|
+
*
|
|
1727
|
+
* The replay is built here, from what the main thread has:
|
|
1728
|
+
* - every mesh the engine had, re-added from its mirrors: live triangles
|
|
1729
|
+
* only, compacted (slot ids change; handles do not), with its origin;
|
|
1730
|
+
* - meshes whose add was never sent (still queued, or failed here after a
|
|
1731
|
+
* poisoning), from their own data;
|
|
1732
|
+
* - placements: the engine's, or, when the scene was not poisoned, the
|
|
1733
|
+
* latest requested one (a `setPlacement` or drag not acknowledged yet);
|
|
1734
|
+
* - fields, colourings and sections as last requested (removed ones are
|
|
1735
|
+
* not re-created).
|
|
1736
|
+
*
|
|
1737
|
+
* History is cleared (`canUndo`/`canRedo` are false). The replay is sent
|
|
1738
|
+
* at once, not with the next frame. Every replayed key is `"computing"`
|
|
1739
|
+
* until the replay's results arrive, and so is the key of every pending
|
|
1740
|
+
* declarative request (placement, drag, colouring, field, section), also
|
|
1741
|
+
* one that failed after a poisoning (its call was rejected then): it
|
|
1742
|
+
* settles with the replay (`"ready"`, or `"error"` when the replay failed
|
|
1743
|
+
* for it), which applies the newest value; after a poisoning, placements
|
|
1744
|
+
* replay the engine's pose. A colouring whose field cannot be replayed
|
|
1745
|
+
* (its mesh was lost) is dropped, with `UNKNOWN_FIELD` on its display key.
|
|
1746
|
+
* Removals count as done: field and section removal keys read `"idle"`
|
|
1747
|
+
* at once (their state is forgotten), mesh removal keys after the next
|
|
1748
|
+
* `commitFrame()` delivers the removal. When the replay fails as a whole
|
|
1749
|
+
* (no Worker, it could not be posted, a trap), the scene is poisoned and
|
|
1750
|
+
* the next `restart()` replays the same intent and settles those keys.
|
|
1751
|
+
*
|
|
1752
|
+
* What cannot be replayed surfaces as errors (`INSTANCE_POISONED`): edits,
|
|
1753
|
+
* repairs, compaction, undo/redo and queries sent and not answered, or not
|
|
1754
|
+
* sent yet (their promises reject), and meshes whose add was sent but
|
|
1755
|
+
* never acknowledged (their buffers went to the old Worker: they stay
|
|
1756
|
+
* failed, and calls on them give `UNKNOWN_MESH`). An active drag ends.
|
|
1757
|
+
* Mirrors, section results included, stay readable throughout. Calling it
|
|
1758
|
+
* again before it settles returns the same promise. When no Worker can be
|
|
1759
|
+
* created, the promise rejects and the scene stays poisoned (a later
|
|
1760
|
+
* `restart()` tries again).
|
|
1761
|
+
*/
|
|
1762
|
+
restart() {
|
|
1763
|
+
if (this.#terminated) return Promise.reject(invalid("the Worker scene is terminated"));
|
|
1764
|
+
if (this.#restarting !== void 0) return this.#restarting;
|
|
1765
|
+
const settle = this.#restart();
|
|
1766
|
+
let worker;
|
|
1767
|
+
try {
|
|
1768
|
+
worker = this.#make();
|
|
1769
|
+
} catch (e) {
|
|
1770
|
+
const error = {
|
|
1771
|
+
code: "INSTANCE_POISONED",
|
|
1772
|
+
message: `a new Worker could not be created (${e instanceof Error ? `${e.name}: ${e.message}` : String(e)})`
|
|
1773
|
+
};
|
|
1774
|
+
this.#poisonAll(error);
|
|
1775
|
+
this.#flush();
|
|
1776
|
+
this.#settle(settle, fromWire(error));
|
|
1777
|
+
return Promise.reject(fromWire(error));
|
|
1778
|
+
}
|
|
1779
|
+
this.#worker = this.#attach(worker);
|
|
1780
|
+
const sent = this.#flush();
|
|
1781
|
+
if (sent === void 0) {
|
|
1782
|
+
const error = {
|
|
1783
|
+
code: "INSTANCE_POISONED",
|
|
1784
|
+
message: "the restart's replay could not be sent to the Worker; restart again"
|
|
1785
|
+
};
|
|
1786
|
+
this.#poisonAll(error);
|
|
1787
|
+
this.#settle(settle, fromWire(error));
|
|
1788
|
+
return Promise.reject(fromWire(error));
|
|
1789
|
+
}
|
|
1790
|
+
const done = new Promise((resolve, reject) => {
|
|
1791
|
+
this.#batchDone.set(sent, {
|
|
1792
|
+
resolve: () => {
|
|
1793
|
+
this.#retryPoses = void 0;
|
|
1794
|
+
this.#settle(settle);
|
|
1795
|
+
resolve();
|
|
1796
|
+
},
|
|
1797
|
+
reject: (e) => {
|
|
1798
|
+
this.#settle(settle, e);
|
|
1799
|
+
reject(e);
|
|
1800
|
+
}
|
|
1801
|
+
});
|
|
1802
|
+
});
|
|
1803
|
+
this.#restarting = done;
|
|
1804
|
+
const clear = () => {
|
|
1805
|
+
if (this.#restarting === done) this.#restarting = void 0;
|
|
1806
|
+
};
|
|
1807
|
+
done.then(clear, clear);
|
|
1808
|
+
return done;
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Ends a restart for the keys it settles without a request of their own:
|
|
1812
|
+
* each is `"ready"`, or `"error"` with `error` (the replay failed) or with
|
|
1813
|
+
* the error of a key it depends on (the mesh or section it targets), unless
|
|
1814
|
+
* a newer request for it was made since. When the replay failed, the keys
|
|
1815
|
+
* are carried to the next restart, which settles them again.
|
|
1816
|
+
*/
|
|
1817
|
+
#settle(settle, error) {
|
|
1818
|
+
for (const [key, covers] of settle.keys) {
|
|
1819
|
+
if (this.#latest.get(key) !== settle.rev) continue;
|
|
1820
|
+
if (error !== void 0) this.#unsettled.set(key, {
|
|
1821
|
+
kind: "declarative",
|
|
1822
|
+
rev: settle.rev,
|
|
1823
|
+
covers
|
|
1824
|
+
});
|
|
1825
|
+
const failed = error ?? covers.map((c) => this.#status.get(c)).find((s) => s?.status === "error")?.error;
|
|
1826
|
+
this.#setStatus(key, failed === void 0 ? {
|
|
1827
|
+
status: "ready",
|
|
1828
|
+
revision: settle.rev
|
|
1829
|
+
} : {
|
|
1830
|
+
status: "error",
|
|
1831
|
+
revision: settle.rev,
|
|
1832
|
+
error: failed
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
this.#statusChanged();
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* Retires the old Worker and queues the replay (the only thing queued).
|
|
1839
|
+
* Returns the keys of declarative requests the replay covers without a
|
|
1840
|
+
* request under their own key, to settle with the replay's result.
|
|
1841
|
+
*/
|
|
1842
|
+
#restart() {
|
|
1843
|
+
const poisoned = this.#poison !== void 0;
|
|
1844
|
+
const old = this.#worker;
|
|
1845
|
+
this.#worker = INERT;
|
|
1846
|
+
old.terminate();
|
|
1847
|
+
this.#unwatch();
|
|
1848
|
+
this.#dropHandoff();
|
|
1849
|
+
if (this.#fallback !== void 0) {
|
|
1850
|
+
clearTimeout(this.#fallback);
|
|
1851
|
+
this.#fallback = void 0;
|
|
1852
|
+
}
|
|
1853
|
+
if (!this.#ready.settled) {
|
|
1854
|
+
this.#ready.settled = true;
|
|
1855
|
+
this.#ready.reject(invalid("the Worker was restarted"));
|
|
1856
|
+
}
|
|
1857
|
+
const poses = /* @__PURE__ */ new Map();
|
|
1858
|
+
for (const st of this.#meshes.values()) {
|
|
1859
|
+
const intended = st.requested !== void 0 && (st.local === void 0 || st.requestedUntil > st.localUntil) ? st.requested : st.local ?? st.pose;
|
|
1860
|
+
poses.set(st, this.#retryPoses?.get(st) ?? (poisoned ? st.pose : intended));
|
|
1861
|
+
}
|
|
1862
|
+
this.#retryPoses = poses;
|
|
1863
|
+
if (this.#drag !== void 0) {
|
|
1864
|
+
this.#drag.active = false;
|
|
1865
|
+
this.#drag = void 0;
|
|
1866
|
+
}
|
|
1867
|
+
for (const st of this.#meshes.values()) {
|
|
1868
|
+
if (!samePose(this.#shown(st), poses.get(st))) this.#optimistic.add(st);
|
|
1869
|
+
st.local = void 0;
|
|
1870
|
+
st.localUntil = 0;
|
|
1871
|
+
st.requested = void 0;
|
|
1872
|
+
st.requestedUntil = 0;
|
|
1873
|
+
}
|
|
1874
|
+
const lost = new FastMeshError("INSTANCE_POISONED", "the Worker was restarted before this request ran");
|
|
1875
|
+
const pending = [...this.#inflight.splice(0).flat(), ...this.#queue];
|
|
1876
|
+
this.#queue = [];
|
|
1877
|
+
const settleKeys = /* @__PURE__ */ new Map();
|
|
1878
|
+
const apply = (sorted) => {
|
|
1879
|
+
if (sorted.key === void 0 || this.#latest.get(sorted.key) !== sorted.rev) return;
|
|
1880
|
+
if (sorted.kind === "removal") this.#setStatus(sorted.key, {
|
|
1881
|
+
status: "ready",
|
|
1882
|
+
revision: sorted.rev
|
|
1883
|
+
});
|
|
1884
|
+
else if (sorted.kind === "declarative") settleKeys.set(sorted.key, sorted.covers);
|
|
1885
|
+
};
|
|
1886
|
+
for (const [key, entry] of [...this.#unsettled, ...this.#failedKeys]) apply({
|
|
1887
|
+
key,
|
|
1888
|
+
...entry
|
|
1889
|
+
});
|
|
1890
|
+
this.#unsettled.clear();
|
|
1891
|
+
this.#failedKeys.clear();
|
|
1892
|
+
for (const req of this.#failed) apply(sortOf(req));
|
|
1893
|
+
for (const req of pending) {
|
|
1894
|
+
const sorted = sortOf(req);
|
|
1895
|
+
if (sorted.kind === "lost") this.#fail([req], lost, false);
|
|
1896
|
+
else apply(sorted);
|
|
1897
|
+
}
|
|
1898
|
+
for (const p of this.#replies.values()) p.reject(lost);
|
|
1899
|
+
this.#replies.clear();
|
|
1900
|
+
this.#poison = void 0;
|
|
1901
|
+
this.#failed.length = 0;
|
|
1902
|
+
this.#failedDropped = 0;
|
|
1903
|
+
this.#history = {
|
|
1904
|
+
canUndo: false,
|
|
1905
|
+
canRedo: false
|
|
1906
|
+
};
|
|
1907
|
+
this.#statusChanged();
|
|
1908
|
+
const first = this.#rev + 1;
|
|
1909
|
+
if (this.#values) this.#push({
|
|
1910
|
+
kind: "values",
|
|
1911
|
+
rev: ++this.#rev
|
|
1912
|
+
});
|
|
1913
|
+
const replayed = /* @__PURE__ */ new Set();
|
|
1914
|
+
for (const st of this.#meshes.values()) {
|
|
1915
|
+
if (st.removed) {
|
|
1916
|
+
if (!st.gone) {
|
|
1917
|
+
st.live = false;
|
|
1918
|
+
st.add = void 0;
|
|
1919
|
+
this.#clearMirrors(st);
|
|
1920
|
+
this.#removedHere(st);
|
|
1921
|
+
}
|
|
1922
|
+
continue;
|
|
1923
|
+
}
|
|
1924
|
+
if (st.live) {
|
|
1925
|
+
const { positions, indices } = liveGeometry(st);
|
|
1926
|
+
this.#push({
|
|
1927
|
+
kind: "addMesh",
|
|
1928
|
+
rev: ++this.#rev,
|
|
1929
|
+
id: st.id,
|
|
1930
|
+
positions: positions.buffer,
|
|
1931
|
+
f64: true,
|
|
1932
|
+
indices: indices.buffer,
|
|
1933
|
+
options: {
|
|
1934
|
+
origin: st.origin,
|
|
1935
|
+
normals: st.normalsOn
|
|
1936
|
+
},
|
|
1937
|
+
inline: true
|
|
1938
|
+
});
|
|
1939
|
+
} else if (st.add !== void 0 && !st.sent) {
|
|
1940
|
+
st.add = {
|
|
1941
|
+
...st.add,
|
|
1942
|
+
rev: ++this.#rev,
|
|
1943
|
+
inline: true
|
|
1944
|
+
};
|
|
1945
|
+
this.#push(st.add);
|
|
1946
|
+
} else {
|
|
1947
|
+
const key = `mesh:${st.id}`;
|
|
1948
|
+
if (st.add !== void 0 && this.status(key).status !== "error") this.#setStatus(key, {
|
|
1949
|
+
status: "error",
|
|
1950
|
+
revision: this.#latest.get(key) ?? 0,
|
|
1951
|
+
error: lost
|
|
1952
|
+
});
|
|
1953
|
+
st.add = void 0;
|
|
1954
|
+
continue;
|
|
1955
|
+
}
|
|
1956
|
+
replayed.add(st.id);
|
|
1957
|
+
}
|
|
1958
|
+
for (const st of this.#meshes.values()) {
|
|
1959
|
+
const pose = poses.get(st);
|
|
1960
|
+
if (!replayed.has(st.id) || samePose(pose, poseOf(IDENTITY, [
|
|
1961
|
+
0,
|
|
1962
|
+
0,
|
|
1963
|
+
0
|
|
1964
|
+
], st.origin))) continue;
|
|
1965
|
+
st.requested = pose;
|
|
1966
|
+
st.requestedUntil = ++this.#rev;
|
|
1967
|
+
if (!samePose(pose, st.pose)) {
|
|
1968
|
+
st.local = pose;
|
|
1969
|
+
st.localUntil = st.requestedUntil;
|
|
1970
|
+
}
|
|
1971
|
+
this.#push({
|
|
1972
|
+
kind: "setPlacement",
|
|
1973
|
+
rev: st.requestedUntil,
|
|
1974
|
+
id: st.id,
|
|
1975
|
+
rotation: pose.rotation,
|
|
1976
|
+
translation: pose.translation,
|
|
1977
|
+
key: `placement:${st.id}`
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
const fields = /* @__PURE__ */ new Set();
|
|
1981
|
+
for (const f of this.#fields.values()) if (!f.removed && replayed.has(f.desc.on) && f.desc.to.every((m) => replayed.has(m))) {
|
|
1982
|
+
fields.add(f.id);
|
|
1983
|
+
this.#push({
|
|
1984
|
+
kind: "field",
|
|
1985
|
+
rev: ++this.#rev,
|
|
1986
|
+
field: f.id,
|
|
1987
|
+
op: "add",
|
|
1988
|
+
desc: f.desc
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
const dropped = /* @__PURE__ */ new Map();
|
|
1992
|
+
for (const st of this.#meshes.values()) {
|
|
1993
|
+
const rule = st.coloring;
|
|
1994
|
+
if (rule === null || !replayed.has(st.id)) continue;
|
|
1995
|
+
const f = this.#byField.get(rule.field);
|
|
1996
|
+
if (f !== void 0 && fields.has(f.id)) {
|
|
1997
|
+
const rev = ++this.#rev;
|
|
1998
|
+
st.pendingRules.set(rev, rule);
|
|
1999
|
+
this.#push({
|
|
2000
|
+
kind: "coloring",
|
|
2001
|
+
rev,
|
|
2002
|
+
id: st.id,
|
|
2003
|
+
rule: {
|
|
2004
|
+
...rule,
|
|
2005
|
+
field: f.id
|
|
2006
|
+
},
|
|
2007
|
+
key: `display:${st.id}`
|
|
2008
|
+
});
|
|
2009
|
+
} else {
|
|
2010
|
+
st.coloring = null;
|
|
2011
|
+
dropped.set(`display:${st.id}`, new FastMeshError("UNKNOWN_FIELD", "the colouring's field could not be replayed (its mesh was lost)"));
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
for (const s of this.#sections.values()) {
|
|
2015
|
+
if (s.removed) continue;
|
|
2016
|
+
for (const id of [...s.results.keys()]) if (!replayed.has(id)) s.results.delete(id);
|
|
2017
|
+
const desc = {
|
|
2018
|
+
plane: s.plane,
|
|
2019
|
+
meshes: s.meshes.filter((m) => replayed.has(m.id)).map((m) => m.id),
|
|
2020
|
+
fill: s.fill
|
|
2021
|
+
};
|
|
2022
|
+
this.#push({
|
|
2023
|
+
kind: "section",
|
|
2024
|
+
rev: ++this.#rev,
|
|
2025
|
+
section: s.id,
|
|
2026
|
+
op: "add",
|
|
2027
|
+
desc
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
const rev = this.#push({
|
|
2031
|
+
kind: "clearHistory",
|
|
2032
|
+
rev: ++this.#rev
|
|
2033
|
+
});
|
|
2034
|
+
const keys = /* @__PURE__ */ new Map();
|
|
2035
|
+
for (const [key, covers] of settleKeys) if ((this.#latest.get(key) ?? 0) < first && !dropped.has(key)) {
|
|
2036
|
+
keys.set(key, covers);
|
|
2037
|
+
this.#latest.set(key, rev);
|
|
2038
|
+
this.#setStatus(key, {
|
|
2039
|
+
status: "computing",
|
|
2040
|
+
revision: rev
|
|
2041
|
+
});
|
|
2042
|
+
}
|
|
2043
|
+
for (const [key, error] of dropped) {
|
|
2044
|
+
this.#latest.set(key, rev);
|
|
2045
|
+
this.#setStatus(key, {
|
|
2046
|
+
status: "error",
|
|
2047
|
+
revision: rev,
|
|
2048
|
+
error
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
this.#runPrunes(Number.POSITIVE_INFINITY);
|
|
2052
|
+
return {
|
|
2053
|
+
rev,
|
|
2054
|
+
keys
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
/** Records a mesh's removal for the next `commitFrame()`, as a result would. */
|
|
2058
|
+
#removedHere(st) {
|
|
2059
|
+
const record = {
|
|
2060
|
+
mesh: st.handle,
|
|
2061
|
+
added: false,
|
|
2062
|
+
removed: true,
|
|
2063
|
+
placementChanged: false,
|
|
2064
|
+
capacityChanged: false,
|
|
2065
|
+
positions: [],
|
|
2066
|
+
normals: [],
|
|
2067
|
+
colors: [],
|
|
2068
|
+
indices: [],
|
|
2069
|
+
fieldsChanged: [],
|
|
2070
|
+
sectionsChanged: []
|
|
2071
|
+
};
|
|
2072
|
+
const prev = this.#changes.get(st);
|
|
2073
|
+
this.#changes.set(st, prev === void 0 ? record : merge(prev, record));
|
|
2074
|
+
}
|
|
2075
|
+
/**
|
|
2076
|
+
* Stops the Worker. Pending promises reject with `INVALID_ARGUMENT`; later
|
|
2077
|
+
* calls throw it. Calling it again does nothing.
|
|
2078
|
+
*/
|
|
2079
|
+
terminate() {
|
|
2080
|
+
if (this.#terminated) return;
|
|
2081
|
+
this.#terminated = true;
|
|
2082
|
+
if (this.#fallback !== void 0) {
|
|
2083
|
+
clearTimeout(this.#fallback);
|
|
2084
|
+
this.#fallback = void 0;
|
|
2085
|
+
}
|
|
2086
|
+
if (this.#drag !== void 0) {
|
|
2087
|
+
this.#drag.active = false;
|
|
2088
|
+
this.#drag = void 0;
|
|
2089
|
+
}
|
|
2090
|
+
this.#worker.terminate();
|
|
2091
|
+
this.#unwatch();
|
|
2092
|
+
this.#dropHandoff();
|
|
2093
|
+
const error = invalid("the Worker scene is terminated");
|
|
2094
|
+
if (!this.#ready.settled) {
|
|
2095
|
+
this.#ready.settled = true;
|
|
2096
|
+
this.#ready.reject(error);
|
|
2097
|
+
}
|
|
2098
|
+
for (const p of [...this.#replies.values(), ...this.#batchDone.values()]) p.reject(error);
|
|
2099
|
+
this.#replies.clear();
|
|
2100
|
+
this.#batchDone.clear();
|
|
2101
|
+
this.#queue = [];
|
|
2102
|
+
this.#inflight.length = 0;
|
|
2103
|
+
}
|
|
2104
|
+
static {
|
|
2105
|
+
createScene = (make, options) => {
|
|
2106
|
+
const scene = new WorkerScene(make, options);
|
|
2107
|
+
return [scene, scene.#ready.promise];
|
|
2108
|
+
};
|
|
2109
|
+
addFieldKeyedOf = (scene, desc, key) => scene.#addField(desc, key);
|
|
2110
|
+
watchStatusKeysOf = (scene, sink) => {
|
|
2111
|
+
scene.#statusSinks.add(sink);
|
|
2112
|
+
return () => {
|
|
2113
|
+
scene.#statusSinks.delete(sink);
|
|
2114
|
+
};
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
};
|
|
2118
|
+
/**
|
|
2119
|
+
* Internal, not exported from `fast-mesh-wasm/worker`: adds a distance field
|
|
2120
|
+
* under `key`, the key of the display it is built for (`display:<meshId>`),
|
|
2121
|
+
* so the engine abandons the build when the colouring it feeds is superseded
|
|
2122
|
+
* before the build starts (the field is then built when first needed). Its
|
|
2123
|
+
* status is reported under `key`. Used by the store (`fast-mesh-wasm/store`).
|
|
2124
|
+
*/
|
|
2125
|
+
function addFieldKeyed(scene, desc, key) {
|
|
2126
|
+
return addFieldKeyedOf(scene, desc, key);
|
|
2127
|
+
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Internal, not exported from `fast-mesh-wasm/worker`: calls `sink` at once
|
|
2130
|
+
* with each key whose status is set or forgotten (before the `onStatus`
|
|
2131
|
+
* listeners run, on a microtask), so the store re-derives only the states
|
|
2132
|
+
* that read those keys. Returns the function that stops it.
|
|
2133
|
+
*/
|
|
2134
|
+
function watchStatusKeys(scene, sink) {
|
|
2135
|
+
return watchStatusKeysOf(scene, sink);
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* A deep copy of a caller's request input (edit ops, repair ops), taken at
|
|
2139
|
+
* call time so later changes to it do not leak into the request.
|
|
2140
|
+
*/
|
|
2141
|
+
function copyInput(value, what) {
|
|
2142
|
+
try {
|
|
2143
|
+
return structuredClone(value);
|
|
2144
|
+
} catch (e) {
|
|
2145
|
+
throw invalid(`${what} could not be copied (${e instanceof Error ? e.message : String(e)})`);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
/** Copies an array-like input; anything else is `INVALID_ARGUMENT`, as `Scene` reports bad input. */
|
|
2149
|
+
function copyArray(value, what, copy) {
|
|
2150
|
+
if (typeof value !== "object" || value === null || typeof value.length !== "number") throw invalid(`${what} must be an array or typed array of numbers`);
|
|
2151
|
+
try {
|
|
2152
|
+
return copy(value);
|
|
2153
|
+
} catch (e) {
|
|
2154
|
+
throw invalid(`${what} could not be read as numbers (${e instanceof Error ? e.message : String(e)})`);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
2158
|
+
* A mesh's live geometry from its mirrors, compacted: the live triangles (a
|
|
2159
|
+
* removed one reads `0, 0, 0`) in slot order, over the vertices they use in
|
|
2160
|
+
* slot order, as world positions before placement (local plus origin, in
|
|
2161
|
+
* `f64`, so the engine gets the same `f32` local positions back).
|
|
2162
|
+
*/
|
|
2163
|
+
function liveGeometry(st) {
|
|
2164
|
+
const idx = st.indices;
|
|
2165
|
+
const p = st.positions;
|
|
2166
|
+
const slots = p.length / 3;
|
|
2167
|
+
const index = new Int32Array(slots).fill(-1);
|
|
2168
|
+
let triangles = 0;
|
|
2169
|
+
for (let t = 0; t < idx.length; t += 3) {
|
|
2170
|
+
const a = idx[t];
|
|
2171
|
+
const b = idx[t + 1];
|
|
2172
|
+
const c = idx[t + 2];
|
|
2173
|
+
if (a === 0 && b === 0 && c === 0 || a >= slots || b >= slots || c >= slots) continue;
|
|
2174
|
+
index[a] = index[b] = index[c] = 0;
|
|
2175
|
+
triangles++;
|
|
2176
|
+
}
|
|
2177
|
+
let vertices = 0;
|
|
2178
|
+
for (let v = 0; v < slots; v++) if (index[v] === 0) index[v] = vertices++;
|
|
2179
|
+
const positions = new Float64Array(3 * vertices);
|
|
2180
|
+
const [ox, oy, oz] = st.origin;
|
|
2181
|
+
for (let v = 0; v < slots; v++) {
|
|
2182
|
+
const k = index[v];
|
|
2183
|
+
if (k >= 0) {
|
|
2184
|
+
positions[3 * k] = p[3 * v] + ox;
|
|
2185
|
+
positions[3 * k + 1] = p[3 * v + 1] + oy;
|
|
2186
|
+
positions[3 * k + 2] = p[3 * v + 2] + oz;
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
const indices = new Uint32Array(3 * triangles);
|
|
2190
|
+
let at = 0;
|
|
2191
|
+
for (let t = 0; t < idx.length; t += 3) {
|
|
2192
|
+
const a = idx[t];
|
|
2193
|
+
const b = idx[t + 1];
|
|
2194
|
+
const c = idx[t + 2];
|
|
2195
|
+
if (a === 0 && b === 0 && c === 0 || a >= slots || b >= slots || c >= slots) continue;
|
|
2196
|
+
indices[at++] = index[a];
|
|
2197
|
+
indices[at++] = index[b];
|
|
2198
|
+
indices[at++] = index[c];
|
|
2199
|
+
}
|
|
2200
|
+
return {
|
|
2201
|
+
positions,
|
|
2202
|
+
indices
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
/** Merges a later record into an earlier one of the same mesh. */
|
|
2206
|
+
function merge(a, b) {
|
|
2207
|
+
if (b.removed) return {
|
|
2208
|
+
...b,
|
|
2209
|
+
added: false
|
|
2210
|
+
};
|
|
2211
|
+
if (b.added) return {
|
|
2212
|
+
...b,
|
|
2213
|
+
fieldsChanged: union(a.fieldsChanged, b.fieldsChanged),
|
|
2214
|
+
sectionsChanged: union(a.sectionsChanged, b.sectionsChanged)
|
|
2215
|
+
};
|
|
2216
|
+
if (a.removed) return b;
|
|
2217
|
+
return {
|
|
2218
|
+
mesh: a.mesh,
|
|
2219
|
+
added: a.added,
|
|
2220
|
+
removed: false,
|
|
2221
|
+
placementChanged: a.placementChanged || b.placementChanged,
|
|
2222
|
+
capacityChanged: a.capacityChanged || b.capacityChanged,
|
|
2223
|
+
positions: mergeRanges(a.positions, b.positions),
|
|
2224
|
+
normals: mergeRanges(a.normals, b.normals),
|
|
2225
|
+
colors: mergeRanges(a.colors, b.colors),
|
|
2226
|
+
indices: mergeRanges(a.indices, b.indices),
|
|
2227
|
+
fieldsChanged: union(a.fieldsChanged, b.fieldsChanged),
|
|
2228
|
+
sectionsChanged: union(a.sectionsChanged, b.sectionsChanged)
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* A copy of a valid plane; throws `INVALID_ARGUMENT` (as `Scene` and the
|
|
2233
|
+
* engine do) for a malformed, non-finite or zero-normal plane, so a mirrored
|
|
2234
|
+
* plane is never invalid.
|
|
2235
|
+
*/
|
|
2236
|
+
function checkPlane(plane) {
|
|
2237
|
+
if (plane?.origin?.length !== 3 || plane.normal?.length !== 3) throw invalid("plane needs a 3-number origin and normal");
|
|
2238
|
+
const origin = [
|
|
2239
|
+
plane.origin[0],
|
|
2240
|
+
plane.origin[1],
|
|
2241
|
+
plane.origin[2]
|
|
2242
|
+
];
|
|
2243
|
+
const normal = [
|
|
2244
|
+
plane.normal[0],
|
|
2245
|
+
plane.normal[1],
|
|
2246
|
+
plane.normal[2]
|
|
2247
|
+
];
|
|
2248
|
+
if (![...origin, ...normal].every((v) => typeof v === "number" && Number.isFinite(v))) throw invalid("plane origin and normal must be finite");
|
|
2249
|
+
if (normal[0] === 0 && normal[1] === 0 && normal[2] === 0) throw invalid("plane normal must not be zero");
|
|
2250
|
+
return {
|
|
2251
|
+
origin,
|
|
2252
|
+
normal
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* A checked plane with its normal normalised. Scaled by its largest
|
|
2257
|
+
* component first, so a huge finite normal (whose length overflows) or a
|
|
2258
|
+
* tiny one (whose length underflows) still normalises.
|
|
2259
|
+
*/
|
|
2260
|
+
function normalised(plane) {
|
|
2261
|
+
const m = Math.max(Math.abs(plane.normal[0]), Math.abs(plane.normal[1]), Math.abs(plane.normal[2]));
|
|
2262
|
+
const n = [
|
|
2263
|
+
plane.normal[0] / m,
|
|
2264
|
+
plane.normal[1] / m,
|
|
2265
|
+
plane.normal[2] / m
|
|
2266
|
+
];
|
|
2267
|
+
const len = Math.hypot(n[0], n[1], n[2]);
|
|
2268
|
+
return {
|
|
2269
|
+
origin: plane.origin,
|
|
2270
|
+
normal: [
|
|
2271
|
+
n[0] / len,
|
|
2272
|
+
n[1] / len,
|
|
2273
|
+
n[2] / len
|
|
2274
|
+
]
|
|
2275
|
+
};
|
|
2276
|
+
}
|
|
2277
|
+
//#endregion
|
|
2278
|
+
export { watchStatusKeys as i, addFieldKeyed as n, createWorkerScene as r, WorkerScene as t };
|