fast-mesh-wasm 0.2.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.
Files changed (50) hide show
  1. package/README.md +488 -1
  2. package/dist/{api-D0o2HjaU.js → api-BUy7FRx7.js} +11 -11
  3. package/dist/client-Bp9FRd70.js +2278 -0
  4. package/dist/client-m2zSdFlu.d.ts +305 -0
  5. package/dist/colormap-D_xH5hI5.js +303 -0
  6. package/dist/core-Cke_kZ2e.js +113 -0
  7. package/dist/core-D2X9GPfK.d.ts +15 -0
  8. package/dist/engine-B-ZEzR1c.js +1818 -0
  9. package/dist/mesh-B16gV3oX.d.ts +130 -0
  10. package/dist/mesh-B8pae8WA.js +428 -0
  11. package/dist/node.d.ts +3 -2
  12. package/dist/node.js +5 -4
  13. package/dist/protocol-CAUYm1gd.js +68 -0
  14. package/dist/protocol-W9R-iGl5.d.ts +293 -0
  15. package/dist/r3f.d.ts +59 -0
  16. package/dist/r3f.js +165 -0
  17. package/dist/react-CTADh3NN.js +124 -0
  18. package/dist/react.d.ts +65 -0
  19. package/dist/react.js +1 -0
  20. package/dist/scene-BG3EEyfw.js +1243 -0
  21. package/dist/scene-like-B_3qm0u6.d.ts +925 -0
  22. package/dist/snapshot-Cf6NgDl7.js +104 -0
  23. package/dist/store-D3ErV6o-.js +1379 -0
  24. package/dist/store-DNnHN33A.d.ts +285 -0
  25. package/dist/store.d.ts +61 -0
  26. package/dist/store.js +105 -0
  27. package/dist/three.d.ts +118 -0
  28. package/dist/three.js +390 -0
  29. package/dist/views-BaZqBxlX.js +189 -0
  30. package/dist/wasm/fast_mesh_wasm.d.ts +458 -0
  31. package/dist/wasm/fast_mesh_wasm.js +1150 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  33. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +74 -0
  34. package/dist/wasm-threads/fast_mesh_wasm.d.ts +540 -0
  35. package/dist/wasm-threads/fast_mesh_wasm.js +1513 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  37. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +93 -0
  38. package/dist/wasm-threads/package.json +7 -0
  39. package/dist/wasm-threads/snippets/fast-mesh-wasm-ae14781a92c2789e/inline0.js +16 -0
  40. package/dist/wasm-threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +107 -0
  41. package/dist/web.d.ts +3 -2
  42. package/dist/web.js +4 -2
  43. package/dist/worker-engine.d.ts +248 -0
  44. package/dist/worker-engine.js +1 -0
  45. package/dist/worker-entry.d.ts +1 -0
  46. package/dist/worker-entry.js +11 -0
  47. package/dist/worker.d.ts +2 -0
  48. package/dist/worker.js +1 -0
  49. package/package.json +53 -4
  50. package/dist/api-HcskOwd7.d.ts +0 -43
@@ -0,0 +1,1243 @@
1
+ import { a as release, c as wasmMemory, i as finalizer, n as call, r as ensureInitialized, t as FastMeshError } from "./core-Cke_kZ2e.js";
2
+ import { a as FieldHandle, c as rotationMatrix, i as encodeRule, l as targetsOf, n as meshViews, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-BaZqBxlX.js";
3
+ import { WasmScene } from "./wasm/fast_mesh_wasm.js";
4
+ //#region src/changes.ts
5
+ const ADDED = 1;
6
+ const REMOVED = 2;
7
+ const PLACEMENT = 4;
8
+ const CAPACITY = 8;
9
+ const POSITIONS_ALL = 16;
10
+ const NORMALS_ALL = 32;
11
+ const COLORS_ALL = 64;
12
+ const INDICES_ALL = 128;
13
+ /** Decodes `[record_count, record...]`. */
14
+ function decodeChanges(msg) {
15
+ let at = 0;
16
+ const next = () => {
17
+ if (at >= msg.length) throw new Error("fast-mesh-wasm: truncated change message");
18
+ return msg[at++];
19
+ };
20
+ const ranges = (all) => {
21
+ const n = next();
22
+ const out = [];
23
+ for (let k = 0; k < n; k++) {
24
+ const start = next();
25
+ out.push([start, next()]);
26
+ }
27
+ return all ? "all" : out;
28
+ };
29
+ const ids = () => {
30
+ const n = next();
31
+ const out = [];
32
+ for (let k = 0; k < n; k++) out.push(next());
33
+ return out;
34
+ };
35
+ const count = next();
36
+ const out = [];
37
+ for (let r = 0; r < count; r++) {
38
+ const index = next();
39
+ const generation = next();
40
+ const flags = next();
41
+ out.push({
42
+ index,
43
+ generation,
44
+ added: (flags & ADDED) !== 0,
45
+ removed: (flags & REMOVED) !== 0,
46
+ placementChanged: (flags & PLACEMENT) !== 0,
47
+ capacityChanged: (flags & CAPACITY) !== 0,
48
+ positions: ranges((flags & POSITIONS_ALL) !== 0),
49
+ normals: ranges((flags & NORMALS_ALL) !== 0),
50
+ colors: ranges((flags & COLORS_ALL) !== 0),
51
+ indices: ranges((flags & INDICES_ALL) !== 0),
52
+ fields: ids(),
53
+ sections: ids()
54
+ });
55
+ }
56
+ if (at !== msg.length) throw new Error("fast-mesh-wasm: trailing words in change message");
57
+ return out;
58
+ }
59
+ //#endregion
60
+ //#region src/scene.ts
61
+ /**
62
+ * The `WasmScene` class new scenes wrap: the single-threaded glue's, unless
63
+ * the Worker entry started the threaded glue ({@link useWasmScene}).
64
+ */
65
+ let RawScene = WasmScene;
66
+ /**
67
+ * Internal (the Worker entry): makes later scenes from `ctor`, the
68
+ * `WasmScene` of the glue it initialised (the threaded one on cross-origin
69
+ * isolated pages). Pair it with `setMemory` for that glue's memory.
70
+ */
71
+ function useWasmScene(ctor) {
72
+ RawScene = ctor;
73
+ }
74
+ const meshIds = /* @__PURE__ */ new WeakMap();
75
+ const rawIds = /* @__PURE__ */ new WeakMap();
76
+ const MODES = {
77
+ eager: 0,
78
+ lazy: 1,
79
+ manual: 2
80
+ };
81
+ function modeCode(mode) {
82
+ if (!Object.hasOwn(MODES, mode)) throw invalid("mode must be \"eager\", \"lazy\" or \"manual\"");
83
+ return MODES[mode];
84
+ }
85
+ const CULLS = {
86
+ none: 0,
87
+ back: 1,
88
+ front: 2
89
+ };
90
+ const SIGNS = {
91
+ auto: 0,
92
+ pseudonormal: 1,
93
+ winding: 2
94
+ };
95
+ /** The code of a string option in `table`, or `INVALID_ARGUMENT` naming `what`. */
96
+ function codeIn(table, value, what) {
97
+ if (!Object.hasOwn(table, value)) throw invalid(`${what} must be one of ${Object.keys(table).join(", ")}`);
98
+ return table[value];
99
+ }
100
+ /** Three numbers of a flat result, from `at`. */
101
+ function vec3At(a, at) {
102
+ return [
103
+ a[at],
104
+ a[at + 1],
105
+ a[at + 2]
106
+ ];
107
+ }
108
+ function invalid(message) {
109
+ return new FastMeshError("INVALID_ARGUMENT", message);
110
+ }
111
+ const U32_LIMIT = 2 ** 32;
112
+ const EDIT_CODES = {
113
+ setPositions: 0,
114
+ addVertices: 1,
115
+ addTriangles: 2,
116
+ removeTriangles: 3,
117
+ removeVertices: 4
118
+ };
119
+ /** An id list as the binding's `n, r, ids..., (slot, op, i)...`; see `crate::edit`. */
120
+ function encodeIds(list, what, words) {
121
+ if (list instanceof Uint32Array) {
122
+ words.push([list.length, 0], list);
123
+ return;
124
+ }
125
+ if (!Array.isArray(list)) throw invalid(`${what} must be a Uint32Array or an array`);
126
+ const ids = new Array(list.length);
127
+ const refs = [];
128
+ for (let slot = 0; slot < list.length; slot++) {
129
+ const x = list[slot];
130
+ if (typeof x === "number") {
131
+ if (!Number.isInteger(x) || x < 0 || x >= U32_LIMIT) throw new FastMeshError("INVALID_INDEX", `${what}: ${x} is not an id`);
132
+ ids[slot] = x;
133
+ continue;
134
+ }
135
+ const ref = x?.ref;
136
+ if (!Array.isArray(ref) || ref.length !== 2) throw invalid(`${what} must hold ids or { ref: [opIndex, i] }`);
137
+ for (const r of ref) if (!Number.isInteger(r) || r < 0 || r >= U32_LIMIT) throw new FastMeshError("INVALID_INDEX", `${what}: ref [${ref.join(", ")}] is out of range`);
138
+ ids[slot] = 0;
139
+ refs.push(slot, ref[0], ref[1]);
140
+ }
141
+ words.push([list.length, refs.length / 3], ids, refs);
142
+ }
143
+ /** World positions of an op, checked to be `3 · count` long (any count when `count` is undefined). */
144
+ function opPositions(positions, count, what) {
145
+ const p = toFloat64(positions ?? []);
146
+ if (p.length % 3 !== 0 || count !== void 0 && p.length !== 3 * count) throw invalid(`${what}: positions need 3 values per vertex`);
147
+ return p;
148
+ }
149
+ /** An edit op list as the binding's `(ops, values)`; see `crate::edit` in the Rust crate. */
150
+ function encodeEdit(ops) {
151
+ if (!Array.isArray(ops)) throw invalid("ops must be an array");
152
+ const words = [];
153
+ const values = [];
154
+ ops.forEach((o, k) => {
155
+ const what = `op ${k}`;
156
+ const code = codeIn(EDIT_CODES, o?.op, `${what}: op`);
157
+ words.push([code]);
158
+ switch (o.op) {
159
+ case "setPositions":
160
+ encodeIds(o.vertices, `${what}: vertices`, words);
161
+ values.push(opPositions(o.positions, o.vertices?.length, what));
162
+ break;
163
+ case "addVertices": {
164
+ const p = opPositions(o.positions, void 0, what);
165
+ words.push([p.length / 3]);
166
+ values.push(p);
167
+ break;
168
+ }
169
+ case "addTriangles":
170
+ encodeIds(o.triangles, `${what}: triangles`, words);
171
+ break;
172
+ case "removeTriangles":
173
+ encodeIds(o.triangles, `${what}: triangles`, words);
174
+ break;
175
+ case "removeVertices": encodeIds(o.vertices, `${what}: vertices`, words);
176
+ }
177
+ });
178
+ const out = new Uint32Array(words.reduce((n, w) => n + w.length, 0));
179
+ let at = 0;
180
+ for (const w of words) {
181
+ out.set(w, at);
182
+ at += w.length;
183
+ }
184
+ const flat = new Float64Array(values.reduce((n, v) => n + v.length, 0));
185
+ at = 0;
186
+ for (const v of values) {
187
+ flat.set(v, at);
188
+ at += v.length;
189
+ }
190
+ return {
191
+ words: out,
192
+ values: flat
193
+ };
194
+ }
195
+ const REPAIR_CODES = {
196
+ weld: 0,
197
+ removeDegenerate: 1,
198
+ removeSmallComponents: 2,
199
+ orient: 3,
200
+ fillHoles: 4
201
+ };
202
+ /** An optional number for the binding: NaN when unset; an explicit NaN is rejected. */
203
+ function optional(v, what) {
204
+ if (v === void 0) return NaN;
205
+ if (typeof v !== "number" || Number.isNaN(v)) throw invalid(`${what} must be a number`);
206
+ return v;
207
+ }
208
+ function flagOf(v, fallback) {
209
+ return v ?? fallback ? 1 : 0;
210
+ }
211
+ /** A loop id as the binding's `minVertex, len, hash low, hash high`. */
212
+ function encodeLoopId(id, out) {
213
+ const { minVertex, len, hash } = id ?? {};
214
+ if (typeof hash !== "bigint" || hash < 0n || hash >= 1n << 64n) throw invalid("a loop id's hash must be a bigint in 0..2^64");
215
+ for (const v of [minVertex, len]) if (!Number.isInteger(v) || v < 0 || v >= U32_LIMIT) throw invalid("a loop id's minVertex and len must be u32 integers");
216
+ out.push(minVertex, len, Number(hash & 4294967295n), Number(hash >> 32n));
217
+ }
218
+ /** A repair op list as the binding's `(ops, loops)`; see `crate::edit` in the Rust crate. */
219
+ function encodeRepair(ops) {
220
+ const values = [];
221
+ const loops = [];
222
+ for (const o of ops) {
223
+ values.push(codeIn(REPAIR_CODES, o?.op, "repair op"));
224
+ switch (o.op) {
225
+ case "weld":
226
+ values.push(optional(o.tolerance, "tolerance"));
227
+ break;
228
+ case "removeDegenerate":
229
+ values.push(optional(o.areaEpsilon, "areaEpsilon"), flagOf(o.removeUnusedVertices, true));
230
+ break;
231
+ case "removeSmallComponents":
232
+ values.push(optional(o.minTriangles, "minTriangles"), optional(o.minArea, "minArea"), flagOf(o.keepLargest, true));
233
+ break;
234
+ case "orient": break;
235
+ case "fillHoles": {
236
+ let count = NaN;
237
+ if (o.loops !== void 0) {
238
+ if (!Array.isArray(o.loops)) throw invalid("loops must be an array of loop ids");
239
+ count = o.loops.length;
240
+ for (const id of o.loops) encodeLoopId(id, loops);
241
+ }
242
+ values.push(optional(o.maxEdges, "maxEdges"), optional(o.maxPerimeter, "maxPerimeter"), optional(o.maxArea, "maxArea"), count, flagOf(o.allowUnclean, false), flagOf(o.fair, true), optional(o.dpLimit, "dpLimit"));
243
+ break;
244
+ }
245
+ }
246
+ }
247
+ return {
248
+ values: Float64Array.from(values),
249
+ loops: Uint32Array.from(loops)
250
+ };
251
+ }
252
+ /** Reads a flat `f64` result front to back. */
253
+ var Reader = class {
254
+ data;
255
+ at = 0;
256
+ constructor(data) {
257
+ this.data = data;
258
+ }
259
+ next() {
260
+ return this.data[this.at++];
261
+ }
262
+ flag() {
263
+ return this.next() === 1;
264
+ }
265
+ /** `n` ids as a copy. */
266
+ ids(n) {
267
+ const out = Uint32Array.from(this.data.subarray(this.at, this.at + n));
268
+ this.at += n;
269
+ return out;
270
+ }
271
+ /** A count, then that many ids. */
272
+ list() {
273
+ return this.ids(this.next());
274
+ }
275
+ loopId() {
276
+ return {
277
+ minVertex: this.next(),
278
+ len: this.next(),
279
+ hash: BigInt(this.next()) | BigInt(this.next()) << 32n
280
+ };
281
+ }
282
+ /** A count, then that many items. */
283
+ many(item) {
284
+ const n = this.next();
285
+ const out = [];
286
+ for (let k = 0; k < n; k++) out.push(item());
287
+ return out;
288
+ }
289
+ };
290
+ const SKIP_REASONS = ["bounds", "unclean"];
291
+ const FAIL_REASONS = [
292
+ "projectionFolds",
293
+ "noValidTriangulation",
294
+ "solver"
295
+ ];
296
+ const WEIGHTS = [
297
+ null,
298
+ "cotangent",
299
+ "uniform"
300
+ ];
301
+ /** One op's report from a repair result; see `crate::edit` in the Rust crate. */
302
+ function decodeReport(op, r) {
303
+ switch (op) {
304
+ case "weld": return {
305
+ mergedVertices: r.next(),
306
+ removedTriangles: r.next()
307
+ };
308
+ case "removeDegenerate": return {
309
+ removedTriangles: r.next(),
310
+ removedVertices: r.next()
311
+ };
312
+ case "removeSmallComponents": return {
313
+ removedComponents: r.next(),
314
+ removedTriangles: r.next(),
315
+ removedVertices: r.next()
316
+ };
317
+ case "orient": return {
318
+ flippedTriangles: r.next(),
319
+ patches: r.next(),
320
+ nonOrientablePatches: r.next(),
321
+ flippedOutwardComponents: r.next()
322
+ };
323
+ case "fillHoles": return {
324
+ filled: r.many(() => ({
325
+ id: r.loopId(),
326
+ trianglesAdded: r.next(),
327
+ verticesAdded: r.next(),
328
+ converged: r.flag(),
329
+ weights: WEIGHTS[r.next()]
330
+ })),
331
+ skipped: r.many(() => ({
332
+ id: r.loopId(),
333
+ reason: SKIP_REASONS[r.next()]
334
+ })),
335
+ failed: r.many(() => ({
336
+ id: r.loopId(),
337
+ reason: FAIL_REASONS[r.next()]
338
+ }))
339
+ };
340
+ }
341
+ }
342
+ /** An analysis result; see `encode_analysis` in the Rust crate. */
343
+ function decodeAnalysis(r) {
344
+ const loops = r.many(() => ({
345
+ id: r.loopId(),
346
+ vertices: r.list(),
347
+ perimeter: r.next(),
348
+ area: r.next(),
349
+ closed: r.flag(),
350
+ clean: r.flag()
351
+ }));
352
+ const coincidentGroups = r.next();
353
+ const coincident = r.many(() => r.list());
354
+ const degenerate = r.next();
355
+ const degenerateList = r.list();
356
+ const duplicate = r.next();
357
+ const duplicateList = r.list();
358
+ const nonManifoldEdges = r.next();
359
+ const nonManifoldEdgeList = r.many(() => [r.next(), r.next()]);
360
+ const nonManifoldVertices = r.list();
361
+ const pinchVertices = r.list();
362
+ const components = r.many(() => ({
363
+ triangles: r.list(),
364
+ area: r.next(),
365
+ closed: r.flag()
366
+ }));
367
+ const orientationConflicts = r.next();
368
+ const si = r.next();
369
+ return {
370
+ loops,
371
+ coincidentGroups,
372
+ coincident,
373
+ degenerate,
374
+ degenerateList,
375
+ duplicate,
376
+ duplicateList,
377
+ nonManifoldEdges,
378
+ nonManifoldEdgeList,
379
+ nonManifoldVertices,
380
+ pinchVertices,
381
+ components,
382
+ orientationConflicts,
383
+ selfIntersects: si < 0 ? null : si === 1
384
+ };
385
+ }
386
+ function toFloat64(values) {
387
+ return values instanceof Float64Array ? values : Float64Array.from(values);
388
+ }
389
+ function toUint32(values) {
390
+ return values instanceof Uint32Array ? values : Uint32Array.from(values);
391
+ }
392
+ /** Set by `Scene`'s static block. */
393
+ let fieldStepsOf;
394
+ /** @internal The stepped field updates of `scene` (see {@link FieldSteps}); for the Worker engine. */
395
+ function fieldSteps(scene) {
396
+ return fieldStepsOf(scene);
397
+ }
398
+ /** Set by `Scene`'s static block. */
399
+ let meshAddsOf;
400
+ /** @internal The stepped mesh adds of `scene` (see {@link MeshAdds}); for the Worker engine. */
401
+ function meshAdds(scene) {
402
+ return meshAddsOf(scene);
403
+ }
404
+ /**
405
+ * A scene of editable meshes. Create it after `await init()`; release it with
406
+ * {@link Scene.free} or a `using` declaration (otherwise it is freed when
407
+ * garbage collected).
408
+ *
409
+ * Render views ({@link Scene.views}) point into WebAssembly memory and are
410
+ * only valid until the next scene call that may allocate or move buffers: a
411
+ * kept view may read other data or be empty. Re-acquire them after every
412
+ * scene call; see {@link MeshViews}.
413
+ */
414
+ var Scene = class {
415
+ #raw;
416
+ #guard;
417
+ /** Live meshes' handles by `"index:generation"`. */
418
+ #meshes = /* @__PURE__ */ new Map();
419
+ /** Handles of meshes removed since the last `takeChanges`, for their removal records. */
420
+ #removed = /* @__PURE__ */ new Map();
421
+ /** The rule each coloured mesh was last given by `setColoring`. */
422
+ #rules = /* @__PURE__ */ new WeakMap();
423
+ /**
424
+ * Field and section handles by raw id, kept for the scene's lifetime (raw
425
+ * ids are never reused), so change records reporting a removed field or
426
+ * section give back the handle the caller holds.
427
+ */
428
+ #fields = /* @__PURE__ */ new Map();
429
+ #sections = /* @__PURE__ */ new Map();
430
+ #listeners = /* @__PURE__ */ new Set();
431
+ /** History step nesting depth, mirrored from the calls made through this class. */
432
+ #stepDepth = 0;
433
+ #drag;
434
+ constructor(options = {}) {
435
+ ensureInitialized("new Scene()");
436
+ this.#raw = call(() => new RawScene());
437
+ this.#guard = options.debug ? new ViewGuard() : void 0;
438
+ finalizer.register(this, this.#raw, this);
439
+ }
440
+ /** Releases the scene and everything in it. Later calls throw `INVALID_ARGUMENT`; calling it again does nothing. */
441
+ free() {
442
+ const raw = this.#raw;
443
+ if (raw === void 0) return;
444
+ this.#raw = void 0;
445
+ this.#guard?.bump();
446
+ this.#drag = void 0;
447
+ finalizer.unregister(this);
448
+ release(raw);
449
+ }
450
+ /** Same as {@link Scene.free}, for `using scene = new Scene()`. */
451
+ [Symbol.dispose]() {
452
+ this.free();
453
+ }
454
+ /** The live raw scene, for a call that may allocate or move buffers. */
455
+ #scene() {
456
+ const s = this.#peek();
457
+ this.#guard?.bump();
458
+ return s;
459
+ }
460
+ /** The live raw scene, for a read-only call that leaves every view valid. */
461
+ #peek() {
462
+ if (this.#raw === void 0) throw invalid("scene is freed");
463
+ return this.#raw;
464
+ }
465
+ /** The live mesh id of a handle of this scene. */
466
+ #id(mesh) {
467
+ this.#peek();
468
+ const id = meshIds.get(mesh);
469
+ if (id === void 0) throw invalid("not a mesh handle");
470
+ if (id.scene !== this) throw invalid("mesh handle belongs to another scene");
471
+ return id;
472
+ }
473
+ #meshHandle(index, generation) {
474
+ const key = `${index}:${generation}`;
475
+ let h = this.#meshes.get(key) ?? this.#removed.get(key);
476
+ if (h === void 0) {
477
+ h = new MeshHandle();
478
+ meshIds.set(h, {
479
+ scene: this,
480
+ index,
481
+ generation
482
+ });
483
+ this.#meshes.set(key, h);
484
+ }
485
+ return h;
486
+ }
487
+ #rawHandle(map, make, raw) {
488
+ let h = map.get(raw);
489
+ if (h === void 0) {
490
+ h = make();
491
+ rawIds.set(h, {
492
+ scene: this,
493
+ index: raw,
494
+ generation: 0
495
+ });
496
+ map.set(raw, h);
497
+ }
498
+ return h;
499
+ }
500
+ /** The raw id of a field or section handle of this scene. */
501
+ #rawId(handle, kind) {
502
+ this.#peek();
503
+ const what = kind === FieldHandle ? "field" : "section";
504
+ const id = handle instanceof kind ? rawIds.get(handle) : void 0;
505
+ if (id === void 0) throw invalid(`not a ${what} handle`);
506
+ if (id.scene !== this) throw invalid(`${what} handle belongs to another scene`);
507
+ return id.index;
508
+ }
509
+ #field(field) {
510
+ return this.#rawId(field, FieldHandle);
511
+ }
512
+ #section(section) {
513
+ return this.#rawId(section, SectionHandle);
514
+ }
515
+ /** Meshes as the binding's flat `[index, generation, ...]` list. */
516
+ #flatIds(meshes) {
517
+ if (!Array.isArray(meshes)) throw invalid("meshes must be an array of mesh handles");
518
+ const out = new Uint32Array(meshes.length * 2);
519
+ meshes.forEach((m, k) => {
520
+ const { index, generation } = this.#id(m);
521
+ out[2 * k] = index;
522
+ out[2 * k + 1] = generation;
523
+ });
524
+ return out;
525
+ }
526
+ /** `[origin, normal]` as the binding's 6 numbers. */
527
+ #plane(plane) {
528
+ if (plane?.origin?.length !== 3 || plane.normal?.length !== 3) throw invalid("plane needs a 3-number origin and normal");
529
+ return Float64Array.from([...plane.origin, ...plane.normal]);
530
+ }
531
+ /**
532
+ * Adds a mesh from world positions. They are stored as `p − origin` in
533
+ * `f32` (see {@link AddMeshOptions.origin}); the placement starts as the
534
+ * identity, so {@link Scene.matrix4} maps the local coordinates back to
535
+ * where they were given.
536
+ *
537
+ * @throws `INVALID_ARGUMENT` for bad lengths or options, `INVALID_INDEX` for an index out of range.
538
+ */
539
+ addMesh(positions, indices, options = {}) {
540
+ const s = this.#scene();
541
+ const mode = modeCode(options.mode ?? "eager");
542
+ const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
543
+ const p = toFloat64(positions);
544
+ const i = toUint32(indices);
545
+ const id = call(() => s.add_mesh(p, i, origin, mode, options.normals ?? true));
546
+ return this.#meshHandle(id[0], id[1]);
547
+ }
548
+ /**
549
+ * Removes a mesh. Its handle then gives `UNKNOWN_MESH`. An active drag of
550
+ * the mesh is ended first, closing its step; the mesh's history entries
551
+ * (the drag's included) are then dropped with it.
552
+ */
553
+ removeMesh(mesh) {
554
+ const { index, generation } = this.#id(mesh);
555
+ if (this.#drag?.mesh === mesh) this.#drag.end();
556
+ call(() => this.#scene().remove_mesh(index, generation));
557
+ const key = `${index}:${generation}`;
558
+ this.#meshes.delete(key);
559
+ this.#removed.set(key, mesh);
560
+ }
561
+ /**
562
+ * Sets a mesh's placement: world = rotation · local + translation, where
563
+ * local is relative to the mesh origin. A quaternion is normalised and
564
+ * converted in double precision.
565
+ *
566
+ * @throws `INVALID_ARGUMENT` when the rotation is not a proper rotation or a quaternion is zero.
567
+ */
568
+ setPlacement(mesh, placement) {
569
+ const { index, generation } = this.#id(mesh);
570
+ const r = Float64Array.from(rotationMatrix(placement.rotation));
571
+ const t = Float64Array.from(placement.translation);
572
+ call(() => this.#scene().set_placement(index, generation, r, t));
573
+ }
574
+ /** A mesh's placement, with the rotation as a row-major matrix. */
575
+ placement(mesh) {
576
+ const { index, generation } = this.#id(mesh);
577
+ const p = call(() => this.#peek().placement(index, generation));
578
+ return {
579
+ rotation: Array.from(p.subarray(0, 9)),
580
+ translation: [
581
+ p[9],
582
+ p[10],
583
+ p[11]
584
+ ]
585
+ };
586
+ }
587
+ /**
588
+ * The column-major world matrix of the local render coordinates,
589
+ * `placement · translate(origin)`, ready for renderers (convert to `f32`
590
+ * yourself).
591
+ */
592
+ matrix4(mesh) {
593
+ const { index, generation } = this.#id(mesh);
594
+ return call(() => this.#peek().matrix4(index, generation));
595
+ }
596
+ /** Sets when the mesh's derived data follows its edits; see {@link UpdateMode}. */
597
+ setMode(mesh, mode) {
598
+ const { index, generation } = this.#id(mesh);
599
+ const m = modeCode(mode);
600
+ call(() => this.#scene().set_mode(index, generation, m));
601
+ }
602
+ /** Brings the mesh's derived data up to date now, whatever its mode. */
603
+ update(mesh) {
604
+ const { index, generation } = this.#id(mesh);
605
+ call(() => this.#scene().update(index, generation));
606
+ }
607
+ /** Brings every mesh that is not `"manual"` up to date. */
608
+ flush() {
609
+ const s = this.#scene();
610
+ call(() => s.flush());
611
+ }
612
+ /** Vertex slots, alive or dead: the vertex length of the render buffers. */
613
+ vertexSlots(mesh) {
614
+ const { index, generation } = this.#id(mesh);
615
+ return call(() => this.#peek().vertex_slots(index, generation));
616
+ }
617
+ /** Triangle slots, alive or dead: the triangle length of the index buffer. */
618
+ triangleSlots(mesh) {
619
+ const { index, generation } = this.#id(mesh);
620
+ return call(() => this.#peek().triangle_slots(index, generation));
621
+ }
622
+ /** Alive vertices. */
623
+ vertexCount(mesh) {
624
+ const { index, generation } = this.#id(mesh);
625
+ return call(() => this.#peek().vertex_count(index, generation));
626
+ }
627
+ /** Alive triangles. */
628
+ triangleCount(mesh) {
629
+ const { index, generation } = this.#id(mesh);
630
+ return call(() => this.#peek().triangle_count(index, generation));
631
+ }
632
+ /**
633
+ * Zero-copy views of the mesh's render buffers. Each getter builds a fresh
634
+ * view; re-acquire views after every scene call that may allocate, since a
635
+ * kept one may read other data or be empty (see {@link MeshViews}).
636
+ */
637
+ views(mesh) {
638
+ const { index, generation } = this.#id(mesh);
639
+ call(() => this.#peek().vertex_slots(index, generation));
640
+ return meshViews(() => this.#peek(), index, generation, this.#guard);
641
+ }
642
+ /**
643
+ * Everything that changed since the previous call, one record per mesh.
644
+ * There is a single consumer: apps that use {@link Scene.onChanges} call
645
+ * {@link Scene.commitFrame} instead.
646
+ */
647
+ takeChanges() {
648
+ const s = this.#scene();
649
+ const raw = decodeChanges(call(() => s.take_changes()));
650
+ const out = raw.map((c) => ({
651
+ mesh: this.#meshHandle(c.index, c.generation),
652
+ added: c.added,
653
+ removed: c.removed,
654
+ placementChanged: c.placementChanged,
655
+ capacityChanged: c.capacityChanged,
656
+ positions: c.positions,
657
+ normals: c.normals,
658
+ colors: c.colors,
659
+ indices: c.indices,
660
+ fieldsChanged: c.fields.map((f) => this.#rawHandle(this.#fields, () => new FieldHandle(), f)),
661
+ sectionsChanged: c.sections.map((x) => this.#rawHandle(this.#sections, () => new SectionHandle(), x))
662
+ }));
663
+ for (const c of raw) if (c.removed) this.#meshes.delete(`${c.index}:${c.generation}`);
664
+ this.#removed.clear();
665
+ return out;
666
+ }
667
+ /**
668
+ * Registers a listener for {@link Scene.commitFrame}. Returns a function
669
+ * that unregisters it.
670
+ */
671
+ onChanges(listener) {
672
+ this.#scene();
673
+ this.#listeners.add(listener);
674
+ return () => {
675
+ this.#listeners.delete(listener);
676
+ };
677
+ }
678
+ /**
679
+ * Takes the changes once and delivers the same array to every listener,
680
+ * then returns it. Call it once per animation frame. Every listener runs
681
+ * even if one throws; the first error is rethrown afterwards.
682
+ */
683
+ commitFrame() {
684
+ const changes = this.takeChanges();
685
+ let failure;
686
+ for (const listener of [...this.#listeners]) try {
687
+ listener(changes);
688
+ } catch (error) {
689
+ failure ??= { error };
690
+ }
691
+ if (failure !== void 0) throw failure.error;
692
+ return changes;
693
+ }
694
+ /**
695
+ * Undoes the latest step; an active drag is ended first. Without an open
696
+ * step around the drag, the drag is what gets undone; inside a caller's
697
+ * open step, that whole step (drag included) is closed and undone. Returns
698
+ * `false` when there is nothing to undo.
699
+ */
700
+ undo() {
701
+ const s = this.#scene();
702
+ this.#drag?.end();
703
+ const done = call(() => s.undo());
704
+ this.#stepDepth = 0;
705
+ return done;
706
+ }
707
+ /** Redoes the latest undone step. Returns `false` when there is nothing to redo. */
708
+ redo() {
709
+ const s = this.#scene();
710
+ this.#drag?.end();
711
+ const done = call(() => s.redo());
712
+ this.#stepDepth = 0;
713
+ return done;
714
+ }
715
+ /** True if {@link Scene.undo} would undo something. */
716
+ canUndo() {
717
+ const s = this.#peek();
718
+ return call(() => s.can_undo());
719
+ }
720
+ /** True if {@link Scene.redo} would redo something. */
721
+ canRedo() {
722
+ const s = this.#peek();
723
+ return call(() => s.can_redo());
724
+ }
725
+ /** Closes an open step, then drops every undo and redo step. */
726
+ clearHistory() {
727
+ const s = this.#scene();
728
+ this.#drag?.end();
729
+ call(() => s.clear_history());
730
+ this.#stepDepth = 0;
731
+ }
732
+ /**
733
+ * Opens a history step, or one more nesting level of the open one. Edits
734
+ * and placement changes until the matching {@link Scene.endStep} are
735
+ * undone together.
736
+ */
737
+ beginStep() {
738
+ const s = this.#scene();
739
+ call(() => s.begin_step());
740
+ this.#stepDepth++;
741
+ }
742
+ /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
743
+ endStep() {
744
+ const s = this.#scene();
745
+ call(() => s.end_step());
746
+ this.#stepDepth--;
747
+ if (this.#drag !== void 0 && this.#stepDepth < this.#drag.depth) this.#drag.abandon();
748
+ }
749
+ /** Reverts and discards the open step, however deeply nested. Throws `STEP_NOT_OPEN` when none is open. */
750
+ cancelStep() {
751
+ const s = this.#scene();
752
+ call(() => s.cancel_step());
753
+ this.#stepDepth = 0;
754
+ this.#drag?.abandon();
755
+ }
756
+ /**
757
+ * Starts dragging a mesh: the moves until {@link DragSession.end} form one
758
+ * undo step (nested in the open step, if there is one). One drag at a time.
759
+ * Every {@link DragSession.move} recomputes the eager fields, so make at most
760
+ * one move per animation frame, with the latest pointer pose.
761
+ */
762
+ drag(mesh) {
763
+ this.#id(mesh);
764
+ if (this.#drag !== void 0) throw invalid("a drag is already active; end or cancel it first");
765
+ const start = this.placement(mesh);
766
+ const outermost = this.#stepDepth === 0;
767
+ this.beginStep();
768
+ const depth = this.#stepDepth;
769
+ let active = true;
770
+ const finish = () => {
771
+ if (!active) return false;
772
+ active = false;
773
+ this.#drag = void 0;
774
+ return true;
775
+ };
776
+ const close = () => {
777
+ while (this.#stepDepth >= depth) this.endStep();
778
+ };
779
+ const session = {
780
+ depth,
781
+ mesh,
782
+ get active() {
783
+ return active;
784
+ },
785
+ move: (placement) => {
786
+ if (!active) throw invalid("the drag is over");
787
+ this.setPlacement(mesh, placement);
788
+ },
789
+ end: () => {
790
+ if (finish()) close();
791
+ },
792
+ cancel: () => {
793
+ if (!finish()) return;
794
+ if (outermost) {
795
+ this.cancelStep();
796
+ return;
797
+ }
798
+ try {
799
+ this.setPlacement(mesh, start);
800
+ } finally {
801
+ close();
802
+ }
803
+ },
804
+ abandon: () => {
805
+ finish();
806
+ }
807
+ };
808
+ this.#drag = session;
809
+ return session;
810
+ }
811
+ /**
812
+ * Edits a mesh's geometry with a list of ops, run in Rust as one
813
+ * transaction: one undo step (or part of the open step), and when any op
814
+ * fails nothing changes and nothing is recorded. Positions are world
815
+ * coordinates, mapped to local with the mesh's placement and origin. Ids
816
+ * may be {@link EditRef}s to ids added by earlier ops of the list; every
817
+ * ref is checked before anything is written. Normals, colours, fields,
818
+ * sections and the BVH follow by the mesh's mode.
819
+ *
820
+ * @throws `INVALID_INDEX` for a bad ref or an id that is not alive;
821
+ * `INVALID_ARGUMENT` for a malformed op, positions not 3 per vertex or not
822
+ * finite in local `f32`, or removing a vertex still in use.
823
+ */
824
+ edit(mesh, ops) {
825
+ const { index, generation } = this.#id(mesh);
826
+ const { words, values } = encodeEdit(ops);
827
+ const out = call(() => this.#scene().edit(index, generation, words, values));
828
+ const added = [];
829
+ let at = 0;
830
+ while (at < out.length) {
831
+ const n = out[at];
832
+ added.push(out.slice(at + 1, at + 1 + n));
833
+ at += 1 + n;
834
+ }
835
+ return { added };
836
+ }
837
+ /**
838
+ * Removes the mesh's dead slots and renumbers the rest. Its next change
839
+ * record has every buffer `"all"` and `capacityChanged` when the slot counts
840
+ * shrank. The mesh's earlier edits leave the history (its placement changes
841
+ * stay undoable).
842
+ */
843
+ compact(mesh) {
844
+ const { index, generation } = this.#id(mesh);
845
+ call(() => this.#scene().compact(index, generation));
846
+ }
847
+ /**
848
+ * A read-only report of the mesh's defects: boundary loops (whose ids
849
+ * `fillHoles` takes), coincident vertices, degenerate and duplicate
850
+ * triangles, non-manifold edges and vertices, components, orientation
851
+ * conflicts and, on request, self-intersection.
852
+ *
853
+ * @throws `INVALID_ARGUMENT` for a negative or non-finite `weldTolerance`; `STALE_BVH`, see {@link AnalyzeOptions.selfIntersection}.
854
+ */
855
+ analyze(mesh, options = {}) {
856
+ const { index, generation } = this.#id(mesh);
857
+ const maxListed = options.maxListed ?? 1e3;
858
+ if (!Number.isInteger(maxListed) || maxListed < 0 || maxListed >= U32_LIMIT) throw invalid("maxListed must be a non-negative integer");
859
+ const tolerance = options.weldTolerance ?? 0;
860
+ const si = options.selfIntersection ?? false;
861
+ return decodeAnalysis(new Reader(call(() => this.#scene().analyze(index, generation, tolerance, si, maxListed))));
862
+ }
863
+ repair(mesh, op) {
864
+ const { index, generation } = this.#id(mesh);
865
+ const ops = Array.isArray(op) ? op : [op];
866
+ const { values, loops } = encodeRepair(ops);
867
+ const r = new Reader(call(() => this.#scene().repair(index, generation, values, loops)));
868
+ const reports = ops.map((o) => decodeReport(o.op, r));
869
+ return Array.isArray(op) ? reports : reports[0];
870
+ }
871
+ /**
872
+ * The nearest hit of a world ray over every mesh, or `null`. `direction`
873
+ * need not be unit length; `distance` is in world units. Lazy meshes are
874
+ * brought up to date first.
875
+ *
876
+ * @throws `INVALID_ARGUMENT` for a non-finite origin or a zero direction; `STALE_BVH` for a stale `"manual"` mesh.
877
+ */
878
+ raycast(origin, direction, options = {}) {
879
+ const s = this.#scene();
880
+ const o = Float64Array.from(origin);
881
+ const d = Float64Array.from(direction);
882
+ const cull = codeIn(CULLS, options.cull ?? "none", "cull");
883
+ const min = options.minDistance ?? 0;
884
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
885
+ const h = call(() => s.raycast(o, d, min, max, cull));
886
+ if (h.length === 0) return null;
887
+ return {
888
+ mesh: this.#meshHandle(h[0], h[1]),
889
+ triangle: h[2],
890
+ point: vec3At(h, 3),
891
+ distance: h[6],
892
+ barycentric: vec3At(h, 7)
893
+ };
894
+ }
895
+ /**
896
+ * The surface point nearest to a world point, over every mesh or one, or
897
+ * `null` when none is within `maxDistance`.
898
+ */
899
+ closestPoint(point, options = {}) {
900
+ const s = this.#scene();
901
+ const p = Float64Array.from(point);
902
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
903
+ let h;
904
+ if (options.mesh === void 0) h = call(() => s.closest_point(p, max));
905
+ else {
906
+ const { index, generation } = this.#id(options.mesh);
907
+ h = call(() => s.closest_point_on(index, generation, p, max));
908
+ }
909
+ if (h.length === 0) return null;
910
+ return {
911
+ mesh: this.#meshHandle(h[0], h[1]),
912
+ triangle: h[2],
913
+ point: vec3At(h, 3),
914
+ distance: h[6]
915
+ };
916
+ }
917
+ /**
918
+ * The distance between two meshes' surfaces as placed, with a closest pair
919
+ * of points, or `null` when it exceeds `maxDistance` (default `Infinity`)
920
+ * or a mesh has no triangle.
921
+ */
922
+ meshDistance(a, b, options = {}) {
923
+ const ia = this.#id(a);
924
+ const ib = this.#id(b);
925
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
926
+ const d = call(() => this.#scene().mesh_distance(ia.index, ia.generation, ib.index, ib.generation, max));
927
+ if (d.length === 0) return null;
928
+ return {
929
+ distance: d[0],
930
+ a: vec3At(d, 1),
931
+ b: vec3At(d, 4),
932
+ triangleA: d[7],
933
+ triangleB: d[8]
934
+ };
935
+ }
936
+ /** Whether two meshes intersect or touch as placed. */
937
+ intersects(a, b) {
938
+ const ia = this.#id(a);
939
+ const ib = this.#id(b);
940
+ return call(() => this.#scene().intersects(ia.index, ia.generation, ib.index, ib.generation));
941
+ }
942
+ /** Every mesh pair (or every pair of `pairs`) within `margin`, sorted by mesh id. */
943
+ findContacts(options = {}) {
944
+ const s = this.#scene();
945
+ const pairs = options.pairs === void 0 ? void 0 : this.#flatIds(options.pairs.flat());
946
+ const msg = call(() => s.find_contacts(options.margin ?? 0, pairs));
947
+ const out = [];
948
+ let at = 1;
949
+ for (let k = 0; k < msg[0]; k++) {
950
+ const na = msg[at + 6];
951
+ const nb = msg[at + 7];
952
+ const start = at + 8;
953
+ out.push({
954
+ a: this.#meshHandle(msg[at], msg[at + 1]),
955
+ b: this.#meshHandle(msg[at + 2], msg[at + 3]),
956
+ intersecting: msg[at + 4] === 1,
957
+ distance: msg[at + 5],
958
+ trianglesA: Uint32Array.from(msg.subarray(start, start + na)),
959
+ trianglesB: Uint32Array.from(msg.subarray(start + na, start + na + nb))
960
+ });
961
+ at = start + na + nb;
962
+ }
963
+ return out;
964
+ }
965
+ /**
966
+ * Adds a signed distance field: one value per vertex slot of `on`, the
967
+ * distance to `to` as placed (negative inside), `Infinity` beyond
968
+ * `maxDistance`, NaN for dead or unused vertices. With several meshes in
969
+ * `to`, the smallest over them, ties going to the earliest. It follows
970
+ * edits and placements by the mesh modes, like normals. Removing a mesh of
971
+ * `to` removes it from the field, or the field with its last target.
972
+ *
973
+ * @throws `INVALID_ARGUMENT` when `to` is empty, holds `on` or a mesh twice, `maxDistance` is negative or NaN, or the name is taken.
974
+ */
975
+ addDistanceField(desc) {
976
+ return this.#addField(desc, false);
977
+ }
978
+ /** `addDistanceField`, or with `deferred` its internal variant that computes nothing yet. */
979
+ #addField(desc, deferred) {
980
+ const s = this.#scene();
981
+ const ids = this.#flatIds([desc.on, ...targetsOf(desc.to)]);
982
+ const sign = codeIn(SIGNS, desc.sign ?? "auto", "sign");
983
+ if (typeof desc.name !== "string") throw invalid("name must be a string");
984
+ const raw = call(() => deferred ? s.add_distance_field_deferred(desc.name, ids, desc.maxDistance, sign) : s.add_distance_field(desc.name, ids, desc.maxDistance, sign));
985
+ return this.#rawHandle(this.#fields, () => new FieldHandle(), raw);
986
+ }
987
+ /** Removes a field, and a colouring by it. Its handle then gives `UNKNOWN_FIELD`. */
988
+ removeField(field) {
989
+ const raw = this.#field(field);
990
+ call(() => this.#scene().remove_field(raw));
991
+ }
992
+ /**
993
+ * A zero-copy view of the field's values as of its last update, one per
994
+ * vertex slot. Like render views, it is only valid until the next call
995
+ * that may allocate (a kept one may read other data or be empty): get it
996
+ * right before use.
997
+ */
998
+ fieldValues(field) {
999
+ const raw = this.#field(field);
1000
+ const s = this.#peek();
1001
+ const ptr = call(() => s.field_values_ptr(raw));
1002
+ const view = new Float32Array(wasmMemory().buffer, ptr, call(() => s.field_values_len(raw)));
1003
+ return this.#guard === void 0 ? view : this.#guard.wrap(view);
1004
+ }
1005
+ /**
1006
+ * Per vertex slot, the index in {@link Scene.fieldTargets} of the target
1007
+ * the field's value came from, or `0xffffffff` for none (`Infinity` or
1008
+ * NaN). A copy, as of the field's last update.
1009
+ */
1010
+ fieldNearest(field) {
1011
+ const raw = this.#field(field);
1012
+ return call(() => this.#peek().field_nearest(raw));
1013
+ }
1014
+ /** The field's target meshes, in index order (a removed target leaves the list). */
1015
+ fieldTargets(field) {
1016
+ const raw = this.#field(field);
1017
+ const flat = call(() => this.#peek().field_targets(raw));
1018
+ const out = [];
1019
+ for (let i = 0; i < flat.length; i += 2) out.push(this.#meshHandle(flat[i], flat[i + 1]));
1020
+ return out;
1021
+ }
1022
+ /**
1023
+ * What the sign data found out about each of the field's targets, in the
1024
+ * order of {@link Scene.fieldTargets}.
1025
+ */
1026
+ fieldTargetStatus(field) {
1027
+ const raw = this.#field(field);
1028
+ const st = call(() => this.#peek().field_target_status(raw));
1029
+ const out = [];
1030
+ for (let i = 0; i < st.length; i += 5) out.push({
1031
+ mode: st[i] === 2 ? "winding" : "pseudonormal",
1032
+ closed: st[i + 1] === 1,
1033
+ consistentOrientation: st[i + 2] === 1,
1034
+ nonManifoldVertices: st[i + 3],
1035
+ degenerateTriangles: st[i + 4]
1036
+ });
1037
+ return out;
1038
+ }
1039
+ /**
1040
+ * Whether the field is current, and what its sign data found out about the
1041
+ * target meshes, together (see {@link FieldStatus.sign}).
1042
+ */
1043
+ fieldStatus(field) {
1044
+ const raw = this.#field(field);
1045
+ const st = call(() => this.#peek().field_status(raw));
1046
+ return {
1047
+ current: st[0] === 1,
1048
+ sign: {
1049
+ mode: st[1] === 2 ? "winding" : "pseudonormal",
1050
+ closed: st[2] === 1,
1051
+ consistentOrientation: st[3] === 1,
1052
+ nonManifoldVertices: st[4],
1053
+ degenerateTriangles: st[5]
1054
+ }
1055
+ };
1056
+ }
1057
+ /**
1058
+ * Colours a mesh from one of its fields (`views(mesh).colors()`), or turns
1059
+ * colouring off with `null`, after which `colors()` returns `null`. Every
1060
+ * vertex is recoloured and reported as `"all"`; later field updates (edits,
1061
+ * drags) report only the vertices whose colour may change. A display
1062
+ * setting: never recorded in history.
1063
+ *
1064
+ * @throws `INVALID_ARGUMENT` when the field is not on `mesh` or the rule is invalid; `UNKNOWN_FIELD`.
1065
+ */
1066
+ setColoring(mesh, rule) {
1067
+ const { index, generation } = this.#id(mesh);
1068
+ if (rule === null) {
1069
+ call(() => this.#scene().clear_coloring(index, generation));
1070
+ this.#rules.delete(mesh);
1071
+ return;
1072
+ }
1073
+ const field = this.#field(rule.field);
1074
+ const { map, values } = encodeRule(rule);
1075
+ call(() => this.#scene().set_coloring(index, generation, field, map, values));
1076
+ this.#rules.set(mesh, copyRule(rule));
1077
+ }
1078
+ /**
1079
+ * The rule the mesh is coloured by (a frozen copy of the one given to
1080
+ * {@link Scene.setColoring}, the same object on every read), or `null`
1081
+ * without colouring (never set, turned off, or its field removed).
1082
+ *
1083
+ * @throws `UNKNOWN_MESH`.
1084
+ */
1085
+ coloring(mesh) {
1086
+ const { index, generation } = this.#id(mesh);
1087
+ return call(() => this.#peek().values_ptr(index, generation)) !== 0 ? this.#rules.get(mesh) ?? null : null;
1088
+ }
1089
+ static {
1090
+ meshAddsOf = (scene) => ({
1091
+ begin: (positions, indices, options = {}) => {
1092
+ const s = scene.#scene();
1093
+ const mode = modeCode(options.mode ?? "eager");
1094
+ const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
1095
+ const p = toFloat64(positions);
1096
+ const i = toUint32(indices);
1097
+ return call(() => s.begin_add_mesh(p, i, origin, mode, options.normals ?? true));
1098
+ },
1099
+ step: (token, budget) => call(() => scene.#scene().add_mesh_step(token, budget)),
1100
+ finish: (token) => {
1101
+ const id = call(() => scene.#scene().finish_add_mesh(token));
1102
+ return scene.#meshHandle(id[0], id[1]);
1103
+ },
1104
+ drop: (token) => call(() => scene.#peek().drop_add_mesh(token))
1105
+ });
1106
+ }
1107
+ static {
1108
+ fieldStepsOf = (scene) => ({
1109
+ setDefer: (on) => call(() => scene.#peek().set_defer_fields(on)),
1110
+ step: (points) => {
1111
+ const s = scene.#scene();
1112
+ const state = call(() => s.field_step(points));
1113
+ return state === 0 ? "idle" : state === 1 ? "pending" : "done";
1114
+ },
1115
+ addDeferred: (desc) => scene.#addField(desc, true),
1116
+ stepField: (field, points) => {
1117
+ const raw = scene.#field(field);
1118
+ const s = scene.#scene();
1119
+ const state = call(() => s.field_step_field(raw, points));
1120
+ return state === 0 ? "idle" : state === 1 ? "pending" : "done";
1121
+ },
1122
+ withdraw: (field) => {
1123
+ const raw = scene.#field(field);
1124
+ return call(() => scene.#scene().withdraw_field(raw));
1125
+ },
1126
+ abandon: () => call(() => scene.#peek().abandon_field_step()),
1127
+ meshes: () => {
1128
+ const flat = call(() => scene.#peek().field_step_meshes());
1129
+ const out = [];
1130
+ for (let k = 0; k < flat.length; k += 2) out.push(scene.#meshHandle(flat[k], flat[k + 1]));
1131
+ return out;
1132
+ }
1133
+ });
1134
+ }
1135
+ /**
1136
+ * Adds a plane section of `meshes`. Results of `"eager"` meshes are computed
1137
+ * right away; others on {@link Scene.updateSections} or `flush()`.
1138
+ *
1139
+ * @throws `INVALID_ARGUMENT` for a zero normal or a mesh listed twice.
1140
+ */
1141
+ addSection(desc) {
1142
+ const s = this.#scene();
1143
+ const plane = this.#plane(desc.plane);
1144
+ const meshes = this.#flatIds(desc.meshes);
1145
+ const raw = call(() => s.add_section(plane, meshes, desc.fill ?? false));
1146
+ return this.#rawHandle(this.#sections, () => new SectionHandle(), raw);
1147
+ }
1148
+ /** Moves a section's plane. */
1149
+ setSectionPlane(section, plane) {
1150
+ const raw = this.#section(section);
1151
+ const p = this.#plane(plane);
1152
+ call(() => this.#scene().set_section_plane(raw, p));
1153
+ }
1154
+ /**
1155
+ * A section's plane as last set by {@link Scene.addSection} or
1156
+ * {@link Scene.setSectionPlane}, the normal normalised. Results not yet
1157
+ * recomputed (`"stale"`) may still be cut with an earlier plane.
1158
+ */
1159
+ sectionPlane(section) {
1160
+ const raw = this.#section(section);
1161
+ const p = call(() => this.#peek().section_desc_plane(raw));
1162
+ return {
1163
+ origin: vec3At(p, 0),
1164
+ normal: vec3At(p, 3)
1165
+ };
1166
+ }
1167
+ /** Changes the meshes a section cuts. */
1168
+ setSectionMeshes(section, meshes) {
1169
+ const raw = this.#section(section);
1170
+ const ids = this.#flatIds(meshes);
1171
+ call(() => this.#scene().set_section_meshes(raw, ids));
1172
+ }
1173
+ /** Turns a section's fill on or off. */
1174
+ setSectionFill(section, fill) {
1175
+ const raw = this.#section(section);
1176
+ call(() => this.#scene().set_section_fill(raw, fill));
1177
+ }
1178
+ /** Removes a section. Its handle then gives `UNKNOWN_SECTION`. */
1179
+ removeSection(section) {
1180
+ const raw = this.#section(section);
1181
+ call(() => this.#scene().remove_section(raw));
1182
+ }
1183
+ /** Computes every stale section result, whatever the mesh modes. */
1184
+ updateSections() {
1185
+ const s = this.#scene();
1186
+ call(() => s.update_sections());
1187
+ }
1188
+ /**
1189
+ * A section's result for one of its meshes as of its last computation
1190
+ * (empty before the first), copied, in world coordinates.
1191
+ *
1192
+ * @throws `INVALID_ARGUMENT` when the section does not cut `mesh`.
1193
+ */
1194
+ section(section, mesh) {
1195
+ const raw = this.#section(section);
1196
+ const { index, generation } = this.#id(mesh);
1197
+ const r = call(() => this.#peek().section(raw, index, generation));
1198
+ const contours = [];
1199
+ let at = 4;
1200
+ for (let k = 0; k < r[3]; k++) {
1201
+ const n = 3 * r[at + 1];
1202
+ contours.push({
1203
+ closed: r[at] === 1,
1204
+ points: Float32Array.from(r.subarray(at + 2, at + 2 + n))
1205
+ });
1206
+ at += 2 + n;
1207
+ }
1208
+ const result = {
1209
+ status: r[0] === 0 ? "current" : "stale",
1210
+ contours,
1211
+ length: r[1],
1212
+ area: r[2]
1213
+ };
1214
+ if (r[at] === 1) {
1215
+ const np = 3 * r[at + 1];
1216
+ const positions = Float32Array.from(r.subarray(at + 2, at + 2 + np));
1217
+ at += 2 + np;
1218
+ result.fill = {
1219
+ positions,
1220
+ indices: Uint32Array.from(r.subarray(at + 1, at + 1 + 3 * r[at]))
1221
+ };
1222
+ }
1223
+ return result;
1224
+ }
1225
+ /**
1226
+ * The closest pair between two meshes' contours in a section, measured in
1227
+ * the plane, or `null` when either has none or their results were cut with
1228
+ * different planes (call {@link Scene.updateSections} first).
1229
+ */
1230
+ sectionGap(section, a, b) {
1231
+ const raw = this.#section(section);
1232
+ const ia = this.#id(a);
1233
+ const ib = this.#id(b);
1234
+ const g = call(() => this.#scene().section_gap(raw, ia.index, ia.generation, ib.index, ib.generation));
1235
+ return g.length === 0 ? null : {
1236
+ distance: g[0],
1237
+ a: vec3At(g, 1),
1238
+ b: vec3At(g, 4)
1239
+ };
1240
+ }
1241
+ };
1242
+ //#endregion
1243
+ export { useWasmScene as i, fieldSteps as n, meshAdds as r, Scene as t };