fast-mesh-wasm 0.6.0 → 0.8.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 (51) hide show
  1. package/README.md +43 -3
  2. package/dist/client-CJWOKQMM.d.ts +664 -0
  3. package/dist/{client-BrTp2eMp.js → client-DQADH6KL.js} +1893 -109
  4. package/dist/{engine-DjdY3GxK.js → engine-D2124Vml.js} +995 -52
  5. package/dist/io.d.ts +205 -2
  6. package/dist/io.js +3063 -9
  7. package/dist/{mesh-DIWD2F5-.js → mesh-BtWBMRMO.js} +2 -1
  8. package/dist/{mesh-BsqIofgT.d.ts → mesh-DTm2Fnqa.d.ts} +3 -2
  9. package/dist/node.d.ts +4 -2
  10. package/dist/node.js +4 -3
  11. package/dist/primitives-6T0eQiSm.d.ts +157 -0
  12. package/dist/primitives-wasm-C30Bk4ut.js +3827 -0
  13. package/dist/primitives-wasm-d9m2vikb.d.ts +43 -0
  14. package/dist/{protocol-Ci9LLiwO.js → protocol-Bvjmvlb3.js} +38 -3
  15. package/dist/protocol-Da0kmXuF.d.ts +743 -0
  16. package/dist/r3f.d.ts +3 -3
  17. package/dist/r3f.js +3 -3
  18. package/dist/{react-DzrtrzZy.js → react-DIuy5dyR.js} +12 -3
  19. package/dist/react.d.ts +6 -3
  20. package/dist/react.js +1 -1
  21. package/dist/scene-like-Bx7lZKif.d.ts +4808 -0
  22. package/dist/{store-DIQmxF_s.js → store-BxzcXy9y.js} +431 -65
  23. package/dist/{store-BfC6kkf5.d.ts → store-LM3iU8E4.d.ts} +110 -11
  24. package/dist/store.d.ts +3 -3
  25. package/dist/store.js +1 -1
  26. package/dist/three.d.ts +13 -11
  27. package/dist/three.js +63 -18
  28. package/dist/views-DPMbo0Sl.js +3147 -0
  29. package/dist/wasm/fast_mesh_wasm.d.ts +548 -8
  30. package/dist/wasm/fast_mesh_wasm.js +2100 -89
  31. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +95 -0
  33. package/dist/wasm-threads/fast_mesh_wasm.d.ts +548 -8
  34. package/dist/wasm-threads/fast_mesh_wasm.js +2101 -90
  35. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +95 -0
  37. package/dist/wave6-wasm-Bt4vTlKz.js +146 -0
  38. package/dist/web.d.ts +4 -2
  39. package/dist/web.js +4 -3
  40. package/dist/worker-engine.d.ts +20 -2
  41. package/dist/worker-engine.js +1 -1
  42. package/dist/worker-entry.js +1 -1
  43. package/dist/worker.d.ts +1 -1
  44. package/dist/worker.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/api-4kz45-Mq.js +0 -63
  47. package/dist/client-Ds09vLkN.d.ts +0 -336
  48. package/dist/protocol-Cb23HelE.d.ts +0 -327
  49. package/dist/scene-D0HNTwoo.js +0 -2216
  50. package/dist/scene-like-CADk1vfb.d.ts +0 -1755
  51. package/dist/views-B00kdV0R.js +0 -214
@@ -0,0 +1,3827 @@
1
+ import { a as release, c as wasmMemory, i as finalizer, n as call, r as ensureInitialized, t as FastMeshError } from "./core-4OcWKu3r.js";
2
+ import { $ as checkU32Arg, $t as normalizeBooleanArgs, A as checkLatticeOptions, At as normalizeSelectSmallIslandsArgs, B as decodeExtrudeFaces, Bt as BOOLEAN_OP_CODES, C as decodeWrapCounts, Cn as checkHeightfieldPlacement, Ct as normalizeHollowArgs, D as checkRegisterOptions, Dn as encodeHeightMapOptions, Dt as normalizeReconstructArgs, E as wrapMeshList, En as encodeHeightMapFrame, Et as normalizePlacementInputArgs, F as decodeHullCounts, Fn as rotationMatrix, Ft as normalizeXpbdArgs, G as decodeDelaunayFlipReport, Gt as GEODESIC_METHOD_CODES, H as extrudeFacesArgs, Ht as DYNTOPO_MODE_CODES, I as hullMeshList, In as targetsOf, Jt as checkSurfacePathOptions, K as decodeDenoiseReport, Kt as ICP_OBJECTIVE_CODES, L as hullNormals, M as decodeLatticePreview, Mn as FieldHandle, Mt as normalizeSliceContoursArgs, N as decodeLatticeReport, Nn as MeshHandle, Nt as normalizeU32Selection, O as DEFAULT_LATTICE_MAX_VOXELS, On as encodeHeightfield, Ot as normalizeScreenSelectArgs, P as encodeLatticeOptions, Pn as SectionHandle, Pt as normalizeVertexMaskSelectArgs, Qt as isBrushSculptOp, R as hullPointsBuffer, S as checkWrapOptions, Sn as checkHeightfield, St as normalizeGrowShrinkArgs, T as encodeWrapOptions, Tt as normalizePlaceMeshArgs, U as checkDelaunayFlipOptions, Ut as FILL_CONTINUITY_CODES, V as extrudeBaseArgs, Vt as COARSE_ALIGN_CODES, W as checkDenoiseOptions, Wt as FILL_CONTINUITY_FROM_CODE, X as checkBooleanArg, Yt as checkU32Int, Z as checkNonNegativeArg, Zt as encodeCsgTree, _ as createDeformDomain, _t as normalizeBuildFfdLatticeArgs, a as encodeRule, an as normalizeGeodesicOptions, at as decodeDrainHoleReport, bt as normalizeFfdArgs, c as EntryBook, cn as normalizePartialBridgeOptions, ct as decodeFitPrimitiveReport, d as decodePermanent, dn as normalizeSourceVertices, dt as decodePlaceMeshReport, en as normalizeCsgBatchArgs, et as cloudBuffer, f as tellPermanent, fn as normalizeSurfacePathTarget, ft as decodePlacement15, g as createInspectDomain, gn as throwIfAborted, gt as normalizeArapArgs, h as createRemeshDomain, ht as normalizeAlignToPrimitiveArgs, i as copyRule, in as normalizeFillHolesContinuityOptions, it as decodeContourSlices, j as decodeLatticePlan, jn as isHeightMapFrame, jt as normalizeSliceContourStackArgs, k as DEFAULT_LATTICE_PREVIEW_VOXELS, kn as heightMapMeshList, kt as normalizeSelectInSphereArgs, l as checkHistoryBudget, ln as normalizeQualityArgs, lt as decodeFreeformReport, m as createRepairDomain, mn as normalizeU32List, n as meshViews, nn as normalizeDyntopoCenterRadius, nt as decodeCollisionRule, on as normalizeLandmarkPairs, ot as decodeFaceEditReport, p as createSculptDomain, pn as normalizeTrimCurveArgs, pt as encodeCollisionRule, qt as QUALITY_METRIC_CODES, r as checkInteractionPoints, rn as normalizeDyntopoOptions, rt as decodeCollisionStepReport, s as ENTRY_EVENTS, sn as normalizeOverhangOptions, st as decodeFfdLattice, t as ViewGuard, tn as normalizeDeviationOptions, tt as cloudOrigin, u as checkHistoryEntry, un as normalizeRegistrationOptions, ut as decodeHollowReport, v as createBooleanDomain, vn as decodePrimitiveMesh, vt as normalizeCollisionRule, w as decodeWrapPlan, wn as decodeHeightMapFrame, wt as normalizeKelvinletArgs, xn as checkHeightMapRows, xt as normalizeFitPrimitiveArgs, y as createAlignDomain, yn as encodePrimitive, yt as normalizeDrainHoleArgs, z as decodeExtrudeBase, zt as BOOLEAN_METHOD_CODES } from "./views-DPMbo0Sl.js";
3
+ import { WasmScene } from "./wasm/fast_mesh_wasm.js";
4
+ // 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
+ const UVS = 256;
14
+ const UVS_ALL = 512;
15
+ const RESTORABLE = 1024;
16
+ /** Decodes `[record_count, record...]`. */
17
+ function decodeChanges(msg) {
18
+ let at = 0;
19
+ const next = () => {
20
+ if (at >= msg.length) throw new Error("fast-mesh-wasm: truncated change message");
21
+ return msg[at++];
22
+ };
23
+ const ranges = (all) => {
24
+ const n = next();
25
+ const out = [];
26
+ for (let k = 0; k < n; k++) {
27
+ const start = next();
28
+ out.push([start, next()]);
29
+ }
30
+ return all ? "all" : out;
31
+ };
32
+ const ids = () => {
33
+ const n = next();
34
+ const out = [];
35
+ for (let k = 0; k < n; k++) out.push(next());
36
+ return out;
37
+ };
38
+ const count = next();
39
+ const out = [];
40
+ for (let r = 0; r < count; r++) {
41
+ const index = next();
42
+ const generation = next();
43
+ const flags = next();
44
+ out.push({
45
+ index,
46
+ generation,
47
+ added: (flags & ADDED) !== 0,
48
+ removed: (flags & REMOVED) !== 0,
49
+ restorable: (flags & RESTORABLE) !== 0,
50
+ placementChanged: (flags & PLACEMENT) !== 0,
51
+ capacityChanged: (flags & CAPACITY) !== 0,
52
+ positions: ranges((flags & POSITIONS_ALL) !== 0),
53
+ normals: ranges((flags & NORMALS_ALL) !== 0),
54
+ colors: ranges((flags & COLORS_ALL) !== 0),
55
+ indices: ranges((flags & INDICES_ALL) !== 0),
56
+ ...(flags & UVS) !== 0 ? { uvs: ranges((flags & UVS_ALL) !== 0) } : {},
57
+ fields: ids(),
58
+ sections: ids()
59
+ });
60
+ }
61
+ if (at !== msg.length) throw new Error("fast-mesh-wasm: trailing words in change message");
62
+ return out;
63
+ }
64
+ // src/selection.ts
65
+ function invalid$1(message) {
66
+ return new FastMeshError("INVALID_ARGUMENT", message);
67
+ }
68
+ function stale(message) {
69
+ return new FastMeshError("STALE_SELECTION", message);
70
+ }
71
+ /** Checks a spec's shape; the Scene methods check the mesh and the stamp. */
72
+ function checkSpec(spec) {
73
+ if (spec === null || typeof spec !== "object") throw invalid$1("spec must be an object");
74
+ switch (spec.kind) {
75
+ case "brush": {
76
+ const c = spec.center;
77
+ if (c?.length !== 3 || ![
78
+ c[0],
79
+ c[1],
80
+ c[2]
81
+ ].every(Number.isFinite)) throw invalid$1("brush center must be 3 finite numbers");
82
+ if (typeof spec.radius !== "number" || !(spec.radius >= 0)) throw invalid$1("brush radius must be a number, zero or greater");
83
+ if (spec.space !== void 0 && spec.space !== "local" && spec.space !== "world") throw invalid$1("brush space must be \"local\" or \"world\"");
84
+ return;
85
+ }
86
+ case "lasso": {
87
+ const p = spec.polygon;
88
+ const n = Array.isArray(p) ? p.length : p instanceof Float32Array ? p.length : -1;
89
+ if (n < 6 || n % 2 !== 0) throw invalid$1("lasso polygon needs at least 3 [x, y] corners");
90
+ const pts = p;
91
+ for (let k = 0; k < n; k++) if (!Number.isFinite(pts[k])) throw invalid$1("lasso polygon must hold finite numbers");
92
+ if (spec.axis !== void 0 && spec.axis !== "xy" && spec.axis !== "xz" && spec.axis !== "yz") throw invalid$1("lasso axis must be \"xy\", \"xz\" or \"yz\"");
93
+ return;
94
+ }
95
+ case "component":
96
+ if (!Number.isInteger(spec.seed) || spec.seed < 0 || spec.seed >= 2 ** 32) throw new FastMeshError("INVALID_INDEX", "component seed is not a vertex id");
97
+ return;
98
+ default: throw invalid$1(`unknown select kind "${spec.kind}"`);
99
+ }
100
+ }
101
+ /**
102
+ * Builds adjacency from index triples, skipping removed slots (`0, 0, 0`).
103
+ * `slots` is the vertex slot count.
104
+ */
105
+ function buildTopology(indices, slots) {
106
+ const sets = Array.from({ length: slots }, () => /* @__PURE__ */ new Set());
107
+ const used = new Uint8Array(slots);
108
+ const live = [];
109
+ const link = (a, b) => {
110
+ if (a !== b && a < slots && b < slots) {
111
+ sets[a].add(b);
112
+ sets[b].add(a);
113
+ }
114
+ };
115
+ for (let t = 0; t * 3 + 2 < indices.length; t++) {
116
+ const a = indices[t * 3];
117
+ const b = indices[t * 3 + 1];
118
+ const c = indices[t * 3 + 2];
119
+ if (a === 0 && b === 0 && c === 0) continue;
120
+ if (a >= slots || b >= slots || c >= slots) continue;
121
+ live.push(t);
122
+ used[a] = 1;
123
+ used[b] = 1;
124
+ used[c] = 1;
125
+ link(a, b);
126
+ link(b, c);
127
+ link(c, a);
128
+ }
129
+ return {
130
+ neighbors: sets.map((s) => [...s].sort((x, y) => x - y)),
131
+ used,
132
+ liveTriangles: Uint32Array.from(live)
133
+ };
134
+ }
135
+ /**
136
+ * Every used vertex within `radius` of `center` (squared distances), both in
137
+ * local coordinates. With `stretch`, a column-major 4x4 (a placement's
138
+ * `matrix4`), `radius` is a length after its linear part.
139
+ */
140
+ function brushPick(positions, used, center, radius, stretch) {
141
+ const out = [];
142
+ const r2 = radius * radius;
143
+ const m = stretch;
144
+ for (let v = 0; v < used.length; v++) {
145
+ if (used[v] === 0) continue;
146
+ let dx = positions[v * 3] - center[0];
147
+ let dy = positions[v * 3 + 1] - center[1];
148
+ let dz = positions[v * 3 + 2] - center[2];
149
+ if (m !== void 0) {
150
+ const [x, y, z] = [
151
+ dx,
152
+ dy,
153
+ dz
154
+ ];
155
+ dx = m[0] * x + m[4] * y + m[8] * z;
156
+ dy = m[1] * x + m[5] * y + m[9] * z;
157
+ dz = m[2] * x + m[6] * y + m[10] * z;
158
+ }
159
+ if (dx * dx + dy * dy + dz * dz <= r2) out.push(v);
160
+ }
161
+ return out;
162
+ }
163
+ /** Even-odd point-in-polygon over flat `[x0, y0, ...]`. */
164
+ function insidePolygon(polygon, x, y) {
165
+ let inside = false;
166
+ const n = polygon.length / 2;
167
+ for (let i = 0, j = n - 1; i < n; j = i++) {
168
+ const xi = polygon[i * 2];
169
+ const yi = polygon[i * 2 + 1];
170
+ const xj = polygon[j * 2];
171
+ const yj = polygon[j * 2 + 1];
172
+ if (yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) inside = !inside;
173
+ }
174
+ return inside;
175
+ }
176
+ /** Every used vertex whose `axis` projection falls inside `polygon`. */
177
+ function lassoPick(positions, used, polygon, axis) {
178
+ const pick = axis === "xy" ? [0, 1] : axis === "xz" ? [0, 2] : [1, 2];
179
+ const out = [];
180
+ for (let v = 0; v < used.length; v++) {
181
+ if (used[v] === 0) continue;
182
+ if (insidePolygon(polygon, positions[v * 3 + pick[0]], positions[v * 3 + pick[1]])) out.push(v);
183
+ }
184
+ return out;
185
+ }
186
+ /**
187
+ * The connected component holding `seed` (over triangle edges). Throws
188
+ * `INVALID_ARGUMENT` when the seed is out of range or not alive.
189
+ */
190
+ function componentOf(topology, seed) {
191
+ if (!Number.isInteger(seed) || seed < 0 || seed >= topology.used.length) throw new FastMeshError("INVALID_INDEX", "component seed is not a vertex id");
192
+ if (topology.used[seed] === 0) throw invalid$1("component seed is not on a live triangle");
193
+ const seen = new Uint8Array(topology.used.length);
194
+ const queue = [seed];
195
+ seen[seed] = 1;
196
+ while (queue.length > 0) {
197
+ const v = queue.pop();
198
+ for (const w of topology.neighbors[v]) if (seen[w] === 0) {
199
+ seen[w] = 1;
200
+ queue.push(w);
201
+ }
202
+ }
203
+ const out = [];
204
+ for (let v = 0; v < seen.length; v++) if (seen[v] === 1) out.push(v);
205
+ return out;
206
+ }
207
+ /**
208
+ * Grows `ids` by `steps` rings of edge neighbours (staying on live
209
+ * vertices). `steps` 0 returns `ids`.
210
+ */
211
+ function growIds(topology, ids, steps) {
212
+ if (!Number.isInteger(steps) || steps < 0) throw invalid$1("steps must be a non-negative integer");
213
+ const inSet = new Uint8Array(topology.used.length);
214
+ for (const v of ids) if (v < inSet.length) inSet[v] = 1;
215
+ let frontier = [...ids].filter((v) => v < inSet.length);
216
+ for (let s = 0; s < steps; s++) {
217
+ const next = [];
218
+ for (const v of frontier) for (const w of topology.neighbors[v]) if (inSet[w] === 0) {
219
+ inSet[w] = 1;
220
+ next.push(w);
221
+ }
222
+ if (next.length === 0) break;
223
+ frontier = next;
224
+ }
225
+ const out = [];
226
+ for (let v = 0; v < inSet.length; v++) if (inSet[v] === 1) out.push(v);
227
+ return out;
228
+ }
229
+ /**
230
+ * Shrinks `ids` by `steps` rings: each step drops the members with a live
231
+ * neighbour outside the set. Interior selections (no boundary) survive
232
+ * unchanged.
233
+ */
234
+ function shrinkIds(topology, ids, steps) {
235
+ if (!Number.isInteger(steps) || steps < 0) throw invalid$1("steps must be a non-negative integer");
236
+ let current = new Set([...ids].filter((v) => v < topology.used.length));
237
+ for (let s = 0; s < steps; s++) {
238
+ const peel = [];
239
+ for (const v of current) if (topology.neighbors[v].some((w) => !current.has(w))) peel.push(v);
240
+ if (peel.length === 0) break;
241
+ for (const v of peel) current.delete(v);
242
+ }
243
+ return [...current].sort((a, b) => a - b);
244
+ }
245
+ /** Throws `STALE_SELECTION` when `sel` is not for `mesh` or predates its stamp. */
246
+ function checkSelection(sel, mesh, stamp) {
247
+ if (sel === null || typeof sel !== "object" || sel.mesh !== mesh) throw invalid$1("the selection is not for this mesh");
248
+ if (!Number.isInteger(sel.stamp) || sel.stamp !== stamp) throw stale("the selection predates the mesh's latest topology edit; reselect it");
249
+ }
250
+ /**
251
+ * The inverse of a column-major 4x4 (a placement's `matrix4`), for
252
+ * world-space brushes. Throws `INVALID_ARGUMENT` when not invertible.
253
+ */
254
+ function invertMatrix4(m) {
255
+ const inv = /* @__PURE__ */ new Float64Array(16);
256
+ const a00 = m[0];
257
+ const a01 = m[1];
258
+ const a02 = m[2];
259
+ const a03 = m[3];
260
+ const a10 = m[4];
261
+ const a11 = m[5];
262
+ const a12 = m[6];
263
+ const a13 = m[7];
264
+ const a20 = m[8];
265
+ const a21 = m[9];
266
+ const a22 = m[10];
267
+ const a23 = m[11];
268
+ const a30 = m[12];
269
+ const a31 = m[13];
270
+ const a32 = m[14];
271
+ const a33 = m[15];
272
+ const b00 = a00 * a11 - a01 * a10;
273
+ const b01 = a00 * a12 - a02 * a10;
274
+ const b02 = a00 * a13 - a03 * a10;
275
+ const b03 = a01 * a12 - a02 * a11;
276
+ const b04 = a01 * a13 - a03 * a11;
277
+ const b05 = a02 * a13 - a03 * a12;
278
+ const b06 = a20 * a31 - a21 * a30;
279
+ const b07 = a20 * a32 - a22 * a30;
280
+ const b08 = a20 * a33 - a23 * a30;
281
+ const b09 = a21 * a32 - a22 * a31;
282
+ const b10 = a21 * a33 - a23 * a31;
283
+ const b11 = a22 * a33 - a23 * a32;
284
+ const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
285
+ if (det === 0 || !Number.isFinite(det)) throw invalid$1("the mesh placement is not invertible");
286
+ const s = 1 / det;
287
+ inv[0] = (a11 * b11 - a12 * b10 + a13 * b09) * s;
288
+ inv[1] = (a02 * b10 - a01 * b11 - a03 * b09) * s;
289
+ inv[2] = (a31 * b05 - a32 * b04 + a33 * b03) * s;
290
+ inv[3] = (a22 * b04 - a21 * b05 - a23 * b03) * s;
291
+ inv[4] = (a12 * b08 - a10 * b11 - a13 * b07) * s;
292
+ inv[5] = (a00 * b11 - a02 * b08 + a03 * b07) * s;
293
+ inv[6] = (a32 * b02 - a30 * b05 - a33 * b01) * s;
294
+ inv[7] = (a20 * b05 - a22 * b02 + a23 * b01) * s;
295
+ inv[8] = (a10 * b10 - a11 * b08 + a13 * b06) * s;
296
+ inv[9] = (a01 * b08 - a00 * b10 - a03 * b06) * s;
297
+ inv[10] = (a30 * b04 - a31 * b02 + a33 * b00) * s;
298
+ inv[11] = (a21 * b02 - a20 * b04 - a23 * b00) * s;
299
+ inv[12] = (a11 * b07 - a10 * b09 - a12 * b06) * s;
300
+ inv[13] = (a00 * b09 - a01 * b07 + a02 * b06) * s;
301
+ inv[14] = (a31 * b01 - a30 * b03 - a32 * b00) * s;
302
+ inv[15] = (a20 * b03 - a21 * b01 + a22 * b00) * s;
303
+ return inv;
304
+ }
305
+ /** Applies a column-major 4x4 to a point. */
306
+ function transformPoint(m, p) {
307
+ const x = p[0];
308
+ const y = p[1];
309
+ const z = p[2];
310
+ const w = m[3] * x + m[7] * y + m[11] * z + m[15];
311
+ if (w === 0 || !Number.isFinite(w)) throw invalid$1("the mesh placement does not map the brush centre");
312
+ return [
313
+ (m[0] * x + m[4] * y + m[8] * z + m[12]) / w,
314
+ (m[1] * x + m[5] * y + m[9] * z + m[13]) / w,
315
+ (m[2] * x + m[6] * y + m[10] * z + m[14]) / w
316
+ ];
317
+ }
318
+ // src/scene.ts
319
+ /**
320
+ * The `WasmScene` class new scenes wrap: the single-threaded glue's, unless
321
+ * the Worker entry started the threaded glue ({@link useWasmScene}).
322
+ */
323
+ let RawScene = WasmScene;
324
+ /**
325
+ * Internal (the Worker entry): makes later scenes from `ctor`, the
326
+ * `WasmScene` of the glue it initialised (the threaded one on cross-origin
327
+ * isolated pages). Pair it with `setMemory` for that glue's memory.
328
+ */
329
+ function useWasmScene(ctor) {
330
+ RawScene = ctor;
331
+ }
332
+ /** Internal: the `WasmScene` class new scenes wrap ({@link useWasmScene}), for its statics. */
333
+ function activeWasmScene() {
334
+ return RawScene;
335
+ }
336
+ const meshIds = /* @__PURE__ */ new WeakMap();
337
+ const rawIds = /* @__PURE__ */ new WeakMap();
338
+ /** The repair list's prefix code for a {@link VertexProtection}. */
339
+ const PROTECT_CODE = 32;
340
+ /** The repair list's prefix code for {@link Symmetry} and {@link SurfaceFilter}. */
341
+ const BRUSH_MODIFIERS_CODE = 33;
342
+ const MODES = {
343
+ eager: 0,
344
+ lazy: 1,
345
+ manual: 2
346
+ };
347
+ const MODE_NAMES = [
348
+ "eager",
349
+ "lazy",
350
+ "manual"
351
+ ];
352
+ function modeCode(mode) {
353
+ if (!Object.hasOwn(MODES, mode)) throw invalid("mode must be \"eager\", \"lazy\" or \"manual\"");
354
+ return MODES[mode];
355
+ }
356
+ const CULLS = {
357
+ none: 0,
358
+ back: 1,
359
+ front: 2
360
+ };
361
+ const SIGNS = {
362
+ auto: 0,
363
+ pseudonormal: 1,
364
+ winding: 2
365
+ };
366
+ /** The code of a string option in `table`, or `INVALID_ARGUMENT` naming `what`. */
367
+ function codeIn(table, value, what) {
368
+ if (!Object.hasOwn(table, value)) throw invalid(`${what} must be one of ${Object.keys(table).join(", ")}`);
369
+ return table[value];
370
+ }
371
+ /** Three numbers of a flat result, from `at`. */
372
+ function vec3At(a, at) {
373
+ return [
374
+ a[at],
375
+ a[at + 1],
376
+ a[at + 2]
377
+ ];
378
+ }
379
+ function invalid(message) {
380
+ return new FastMeshError("INVALID_ARGUMENT", message);
381
+ }
382
+ /**
383
+ * The stretch of a column-major 4x4's linear part, a rotation and a uniform
384
+ * scale: the cube root of its determinant. World-space brush radii divide by
385
+ * it.
386
+ */
387
+ function meanStretch(m) {
388
+ const det = m[0] * (m[5] * m[10] - m[6] * m[9]) - m[4] * (m[1] * m[10] - m[2] * m[9]) + m[8] * (m[1] * m[6] - m[2] * m[5]);
389
+ const s = Math.cbrt(Math.abs(det));
390
+ if (s === 0 || !Number.isFinite(s)) throw invalid("the mesh placement is not invertible");
391
+ return s;
392
+ }
393
+ const U32_LIMIT = 2 ** 32;
394
+ const EDIT_CODES = {
395
+ setPositions: 0,
396
+ addVertices: 1,
397
+ addTriangles: 2,
398
+ removeTriangles: 3,
399
+ removeVertices: 4,
400
+ setUvs: 5
401
+ };
402
+ /** An id list as the binding's `n, r, ids..., (slot, op, i)...`; see `crate::edit`. */
403
+ function encodeIds(list, what, words) {
404
+ if (list instanceof Uint32Array) {
405
+ words.push([list.length, 0], list);
406
+ return;
407
+ }
408
+ if (!Array.isArray(list)) throw invalid(`${what} must be a Uint32Array or an array`);
409
+ const ids = new Array(list.length);
410
+ const refs = [];
411
+ for (let slot = 0; slot < list.length; slot++) {
412
+ const x = list[slot];
413
+ if (typeof x === "number") {
414
+ if (!Number.isInteger(x) || x < 0 || x >= U32_LIMIT) throw new FastMeshError("INVALID_INDEX", `${what}: ${x} is not an id`);
415
+ ids[slot] = x;
416
+ continue;
417
+ }
418
+ const ref = x?.ref;
419
+ if (!Array.isArray(ref) || ref.length !== 2) throw invalid(`${what} must hold ids or { ref: [opIndex, i] }`);
420
+ 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`);
421
+ ids[slot] = 0;
422
+ refs.push(slot, ref[0], ref[1]);
423
+ }
424
+ words.push([list.length, refs.length / 3], ids, refs);
425
+ }
426
+ /** World positions of an op, checked to be `3 · count` long (any count when `count` is undefined). */
427
+ function opPositions(positions, count, what) {
428
+ const p = toFloat64(positions ?? []);
429
+ if (p.length % 3 !== 0 || count !== void 0 && p.length !== 3 * count) throw invalid(`${what}: positions need 3 values per vertex`);
430
+ return p;
431
+ }
432
+ /** An edit op list as the binding's `(ops, values)`; see `crate::edit` in the Rust crate. */
433
+ function encodeEdit(ops) {
434
+ if (!Array.isArray(ops)) throw invalid("ops must be an array");
435
+ const words = [];
436
+ const values = [];
437
+ ops.forEach((o, k) => {
438
+ const what = `op ${k}`;
439
+ const code = codeIn(EDIT_CODES, o?.op, `${what}: op`);
440
+ words.push([code]);
441
+ switch (o.op) {
442
+ case "setPositions":
443
+ encodeIds(o.vertices, `${what}: vertices`, words);
444
+ values.push(opPositions(o.positions, o.vertices?.length, what));
445
+ break;
446
+ case "addVertices": {
447
+ const p = opPositions(o.positions, void 0, what);
448
+ words.push([p.length / 3]);
449
+ values.push(p);
450
+ break;
451
+ }
452
+ case "addTriangles":
453
+ encodeIds(o.triangles, `${what}: triangles`, words);
454
+ break;
455
+ case "removeTriangles":
456
+ encodeIds(o.triangles, `${what}: triangles`, words);
457
+ break;
458
+ case "removeVertices":
459
+ encodeIds(o.vertices, `${what}: vertices`, words);
460
+ break;
461
+ case "setUvs": {
462
+ encodeIds(o.vertices, `${what}: vertices`, words);
463
+ const uvs = Float64Array.from(o.uvs ?? []);
464
+ if (uvs.length !== 2 * o.vertices.length) throw invalid(`${what}: uvs need 2 values per vertex`);
465
+ values.push(uvs);
466
+ break;
467
+ }
468
+ }
469
+ });
470
+ const out = new Uint32Array(words.reduce((n, w) => n + w.length, 0));
471
+ let at = 0;
472
+ for (const w of words) {
473
+ out.set(w, at);
474
+ at += w.length;
475
+ }
476
+ const flat = new Float64Array(values.reduce((n, v) => n + v.length, 0));
477
+ at = 0;
478
+ for (const v of values) {
479
+ flat.set(v, at);
480
+ at += v.length;
481
+ }
482
+ return {
483
+ words: out,
484
+ values: flat
485
+ };
486
+ }
487
+ const REPAIR_CODES = {
488
+ weld: 0,
489
+ removeDegenerate: 1,
490
+ removeSmallComponents: 2,
491
+ orient: 3,
492
+ fillHoles: 4,
493
+ inflate: 5,
494
+ smooth: 6,
495
+ remesh: 7,
496
+ bridgeLoops: 8,
497
+ grab: 9,
498
+ relax: 10,
499
+ offset: 11,
500
+ shell: 12,
501
+ simplify: 28,
502
+ subdivide: 14,
503
+ splitStretched: 16,
504
+ captureRestSizes: 17,
505
+ captureStrokeState: 18,
506
+ flatten: 19,
507
+ crease: 20,
508
+ clay: 21,
509
+ twist: 22,
510
+ makeManifold: 23,
511
+ resolveSelfIntersections: 24,
512
+ cleanupSlivers: 25,
513
+ remeshSurface: 27
514
+ };
515
+ /** The op code of a legacy {@link AutoRepairRequest}; see `crate::edit` in the Rust crate. */
516
+ const AUTO_REPAIR_CODE = 15;
517
+ /** The op code of an extended preset {@link AutoRepairRequest}; see `crate::edit` in the Rust crate. */
518
+ const AUTO_REPAIR_PRESET_CODE = 26;
519
+ const AUTO_STAGE_OPS = {
520
+ 0: "weld",
521
+ 1: "removeDegenerate",
522
+ 2: "removeSmallComponents",
523
+ 3: "orient",
524
+ 4: "fillHoles",
525
+ 23: "makeManifold",
526
+ 24: "resolveSelfIntersections",
527
+ 25: "cleanupSlivers"
528
+ };
529
+ const PRESET_CODES = {
530
+ general: 0,
531
+ scan3d: 1,
532
+ print3d: 2,
533
+ cadImport: 3
534
+ };
535
+ const SELF_INTERSECTION_MODES = [
536
+ "none",
537
+ "deleteAndFill",
538
+ "cutAndStitch",
539
+ "voxelHeal"
540
+ ];
541
+ const SELF_INTERSECTION_MODE_CODES = {
542
+ none: 0,
543
+ deleteAndFill: 1,
544
+ cutAndStitch: 2,
545
+ voxelHeal: 3
546
+ };
547
+ const FALLOFF_CODES = {
548
+ linear: 0,
549
+ smooth: 1
550
+ };
551
+ const INFLATE_METHOD_CODES = {
552
+ vertexNormal: 0,
553
+ averageNormal: 1,
554
+ strokeNormal: 2
555
+ };
556
+ const SMOOTH_METHOD_CODES = {
557
+ taubin: 0,
558
+ laplacian: 1,
559
+ hcLaplacian: 2,
560
+ cotangent: 3
561
+ };
562
+ const GRAB_METHOD_CODES = {
563
+ sphere: 0,
564
+ geodesic: 1,
565
+ kelvinlet: 2
566
+ };
567
+ const FLATTEN_MODE_CODES = {
568
+ both: 0,
569
+ peaks: 1,
570
+ valleys: 2
571
+ };
572
+ const CLAY_PROFILE_CODES = {
573
+ round: 0,
574
+ strips: 1
575
+ };
576
+ const TWIST_METHOD_CODES = {
577
+ vortex: 0,
578
+ kelvinlet: 1
579
+ };
580
+ const OFFSET_ALGORITHM_CODES = {
581
+ normal: 0,
582
+ fhEdt: 1,
583
+ bvhSdf: 2
584
+ };
585
+ const SUBDIVIDE_METHOD_CODES = { loop: 0 };
586
+ const SURFACE_REMESH_MODE_CODES = {
587
+ isotropic: 0,
588
+ adaptive: 1
589
+ };
590
+ /** An optional number for the binding: NaN when unset; an explicit NaN is rejected. */
591
+ /** The `status` codes of `WasmScene.register`, in order. */
592
+ const REGISTER_STATUSES = [
593
+ "converged",
594
+ "maxIterations",
595
+ "underconstrained",
596
+ "tooFewCorrespondences",
597
+ "diverged"
598
+ ];
599
+ /** The `not applied` codes of `WasmScene.register`, in order. */
600
+ const REGISTER_NOT_APPLIED = [
601
+ null,
602
+ "notRequested",
603
+ "notConverged",
604
+ "rmseAboveLimit",
605
+ "tooFewInliers"
606
+ ];
607
+ function optional(v, what) {
608
+ if (v === void 0) return NaN;
609
+ if (typeof v !== "number" || Number.isNaN(v)) throw invalid(`${what} must be a number`);
610
+ return v;
611
+ }
612
+ function flagOf(v, fallback) {
613
+ return v ?? fallback ? 1 : 0;
614
+ }
615
+ function optVoxelSize(v) {
616
+ if (v === void 0) return NaN;
617
+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0) throw invalid("voxelSize must be positive and finite");
618
+ return v;
619
+ }
620
+ function optMaxVoxels(v) {
621
+ if (v === void 0) return NaN;
622
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 64 || v > Number.MAX_SAFE_INTEGER) throw invalid("maxVoxels must be an integer of at least 64");
623
+ return v;
624
+ }
625
+ /** A brush center as 3 values; anything else is `INVALID_ARGUMENT`. */
626
+ function centerOf(center, values) {
627
+ const c = center;
628
+ if (c?.length !== 3 || ![
629
+ c[0],
630
+ c[1],
631
+ c[2]
632
+ ].every(Number.isFinite)) throw invalid("center must be 3 finite numbers");
633
+ values.push(c[0], c[1], c[2]);
634
+ }
635
+ /** A loop id as the binding's `minVertex, len, hash low, hash high`. */
636
+ function encodeLoopId(id, out) {
637
+ const { minVertex, len, hash } = id ?? {};
638
+ if (typeof hash !== "bigint" || hash < 0n || hash >= 1n << 64n) throw invalid("a loop id's hash must be a bigint in 0..2^64");
639
+ 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");
640
+ out.push(minVertex, len, Number(hash & 4294967295n), Number(hash >> 32n));
641
+ }
642
+ function isAutoRepair(op) {
643
+ return op?.kind === "auto";
644
+ }
645
+ function optionalVec3(v, what, values) {
646
+ if (v === void 0) {
647
+ values.push(0, 0, 0, 0);
648
+ return;
649
+ }
650
+ const c = v;
651
+ if (c?.length !== 3 || ![
652
+ c[0],
653
+ c[1],
654
+ c[2]
655
+ ].every((x) => typeof x === "number" && Number.isFinite(x))) throw invalid(`${what} must be 3 finite numbers`);
656
+ values.push(1, c[0], c[1], c[2]);
657
+ }
658
+ /** The prefix that wraps the op after it in a {@link VertexProtection}; see `crate::edit` in the Rust crate. */
659
+ function encodeProtect(protect, values) {
660
+ const { vertices, weights, band } = protect;
661
+ if (vertices?.length === void 0) throw invalid("protect.vertices must be an array of vertex ids");
662
+ const n = vertices.length;
663
+ if (weights !== void 0 && weights.length !== n) throw invalid("protect.weights must have one weight per vertex");
664
+ values.push(PROTECT_CODE, n, optional(band, "protect.band"));
665
+ for (let k = 0; k < n; k++) values.push(vertices[k]);
666
+ for (let k = 0; k < n; k++) values.push(weights === void 0 ? 0 : weights[k]);
667
+ }
668
+ /** Encodes prefix `33` (`brushModifiers`: symmetry + surface filter) before a brush op. */
669
+ function encodeBrushModifiers(symmetry, filter, values) {
670
+ if (symmetry === void 0 && filter === void 0) return;
671
+ let symMask = 0;
672
+ if (symmetry !== void 0) {
673
+ if (typeof symmetry !== "object" || symmetry === null) throw invalid("symmetry must be an object");
674
+ if (symmetry.x) symMask |= 1;
675
+ if (symmetry.y) symMask |= 2;
676
+ if (symmetry.z) symMask |= 4;
677
+ }
678
+ let filterKind = 0;
679
+ let p0 = NaN;
680
+ let p1 = NaN;
681
+ let normal;
682
+ if (filter !== void 0) {
683
+ if (typeof filter !== "object" || filter === null) throw invalid("filter must be an object");
684
+ switch (filter.kind) {
685
+ case "none": break;
686
+ case "peaksOnly":
687
+ case "valleysOnly":
688
+ filterKind = filter.kind === "peaksOnly" ? 1 : 2;
689
+ p0 = optional(filter.threshold, "filter.threshold");
690
+ p1 = optional(filter.contrast, "filter.contrast");
691
+ break;
692
+ case "normalAngle":
693
+ filterKind = 3;
694
+ p0 = optional(filter.maxAngleDeg, "filter.maxAngleDeg");
695
+ normal = filter.normal;
696
+ break;
697
+ default: throw invalid("filter.kind must be \"none\", \"peaksOnly\", \"valleysOnly\" or \"normalAngle\"");
698
+ }
699
+ }
700
+ values.push(BRUSH_MODIFIERS_CODE, symMask, filterKind, p0, p1);
701
+ optionalVec3(normal, "filter.normal", values);
702
+ }
703
+ /** A repair op list as the binding's `(ops, loops)`; see `crate::edit` in the Rust crate. */
704
+ function encodeRepair(ops) {
705
+ const values = [];
706
+ const loops = [];
707
+ for (const o of ops) {
708
+ const code = codeIn(REPAIR_CODES, o?.op, "repair op");
709
+ const protect = o?.protect;
710
+ if (protect !== void 0) encodeProtect(protect, values);
711
+ const symmetry = o?.symmetry;
712
+ const filter = o?.filter;
713
+ encodeBrushModifiers(symmetry, filter, values);
714
+ values.push(code);
715
+ switch (o.op) {
716
+ case "weld":
717
+ values.push(optional(o.tolerance, "tolerance"));
718
+ break;
719
+ case "removeDegenerate":
720
+ values.push(optional(o.areaEpsilon, "areaEpsilon"), flagOf(o.removeUnusedVertices, true));
721
+ break;
722
+ case "removeSmallComponents":
723
+ values.push(optional(o.minTriangles, "minTriangles"), optional(o.minArea, "minArea"), flagOf(o.keepLargest, true), flagOf(o.keepCavities, true));
724
+ break;
725
+ case "orient": break;
726
+ case "fillHoles": {
727
+ let count = NaN;
728
+ if (o.loops !== void 0) {
729
+ if (!Array.isArray(o.loops)) throw invalid("loops must be an array of loop ids");
730
+ count = o.loops.length;
731
+ for (const id of o.loops) encodeLoopId(id, loops);
732
+ }
733
+ 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"), optional(o.maxDihedral, "maxDihedral"), optional(o.maxRefineVertices, "maxRefineVertices"));
734
+ break;
735
+ }
736
+ case "inflate":
737
+ centerOf(o.center, values);
738
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), o.method === void 0 ? NaN : codeIn(INFLATE_METHOD_CODES, o.method, "inflate method"));
739
+ break;
740
+ case "smooth":
741
+ centerOf(o.center, values);
742
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), optional(o.cycles, "cycles"), o.method === void 0 ? NaN : codeIn(SMOOTH_METHOD_CODES, o.method, "smooth method"));
743
+ break;
744
+ case "relax":
745
+ centerOf(o.center, values);
746
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), optional(o.cycles, "cycles"));
747
+ break;
748
+ case "remesh":
749
+ centerOf(o.center, values);
750
+ values.push(optional(o.radius, "radius"), optional(o.targetLength, "targetLength"), optional(o.maxRounds, "maxRounds"), flagOf(o.splitOnly, false));
751
+ break;
752
+ case "bridgeLoops":
753
+ if (!Array.isArray(o.loops) || o.loops.length !== 2) throw invalid("loops must be an array of two loop ids");
754
+ values.push(optional(o.maxEdges, "maxEdges"));
755
+ for (const id of o.loops) encodeLoopId(id, loops);
756
+ break;
757
+ case "grab": {
758
+ centerOf(o.center, values);
759
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"));
760
+ const d = o.direction;
761
+ if (d?.length !== 3 || ![
762
+ d[0],
763
+ d[1],
764
+ d[2]
765
+ ].every(Number.isFinite)) throw invalid("direction must be 3 finite numbers");
766
+ values.push(d[0], d[1], d[2], o.method === void 0 ? NaN : codeIn(GRAB_METHOD_CODES, o.method, "grab method"), optional(o.poisson, "poisson"), flagOf(o.fromStroke, false), flagOf(o.adaptiveReach, false));
767
+ break;
768
+ }
769
+ case "flatten":
770
+ centerOf(o.center, values);
771
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), o.mode === void 0 ? NaN : codeIn(FLATTEN_MODE_CODES, o.mode, "flatten mode"));
772
+ optionalVec3(o.planeOrigin, "planeOrigin", values);
773
+ optionalVec3(o.planeNormal, "planeNormal", values);
774
+ break;
775
+ case "crease":
776
+ centerOf(o.center, values);
777
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), optional(o.pinch, "pinch"));
778
+ break;
779
+ case "clay":
780
+ centerOf(o.center, values);
781
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), o.profile === void 0 ? NaN : codeIn(CLAY_PROFILE_CODES, o.profile, "clay profile"));
782
+ optionalVec3(o.tangent, "tangent", values);
783
+ break;
784
+ case "twist":
785
+ centerOf(o.center, values);
786
+ values.push(optional(o.radius, "radius"), codeIn(FALLOFF_CODES, o.falloff, "falloff"), optional(o.strength, "strength"), o.method === void 0 ? NaN : codeIn(TWIST_METHOD_CODES, o.method, "twist method"));
787
+ optionalVec3(o.axis, "axis", values);
788
+ break;
789
+ case "offset": {
790
+ const distance = optional(o.distance, "distance");
791
+ const alg = o.algorithm === void 0 ? NaN : codeIn(OFFSET_ALGORITHM_CODES, o.algorithm, "algorithm");
792
+ values.push(distance, alg, optVoxelSize(o.voxelSize), optMaxVoxels(o.maxVoxels));
793
+ break;
794
+ }
795
+ case "shell":
796
+ values.push(optional(o.thickness, "thickness"));
797
+ break;
798
+ case "simplify":
799
+ if (o.targetTriangles === void 0 && o.targetRatio === void 0 && o.maxDeviation === void 0) throw invalid("simplify requires targetTriangles, targetRatio, or maxDeviation");
800
+ values.push(optional(o.targetTriangles, "targetTriangles"), optional(o.targetRatio, "targetRatio"), optional(o.maxDeviation, "maxDeviation"), flagOf(o.preserveBoundary, true), flagOf(o.preserveUvs, false), flagOf(o.lockCreases, false), optional(o.creaseAngleDeg, "creaseAngleDeg"), flagOf(o.preventNormalInversion, true));
801
+ break;
802
+ case "remeshSurface":
803
+ if (typeof o.targetEdgeLength !== "number" || !Number.isFinite(o.targetEdgeLength) || o.targetEdgeLength <= 0) throw invalid("targetEdgeLength must be positive and finite");
804
+ values.push(o.mode === void 0 ? NaN : codeIn(SURFACE_REMESH_MODE_CODES, o.mode, "mode"), o.targetEdgeLength, optional(o.minEdgeLength, "minEdgeLength"), optional(o.maxEdgeLength, "maxEdgeLength"), optional(o.iterations, "iterations"), optional(o.smoothStrength, "smoothStrength"), flagOf(o.projectToSurface, true), flagOf(o.lockBoundaries, true), flagOf(o.lockCreases, true), optional(o.creaseAngleDeg, "creaseAngleDeg"));
805
+ break;
806
+ case "subdivide":
807
+ values.push(o.method === void 0 ? NaN : codeIn(SUBDIVIDE_METHOD_CODES, o.method, "method"), optional(o.levels, "levels"));
808
+ break;
809
+ case "splitStretched":
810
+ centerOf(o.center, values);
811
+ values.push(optional(o.radius, "radius"), optional(o.limit, "limit"), optional(o.maxSplits, "maxSplits"), flagOf(o.smooth, true), optional(o.sharpAngle, "sharpAngle"));
812
+ break;
813
+ case "captureRestSizes":
814
+ case "captureStrokeState":
815
+ values.push(flagOf(o.onlyIfMissing, false));
816
+ break;
817
+ case "makeManifold":
818
+ values.push(flagOf(o.removeDuplicates, true), flagOf(o.pruneFins, true), flagOf(o.splitNonManifoldEdges, true), flagOf(o.splitPinchVertices, true));
819
+ break;
820
+ case "resolveSelfIntersections":
821
+ values.push(o.mode === void 0 ? NaN : codeIn(SELF_INTERSECTION_MODE_CODES, o.mode, "mode"), optional(o.ringExpansion, "ringExpansion"), optVoxelSize(o.voxelSize), optMaxVoxels(o.maxVoxels), optional(o.maxHoleEdges, "maxHoleEdges"), flagOf(o.fair, true), optional(o.stitchTolerance, "stitchTolerance"));
822
+ break;
823
+ case "cleanupSlivers": values.push(optional(o.maxAspectRatio, "maxAspectRatio"), optional(o.minAngleDeg, "minAngleDeg"), optional(o.maxAngleDeg, "maxAngleDeg"), optional(o.maxIterations, "maxIterations"));
824
+ }
825
+ }
826
+ return {
827
+ values: Float64Array.from(values),
828
+ loops: Uint32Array.from(loops)
829
+ };
830
+ }
831
+ /** Reads a flat `f64` result front to back. */
832
+ var Reader = class {
833
+ data;
834
+ at = 0;
835
+ constructor(data) {
836
+ this.data = data;
837
+ }
838
+ next() {
839
+ return this.data[this.at++];
840
+ }
841
+ flag() {
842
+ return this.next() === 1;
843
+ }
844
+ /** `n` ids as a copy. */
845
+ ids(n) {
846
+ const out = Uint32Array.from(this.data.subarray(this.at, this.at + n));
847
+ this.at += n;
848
+ return out;
849
+ }
850
+ /** A count, then that many ids. */
851
+ list() {
852
+ return this.ids(this.next());
853
+ }
854
+ loopId() {
855
+ return {
856
+ minVertex: this.next(),
857
+ len: this.next(),
858
+ hash: BigInt(this.next()) | BigInt(this.next()) << 32n
859
+ };
860
+ }
861
+ /** A count, then that many items. */
862
+ many(item) {
863
+ const n = this.next();
864
+ const out = [];
865
+ for (let k = 0; k < n; k++) out.push(item());
866
+ return out;
867
+ }
868
+ };
869
+ const SKIP_REASONS = [
870
+ "bounds",
871
+ "unclean",
872
+ "uvSeam"
873
+ ];
874
+ const FAIL_REASONS = [
875
+ "projectionFolds",
876
+ "noValidTriangulation",
877
+ "solver"
878
+ ];
879
+ const WEIGHTS = [
880
+ null,
881
+ "cotangent",
882
+ "uniform"
883
+ ];
884
+ /** One op's report from a repair result; see `crate::edit` in the Rust crate. */
885
+ function decodeReport(op, r) {
886
+ switch (op) {
887
+ case "weld": return {
888
+ mergedVertices: r.next(),
889
+ removedTriangles: r.next()
890
+ };
891
+ case "removeDegenerate": return {
892
+ removedTriangles: r.next(),
893
+ removedVertices: r.next()
894
+ };
895
+ case "removeSmallComponents": return {
896
+ removedComponents: r.next(),
897
+ removedTriangles: r.next(),
898
+ removedVertices: r.next()
899
+ };
900
+ case "orient": return {
901
+ flippedTriangles: r.next(),
902
+ patches: r.next(),
903
+ nonOrientablePatches: r.next(),
904
+ flippedOutwardComponents: r.next()
905
+ };
906
+ case "fillHoles": return {
907
+ filled: r.many(() => ({
908
+ id: r.loopId(),
909
+ trianglesAdded: r.next(),
910
+ verticesAdded: r.next(),
911
+ converged: r.flag(),
912
+ weights: WEIGHTS[r.next()],
913
+ refineCapped: r.flag()
914
+ })),
915
+ skipped: r.many(() => ({
916
+ id: r.loopId(),
917
+ reason: SKIP_REASONS[r.next()]
918
+ })),
919
+ failed: r.many(() => ({
920
+ id: r.loopId(),
921
+ reason: FAIL_REASONS[r.next()]
922
+ }))
923
+ };
924
+ case "inflate":
925
+ case "smooth":
926
+ case "relax":
927
+ case "grab":
928
+ case "flatten":
929
+ case "crease":
930
+ case "clay":
931
+ case "twist": return {
932
+ moved: r.next(),
933
+ maxDisplacement: r.next()
934
+ };
935
+ case "remesh": return {
936
+ splits: r.next(),
937
+ collapses: r.next(),
938
+ flips: r.next(),
939
+ rounds: r.next()
940
+ };
941
+ case "bridgeLoops": return { trianglesAdded: r.next() };
942
+ case "offset": return {
943
+ moved: r.next(),
944
+ maxDisplacement: r.next(),
945
+ degenerateRemoved: r.next(),
946
+ verticesRemoved: r.next(),
947
+ verticesAdded: r.next(),
948
+ trianglesAdded: r.next(),
949
+ trianglesRemoved: r.next(),
950
+ voxelSize: r.next(),
951
+ uvsDropped: r.flag()
952
+ };
953
+ case "shell": return {
954
+ verticesAdded: r.next(),
955
+ trianglesAdded: r.next(),
956
+ loopsClosed: r.next(),
957
+ degenerateRemoved: r.next(),
958
+ verticesRemoved: r.next()
959
+ };
960
+ case "simplify": return {
961
+ collapsed: r.next(),
962
+ trianglesRemoved: r.next(),
963
+ verticesRemoved: r.next(),
964
+ maxDeviationAchieved: r.next()
965
+ };
966
+ case "remeshSurface": return {
967
+ initialTriangles: r.next(),
968
+ finalTriangles: r.next(),
969
+ splits: r.next(),
970
+ collapses: r.next(),
971
+ flips: r.next(),
972
+ iterationsRun: r.next(),
973
+ uvsDropped: r.flag()
974
+ };
975
+ case "subdivide": return {
976
+ verticesAdded: r.next(),
977
+ trianglesAdded: r.next()
978
+ };
979
+ case "splitStretched": {
980
+ const splits = r.next();
981
+ const remaining = r.next();
982
+ const vertices = new Uint32Array(3 * splits);
983
+ for (let k = 0; k < vertices.length; k++) vertices[k] = r.next();
984
+ return {
985
+ splits,
986
+ remaining,
987
+ vertices
988
+ };
989
+ }
990
+ case "captureRestSizes":
991
+ case "captureStrokeState": return {};
992
+ case "makeManifold": return {
993
+ removedDuplicateTriangles: r.next(),
994
+ prunedFinTriangles: r.next(),
995
+ splitNonManifoldEdges: r.next(),
996
+ splitPinchVertices: r.next(),
997
+ verticesAdded: r.next(),
998
+ removedVertices: r.next()
999
+ };
1000
+ case "resolveSelfIntersections": return {
1001
+ initialPairs: r.next(),
1002
+ remainingPairs: r.next(),
1003
+ removedTriangles: r.next(),
1004
+ addedTriangles: r.next(),
1005
+ modeUsed: SELF_INTERSECTION_MODES[r.next()],
1006
+ uvsDropped: r.flag()
1007
+ };
1008
+ case "cleanupSlivers": return {
1009
+ collapsedNeedles: r.next(),
1010
+ flippedCaps: r.next(),
1011
+ removedDegenerate: r.next(),
1012
+ removedVertices: r.next()
1013
+ };
1014
+ }
1015
+ }
1016
+ /** An auto repair's result, stage by stage in the order they ran; see `crate::edit` in the Rust crate. */
1017
+ function decodeAutoReport(r) {
1018
+ const stages = {};
1019
+ while (r.at < r.data.length) {
1020
+ const code = r.next();
1021
+ const op = AUTO_STAGE_OPS[code];
1022
+ if (op === void 0) throw invalid(`unknown auto repair stage code ${code}`);
1023
+ stages[op] = decodeReport(op, r);
1024
+ }
1025
+ return stages;
1026
+ }
1027
+ /** An analysis result; see `encode_analysis` in the Rust crate. */
1028
+ function decodeAnalysis(r) {
1029
+ const loops = r.many(() => ({
1030
+ id: r.loopId(),
1031
+ vertices: r.list(),
1032
+ perimeter: r.next(),
1033
+ area: r.next(),
1034
+ closed: r.flag(),
1035
+ clean: r.flag()
1036
+ }));
1037
+ const coincidentGroups = r.next();
1038
+ const coincident = r.many(() => r.list());
1039
+ const degenerate = r.next();
1040
+ const degenerateList = r.list();
1041
+ const duplicate = r.next();
1042
+ const duplicateList = r.list();
1043
+ const nonManifoldEdges = r.next();
1044
+ const nonManifoldEdgeList = r.many(() => [r.next(), r.next()]);
1045
+ const nonManifoldVertices = r.list();
1046
+ const pinchVertices = r.list();
1047
+ const components = r.many(() => ({
1048
+ triangles: r.list(),
1049
+ area: r.next(),
1050
+ closed: r.flag(),
1051
+ cavity: r.flag()
1052
+ }));
1053
+ const orientationConflicts = r.next();
1054
+ const si = r.next();
1055
+ return {
1056
+ loops,
1057
+ coincidentGroups,
1058
+ coincident,
1059
+ degenerate,
1060
+ degenerateList,
1061
+ duplicate,
1062
+ duplicateList,
1063
+ nonManifoldEdges,
1064
+ nonManifoldEdgeList,
1065
+ nonManifoldVertices,
1066
+ pinchVertices,
1067
+ components,
1068
+ orientationConflicts,
1069
+ selfIntersects: si < 0 ? null : si === 1
1070
+ };
1071
+ }
1072
+ function toFloat64(values) {
1073
+ return values instanceof Float64Array ? values : Float64Array.from(values);
1074
+ }
1075
+ function toUint32(values) {
1076
+ return values instanceof Uint32Array ? values : Uint32Array.from(values);
1077
+ }
1078
+ /** Set by `Scene`'s static block. */
1079
+ let fieldStepsOf;
1080
+ /** @internal The stepped field updates of `scene` (see {@link FieldSteps}); for the Worker engine. */
1081
+ function fieldSteps(scene) {
1082
+ return fieldStepsOf(scene);
1083
+ }
1084
+ /** Set by `Scene`'s static block. */
1085
+ let meshAddsOf;
1086
+ function decodeFillContinuityStats(raw) {
1087
+ return {
1088
+ loopIndex: raw[0],
1089
+ filledVertices: raw[1],
1090
+ filledTriangles: raw[2],
1091
+ perimeter: raw[3],
1092
+ maxDihedralAngleDeg: raw[4],
1093
+ continuity: FILL_CONTINUITY_FROM_CODE[raw[5]] ?? "curvature",
1094
+ islandLoopsMerged: raw[6],
1095
+ converged: raw[7] === 1
1096
+ };
1097
+ }
1098
+ function decodeDyntopoPatch(raw, offset) {
1099
+ const newCount = raw[offset + 4];
1100
+ const removedCount = raw[offset + 5];
1101
+ const start = offset + 6;
1102
+ return {
1103
+ splits: raw[offset],
1104
+ collapses: raw[offset + 1],
1105
+ flips: raw[offset + 2],
1106
+ smoothed: raw[offset + 3],
1107
+ createdVertices: Uint32Array.from(raw.subarray(start, start + newCount)),
1108
+ removedVertices: Uint32Array.from(raw.subarray(start + newCount, start + newCount + removedCount))
1109
+ };
1110
+ }
1111
+ /** @internal The stepped mesh adds of `scene` (see {@link MeshAdds}); for the Worker engine. */
1112
+ function meshAdds(scene) {
1113
+ return meshAddsOf(scene);
1114
+ }
1115
+ /** Set by `Scene`'s static block. */
1116
+ let geodesicStepsOf;
1117
+ /** @internal The stepped geodesic queries of `scene` (see {@link GeodesicSteps}); for the Worker engine. */
1118
+ function geodesicSteps(scene) {
1119
+ return geodesicStepsOf(scene);
1120
+ }
1121
+ /**
1122
+ * A scene of editable meshes. Create it after `await init()`; release it with
1123
+ * {@link Scene.free} or a `using` declaration (otherwise it is freed when
1124
+ * garbage collected).
1125
+ *
1126
+ * Render views ({@link Scene.views}) point into WebAssembly memory and are
1127
+ * only valid until the next scene call that may allocate or move buffers: a
1128
+ * kept view may read other data or be empty. Re-acquire them after every
1129
+ * scene call; see {@link MeshViews}.
1130
+ */
1131
+ var Scene = class {
1132
+ #raw;
1133
+ #guard;
1134
+ /** Handles by `"index:generation"`, of live meshes and of those undo or redo can bring back. */
1135
+ #meshes = /* @__PURE__ */ new Map();
1136
+ /** A handle in `#meshes` may be of a mesh the history has dropped since. */
1137
+ #prune = false;
1138
+ /** Handles of meshes removed since the last `takeChanges`, for their removal records. */
1139
+ #removed = /* @__PURE__ */ new Map();
1140
+ /** The rule each coloured mesh was last given by `setColoring`. */
1141
+ #rules = /* @__PURE__ */ new WeakMap();
1142
+ /**
1143
+ * Field and section handles by raw id, kept for the scene's lifetime (raw
1144
+ * ids are never reused), so change records reporting a removed field or
1145
+ * section give back the handle the caller holds.
1146
+ */
1147
+ #fields = /* @__PURE__ */ new Map();
1148
+ #sections = /* @__PURE__ */ new Map();
1149
+ #listeners = /* @__PURE__ */ new Set();
1150
+ #permanentListeners = /* @__PURE__ */ new Set();
1151
+ /** The application's entries in the history. */
1152
+ #entries = new EntryBook();
1153
+ /** The latest entry's `coalesce` and the number the engine knows it by. */
1154
+ #coalesce = {
1155
+ key: "",
1156
+ id: 0
1157
+ };
1158
+ /** A {@link Scene.#settleHistory} is queued on a microtask. */
1159
+ #settleQueued = false;
1160
+ /** History step nesting depth, mirrored from the calls made through this class. */
1161
+ #stepDepth = 0;
1162
+ #drag;
1163
+ /**
1164
+ * Callable repair domain (`scene.repair(mesh, op)` and `scene.repair.<method>(...)`).
1165
+ */
1166
+ repair = createRepairDomain({
1167
+ repair: ((mesh, op) => this.#runRepair(mesh, op)),
1168
+ analyze: (mesh, options) => this.analyze(mesh, options),
1169
+ join: (target, source, options) => this.join(target, source, options),
1170
+ fillHoleContinuity: (mesh, loopIndex, options) => this.fillHoleContinuity(mesh, loopIndex, options),
1171
+ fillAllHolesContinuity: (mesh, options) => this.fillAllHolesContinuity(mesh, options),
1172
+ bridgePartialArcs: (mesh, loopA, loopB, options) => this.bridgePartialArcs(mesh, loopA, loopB, options),
1173
+ selectFacesScreen: (mesh, shape, options) => this.selectFacesScreen(mesh, shape, options),
1174
+ selectFacesInSphere: (mesh, center, radius, normalCone) => this.selectFacesInSphere(mesh, center, radius, normalCone),
1175
+ selectByCreaseAngle: (mesh, seedTri, maxDihedralRad) => this.selectByCreaseAngle(mesh, seedTri, maxDihedralRad),
1176
+ selectConnectedShell: (mesh, seedTri) => this.selectConnectedShell(mesh, seedTri),
1177
+ selectSmallFaceIslands: (mesh, maxFaceCount, maxArea) => this.selectSmallFaceIslands(mesh, maxFaceCount, maxArea),
1178
+ growFaceSelection: (mesh, selectedTris, rings, adjacency) => this.growFaceSelection(mesh, selectedTris, rings, adjacency),
1179
+ shrinkFaceSelection: (mesh, selectedTris, rings, adjacency) => this.shrinkFaceSelection(mesh, selectedTris, rings, adjacency),
1180
+ fillSelectionHoles: (mesh, selectedTris, maxHoleTris) => this.fillSelectionHoles(mesh, selectedTris, maxHoleTris),
1181
+ smoothSelectionBoundary: (mesh, selectedTris, iterations) => this.smoothSelectionBoundary(mesh, selectedTris, iterations),
1182
+ faceSelectionToVertexMask: (mesh, selectedTris) => this.faceSelectionToVertexMask(mesh, selectedTris),
1183
+ vertexMaskToFaceSelection: (mesh, mask, threshold, requireAllVertices) => this.vertexMaskToFaceSelection(mesh, mask, threshold, requireAllVertices),
1184
+ deleteSelectedFaces: (mesh, selectedTris) => this.deleteSelectedFaces(mesh, selectedTris),
1185
+ extractSelectedFaces: (mesh, selectedTris, options) => this.extractSelectedFaces(mesh, selectedTris, options),
1186
+ splitSelectedFaces: (mesh, selectedTris, options) => this.splitSelectedFaces(mesh, selectedTris, options)
1187
+ });
1188
+ /**
1189
+ * Callable sculpt domain (`scene.sculpt(mesh, op)` and `scene.sculpt.<method>(...)`).
1190
+ */
1191
+ sculpt = createSculptDomain({
1192
+ sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
1193
+ verticesInSphere: (mesh, center, radius) => this.verticesInSphere(mesh, center, radius),
1194
+ beginStep: () => this.beginStep(),
1195
+ endStep: () => this.endStep(),
1196
+ cancelStep: () => this.cancelStep(),
1197
+ applyDyntopo: (mesh, center, radius, options, pinned) => this.applyDyntopo(mesh, center, radius, options, pinned),
1198
+ dyntopoDab: (mesh, dab, options, protection) => this.dyntopoDab(mesh, dab, options, protection)
1199
+ });
1200
+ /** Remesh, simplification, subdivision, and volumetric reconstruction domain. */
1201
+ remesh = createRemeshDomain({ repair: ((mesh, op) => this.#runRepair(mesh, op)) });
1202
+ /** Callable boolean, cutting, trimming, offsetting, and shell domain. */
1203
+ boolean = createBooleanDomain({
1204
+ isAsync: false,
1205
+ repair: ((mesh, op) => this.#runRepair(mesh, op)),
1206
+ boolean: (target, source, op, options) => this.#runBoolean(target, source, op, options),
1207
+ booleanBatch: (meshesOrTree, treeOrOptions, maybeOptions) => Array.isArray(meshesOrTree) ? this.booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) : this.booleanBatch(meshesOrTree, treeOrOptions),
1208
+ cutByPlane: (mesh, plane, options) => this.cutByPlane(mesh, plane, options),
1209
+ trimByCurve: (mesh, optionsOrCurve, maybeOptions) => Array.isArray(optionsOrCurve) ? this.trimByCurve(mesh, optionsOrCurve, maybeOptions) : this.trimByCurve(mesh, optionsOrCurve),
1210
+ hollowMesh: (mesh, options) => this.hollowMesh(mesh, options),
1211
+ punchDrainHole: (mesh, options) => this.punchDrainHole(mesh, options),
1212
+ placeMesh: (target, stamp, options) => this.placeMesh(target, stamp, options)
1213
+ });
1214
+ /** Surface deformation and vertex-protection domain. */
1215
+ deform = createDeformDomain({
1216
+ sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
1217
+ buildFfdLattice: (mesh, dims, basis, padding) => this.buildFfdLattice(mesh, dims, basis, padding),
1218
+ applyFfd: (mesh, options) => this.applyFfd(mesh, options),
1219
+ applyArap: (mesh, options) => this.applyArap(mesh, options),
1220
+ applyKelvinlet: (mesh, options) => this.applyKelvinlet(mesh, options),
1221
+ applyXpbd: (mesh, options) => this.applyXpbd(mesh, options)
1222
+ });
1223
+ /** Defect analysis, metrology, queries, printability/quality/geodesic fields, paths, and section inspection domain. */
1224
+ inspect = createInspectDomain({
1225
+ analyze: (mesh, options) => this.analyze(mesh, options),
1226
+ measure: (mesh) => this.measure(mesh),
1227
+ bounds: (mesh) => this.bounds(mesh),
1228
+ raycast: (origin, direction, options) => this.raycast(origin, direction, options),
1229
+ closestPoint: (point, options) => this.closestPoint(point, options),
1230
+ meshDistance: (a, b, options) => this.meshDistance(a, b, options),
1231
+ intersects: (a, b) => this.intersects(a, b),
1232
+ selfIntersectingTriangles: (mesh) => this.selfIntersectingTriangles(mesh),
1233
+ findContacts: (options) => this.findContacts(options),
1234
+ overhangs: (mesh, options) => this.overhangs(mesh, options),
1235
+ triangleQuality: (mesh, metricOrOptions, sliverThreshold) => this.triangleQuality(mesh, metricOrOptions, sliverThreshold),
1236
+ meshDeviation: (source, target, options) => this.meshDeviation(source, target, options),
1237
+ geodesicDistances: (mesh, sources, options) => this.geodesicDistances(mesh, sources, options),
1238
+ releaseGeodesics: () => this.releaseGeodesics(),
1239
+ shortestSurfacePath: (mesh, sources, targetVertex, options) => this.shortestSurfacePath(mesh, sources, targetVertex, options),
1240
+ addDistanceField: (desc) => this.addDistanceField(desc),
1241
+ addThicknessField: (desc) => this.addThicknessField(desc),
1242
+ addCurvatureField: (desc) => this.addCurvatureField(desc),
1243
+ removeField: (field) => this.removeField(field),
1244
+ fieldValues: (field) => this.fieldValues(field),
1245
+ fieldNearest: (field) => this.fieldNearest(field),
1246
+ fieldStatus: (field) => this.fieldStatus(field),
1247
+ fieldTargetStatus: (field) => this.fieldTargetStatus(field),
1248
+ setColoring: (mesh, rule) => this.setColoring(mesh, rule),
1249
+ coloring: (mesh) => this.coloring(mesh),
1250
+ addSection: (desc) => this.addSection(desc),
1251
+ setSectionPlane: (section, plane) => this.setSectionPlane(section, plane),
1252
+ sectionPlane: (section) => this.sectionPlane(section),
1253
+ setSectionMeshes: (section, meshes) => this.setSectionMeshes(section, meshes),
1254
+ setSectionFill: (section, fill) => this.setSectionFill(section, fill),
1255
+ removeSection: (section) => this.removeSection(section),
1256
+ section: (section, mesh) => this.section(section, mesh),
1257
+ sectionGap: (section, a, b) => this.sectionGap(section, a, b),
1258
+ updateSections: () => this.updateSections(),
1259
+ fitPrimitive: (mesh, options) => this.fitPrimitive(mesh, options),
1260
+ alignToFittedPrimitive: (mesh, primitive, targetAxis, targetOrigin) => this.alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin),
1261
+ sliceContours: (mesh, origin, normal) => this.sliceContours(mesh, origin, normal),
1262
+ sliceContourStack: (mesh, origin, normal, spacing, count) => this.sliceContourStack(mesh, origin, normal, spacing, count),
1263
+ reconstructPointCloud: (cloud, options) => this.reconstructPointCloud(cloud, options)
1264
+ });
1265
+ /** Rigid registration, landmark SVD, multi-stage alignment, and symmetry detection domain. */
1266
+ align = createAlignDomain({
1267
+ register: (moving, fixed, options) => this.register(moving, fixed, options),
1268
+ alignByLandmarks: (moving, fixed, pairs, allowScaling) => this.alignByLandmarks(moving, fixed, pairs, allowScaling),
1269
+ registerMultistage: (moving, fixed, options) => this.registerMultistage(moving, fixed, options),
1270
+ detectSymmetryPlane: (mesh) => this.detectSymmetryPlane(mesh)
1271
+ });
1272
+ constructor(options = {}) {
1273
+ ensureInitialized("new Scene()");
1274
+ const budget = options.historyBudget === void 0 ? void 0 : checkHistoryBudget(options.historyBudget);
1275
+ const raw = call(() => new RawScene());
1276
+ this.#raw = raw;
1277
+ if (budget !== void 0) call(() => raw.set_history_budget(budget));
1278
+ this.#guard = options.debug ? new ViewGuard() : void 0;
1279
+ finalizer.register(this, this.#raw, this);
1280
+ }
1281
+ /** Releases the scene and everything in it. Later calls throw `INVALID_ARGUMENT`; calling it again does nothing. */
1282
+ free() {
1283
+ const raw = this.#raw;
1284
+ if (raw === void 0) return;
1285
+ this.#raw = void 0;
1286
+ this.#guard?.bump();
1287
+ this.#drag = void 0;
1288
+ this.#entries.dropAll();
1289
+ finalizer.unregister(this);
1290
+ release(raw);
1291
+ }
1292
+ /** Same as {@link Scene.free}, for `using scene = new Scene()`. */
1293
+ [Symbol.dispose]() {
1294
+ this.free();
1295
+ }
1296
+ /** The live raw scene, for a call that may allocate or move buffers. */
1297
+ #scene() {
1298
+ const s = this.#peek();
1299
+ this.#guard?.bump();
1300
+ if (!this.#settleQueued && (this.#permanentListeners.size > 0 || this.#entries.size > 0)) {
1301
+ this.#settleQueued = true;
1302
+ queueMicrotask(() => {
1303
+ this.#settleQueued = false;
1304
+ try {
1305
+ this.#settleHistory();
1306
+ } catch {}
1307
+ });
1308
+ }
1309
+ return s;
1310
+ }
1311
+ /** Tells the application's entries and the listeners what the history did since the last call. */
1312
+ #settleHistory() {
1313
+ const s = this.#raw;
1314
+ if (s === void 0) return;
1315
+ let permanent = [];
1316
+ if (call(() => s.has_permanent())) {
1317
+ this.#guard?.bump();
1318
+ const msg = call(() => s.take_permanent());
1319
+ permanent = decodePermanent(msg, (index, generation) => {
1320
+ const key = `${index}:${generation}`;
1321
+ return this.#meshes.get(key) ?? this.#removed.get(key);
1322
+ });
1323
+ }
1324
+ while (this.#raw === s) {
1325
+ const event = call(() => s.next_entry_event());
1326
+ if (event < 0) break;
1327
+ this.#entries.tell(Math.floor(event / 4), ENTRY_EVENTS[event % 4]);
1328
+ }
1329
+ tellPermanent(this.#permanentListeners, permanent);
1330
+ }
1331
+ /** The live raw scene, for a read-only call that leaves every view valid. */
1332
+ #peek() {
1333
+ if (this.#raw === void 0) throw invalid("scene is freed");
1334
+ return this.#raw;
1335
+ }
1336
+ /** The live mesh id of a handle of this scene. */
1337
+ #id(mesh) {
1338
+ this.#peek();
1339
+ const id = meshIds.get(mesh);
1340
+ if (id === void 0) throw invalid("not a mesh handle");
1341
+ if (id.scene !== this) throw invalid("mesh handle belongs to another scene");
1342
+ return id;
1343
+ }
1344
+ #meshHandle(index, generation) {
1345
+ const key = `${index}:${generation}`;
1346
+ let h = this.#meshes.get(key) ?? this.#removed.get(key);
1347
+ if (h === void 0) {
1348
+ h = new MeshHandle();
1349
+ meshIds.set(h, {
1350
+ scene: this,
1351
+ index,
1352
+ generation
1353
+ });
1354
+ this.#meshes.set(key, h);
1355
+ }
1356
+ return h;
1357
+ }
1358
+ #rawHandle(map, make, raw) {
1359
+ let h = map.get(raw);
1360
+ if (h === void 0) {
1361
+ h = make();
1362
+ rawIds.set(h, {
1363
+ scene: this,
1364
+ index: raw,
1365
+ generation: 0
1366
+ });
1367
+ map.set(raw, h);
1368
+ }
1369
+ return h;
1370
+ }
1371
+ /** The raw id of a field or section handle of this scene. */
1372
+ #rawId(handle, kind) {
1373
+ this.#peek();
1374
+ const what = kind === FieldHandle ? "field" : "section";
1375
+ const id = handle instanceof kind ? rawIds.get(handle) : void 0;
1376
+ if (id === void 0) throw invalid(`not a ${what} handle`);
1377
+ if (id.scene !== this) throw invalid(`${what} handle belongs to another scene`);
1378
+ return id.index;
1379
+ }
1380
+ #field(field) {
1381
+ return this.#rawId(field, FieldHandle);
1382
+ }
1383
+ #section(section) {
1384
+ return this.#rawId(section, SectionHandle);
1385
+ }
1386
+ /** Meshes as the binding's flat `[index, generation, ...]` list. */
1387
+ #flatIds(meshes) {
1388
+ if (!Array.isArray(meshes)) throw invalid("meshes must be an array of mesh handles");
1389
+ const out = new Uint32Array(meshes.length * 2);
1390
+ meshes.forEach((m, k) => {
1391
+ const { index, generation } = this.#id(m);
1392
+ out[2 * k] = index;
1393
+ out[2 * k + 1] = generation;
1394
+ });
1395
+ return out;
1396
+ }
1397
+ /** `[origin, normal]` as the binding's 6 numbers. */
1398
+ #plane(plane) {
1399
+ if (plane?.origin?.length !== 3 || plane.normal?.length !== 3) throw invalid("plane needs a 3-number origin and normal");
1400
+ return Float64Array.from([...plane.origin, ...plane.normal]);
1401
+ }
1402
+ /**
1403
+ * Adds a mesh from world positions. They are stored as `p − origin` in
1404
+ * `f32` (see {@link AddMeshOptions.origin}); the placement starts as the
1405
+ * identity, so {@link Scene.matrix4} maps the local coordinates back to
1406
+ * where they were given.
1407
+ *
1408
+ * @throws `INVALID_ARGUMENT` for bad lengths or options (`uvs` not 2 finite
1409
+ * values per vertex included), `INVALID_INDEX` for an index out of range.
1410
+ */
1411
+ addMesh(positions, indices, options = {}) {
1412
+ const s = this.#scene();
1413
+ const mode = modeCode(options.mode ?? "eager");
1414
+ const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
1415
+ const p = toFloat64(positions);
1416
+ const i = toUint32(indices);
1417
+ const normals = options.normals ?? true;
1418
+ const uvs = options.uvs === void 0 || options.uvs instanceof Float32Array ? options.uvs : Float32Array.from(options.uvs);
1419
+ const id = call(() => {
1420
+ if (options.undoable === true) return s.add_mesh_undoable(p, i, uvs, origin, mode, normals);
1421
+ return uvs === void 0 ? s.add_mesh(p, i, origin, mode, normals) : s.add_mesh_with_uvs(p, i, uvs, origin, mode, normals);
1422
+ });
1423
+ return this.#meshHandle(id[0], id[1]);
1424
+ }
1425
+ /**
1426
+ * Removes a mesh. Its handle then gives `UNKNOWN_MESH`. An active drag of
1427
+ * the mesh is ended first, closing its step; the mesh's history entries
1428
+ * (the drag's included) are then dropped with it.
1429
+ *
1430
+ * With `undoable` the removal is an undo step (or part of the open one)
1431
+ * and the history stays: {@link Scene.undo} brings the mesh back with the
1432
+ * same handle, its data, placement, display (normals, colouring), the
1433
+ * fields on it and its collision rules (a rule once both its meshes are
1434
+ * back). Nothing is copied, whatever the mesh's size. What belongs to other
1435
+ * meshes is cut as by any removal and does not come back: fields on other
1436
+ * meshes measured to it, and its section entries. The kept mesh counts
1437
+ * against the history's memory budget, and is freed once the history drops
1438
+ * the step (see {@link Scene.isRestorable}). A removal larger than the
1439
+ * whole budget is permanent: {@link Scene.removalBytes} tells before,
1440
+ * {@link Scene.onPermanent} after.
1441
+ */
1442
+ removeMesh(mesh, options = {}) {
1443
+ const { index, generation } = this.#id(mesh);
1444
+ if (this.#drag?.mesh === mesh) this.#drag.end();
1445
+ if (options.undoable === true) {
1446
+ call(() => this.#scene().remove_mesh_undoable(index, generation));
1447
+ this.#settleHistory();
1448
+ this.#prune = true;
1449
+ return;
1450
+ }
1451
+ call(() => this.#scene().remove_mesh(index, generation));
1452
+ const key = `${index}:${generation}`;
1453
+ this.#meshes.delete(key);
1454
+ this.#removed.set(key, mesh);
1455
+ this.#settleHistory();
1456
+ }
1457
+ /** Whether the scene has `mesh`: `false` once it is removed, or its add is undone. */
1458
+ has(mesh) {
1459
+ const { index, generation } = this.#id(mesh);
1460
+ return this.#peek().has_mesh(index, generation);
1461
+ }
1462
+ /**
1463
+ * Whether undo or redo can still bring back `mesh`: it was removed with
1464
+ * `undoable`, or its undoable add was undone, and the history has not
1465
+ * dropped the step (its memory budget, {@link Scene.clearHistory}, or a
1466
+ * new step after an undone add). `false` for a mesh in the scene.
1467
+ */
1468
+ isRestorable(mesh) {
1469
+ const { index, generation } = this.#id(mesh);
1470
+ return this.#peek().is_restorable(index, generation);
1471
+ }
1472
+ /**
1473
+ * About the bytes of history an undoable {@link Scene.removeMesh} of `mesh`
1474
+ * takes. One larger than {@link Scene.historyBudget} is permanent.
1475
+ *
1476
+ * @example
1477
+ * ```ts
1478
+ * if (scene.removalBytes(mesh) <= scene.historyBudget() || confirm("Remove for good?")) {
1479
+ * scene.removeMesh(mesh, { undoable: true });
1480
+ * }
1481
+ * ```
1482
+ */
1483
+ removalBytes(mesh) {
1484
+ const { index, generation } = this.#id(mesh);
1485
+ return call(() => this.#peek().removal_bytes(index, generation));
1486
+ }
1487
+ /**
1488
+ * Joins `source` into `target`: copies the source's geometry into the
1489
+ * target (keeping its world shape), bridges `options.loopA` to the copied
1490
+ * `options.loopB`, and removes the source. All of it is one undo step:
1491
+ * {@link Scene.undo} restores the target and brings the source back with
1492
+ * the same handle, as for {@link Scene.removeMesh} with `undoable` (what
1493
+ * comes back with it, and the memory it takes, are described there). A drag
1494
+ * of the source ends first, recording its moves as one step, so they
1495
+ * survive a failed join.
1496
+ *
1497
+ * @deprecated Use `scene.repair.join()` instead.
1498
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for one
1499
+ * mesh twice or loops that cannot bridge; `STALE_LOOPS` for a loop that is
1500
+ * not there. A failed join changes nothing.
1501
+ */
1502
+ join(target, source, options) {
1503
+ const ta = this.#id(target);
1504
+ const sb = this.#id(source);
1505
+ const loops = [];
1506
+ encodeLoopId(options.loopA, loops);
1507
+ encodeLoopId(options.loopB, loops);
1508
+ const maxEdges = optional(options.maxEdges, "maxEdges");
1509
+ if (this.#drag?.mesh === source) this.#drag.end();
1510
+ const r = call(() => this.#scene().join(ta.index, ta.generation, sb.index, sb.generation, Uint32Array.from(loops), maxEdges));
1511
+ this.#settleHistory();
1512
+ this.#prune = true;
1513
+ return {
1514
+ verticesAdded: r[0],
1515
+ trianglesAdded: r[1],
1516
+ bridgeTrianglesAdded: r[2]
1517
+ };
1518
+ }
1519
+ /**
1520
+ * Cuts `mesh` with a world `plane`: the `+` side
1521
+ * (`signedDistance >= 0`) stays on the mesh and the `-` side is added as
1522
+ * a new mesh with the same placement, so the world shape is kept.
1523
+ * Cutting a closed mesh with `cap` (the default) yields two closed
1524
+ * meshes, capped with flat, unfaired patches. On a mesh with UVs, closed
1525
+ * means closed by exact position, so seams count as closed: the cap's UVs
1526
+ * come from the rim and blend across a seam. A rim that runs into a real
1527
+ * boundary of an open mesh stays open. A mesh without UVs is read by vertex
1528
+ * index, so its split vertices are such a boundary: weld it first.
1529
+ *
1530
+ * The cut and the added mesh are one undo step: undo restores the mesh
1531
+ * and removes the added one, redo brings it back with the same handle.
1532
+ *
1533
+ * @deprecated Use `scene.boolean.cut()` instead.
1534
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` when
1535
+ * the plane does not cut the mesh or a rim cannot be capped, as listed in
1536
+ * `docs/uv-channel.md`, for example a rim that closes by position with its
1537
+ * walls wound against each other. A failed cut changes nothing.
1538
+ */
1539
+ cutByPlane(mesh, plane, options) {
1540
+ const { index, generation } = this.#id(mesh);
1541
+ const p = this.#plane(plane);
1542
+ const r = call(() => this.#scene().cut_by_plane(index, generation, p, options?.cap ?? true));
1543
+ return {
1544
+ kept: this.#meshHandle(r[0], r[1]),
1545
+ removed: this.#meshHandle(r[2], r[3]),
1546
+ keptTriangles: r[4],
1547
+ removedTriangles: r[5],
1548
+ capTriangles: r[6]
1549
+ };
1550
+ }
1551
+ /**
1552
+ * Combines `source` into `target` in the world: the union, subtraction
1553
+ * (`target` minus `source`) or intersection. Returns `target`, now
1554
+ * holding the result with its placement; `source` is unchanged.
1555
+ *
1556
+ * Both meshes must be closed and manifold. The boolean undoes in one
1557
+ * step. Combining a mesh with itself is a no-op for `"union"` and
1558
+ * `"intersect"`, and clears it for `"subtract"`.
1559
+ *
1560
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for an
1561
+ * input that is not closed, manifold and consistently wound. A failed
1562
+ * boolean changes nothing.
1563
+ */
1564
+ #runBoolean(target, source, op, options) {
1565
+ const ta = this.#id(target);
1566
+ const sb = this.#id(source);
1567
+ const norm = normalizeBooleanArgs(op, options);
1568
+ const r = options === void 0 ? call(() => this.#scene().boolean(ta.index, ta.generation, sb.index, sb.generation, BOOLEAN_OP_CODES[norm.op])) : call(() => this.#scene().boolean_with_options(ta.index, ta.generation, sb.index, sb.generation, BOOLEAN_OP_CODES[norm.op], BOOLEAN_METHOD_CODES[norm.method], optional(norm.coplanarTolerance, "coplanarTolerance"), norm.snapSlivers, optional(norm.voxelPitch, "voxelPitch"), optional(norm.maxTriangles, "maxTriangles")));
1569
+ return this.#meshHandle(r[0], r[1]);
1570
+ }
1571
+ booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) {
1572
+ const { meshes, tree, options } = normalizeCsgBatchArgs(meshesOrTree, treeOrOptions, maybeOptions);
1573
+ const ids = this.#flatIds(meshes);
1574
+ const encodedTree = Float64Array.from(encodeCsgTree(tree));
1575
+ const r = call(() => this.#scene().boolean_batch(ids, encodedTree, BOOLEAN_OP_CODES[options.op], BOOLEAN_METHOD_CODES[options.method], optional(options.coplanarTolerance, "coplanarTolerance"), options.snapSlivers, optional(options.voxelPitch, "voxelPitch"), optional(options.maxTriangles, "maxTriangles")));
1576
+ return this.#meshHandle(r[0], r[1]);
1577
+ }
1578
+ /**
1579
+ * Adds the convex hull of `meshes` (one mesh or several) as a new mesh and
1580
+ * returns it with its counts. The hull is built from the vertices the
1581
+ * meshes' live triangles use; the meshes are not changed.
1582
+ *
1583
+ * The hull is exact (no tolerance): every vertex is inside it or on its
1584
+ * boundary, and it is convex, closed and wound outward, with no
1585
+ * degenerate triangle. Its vertices are input vertices, including every
1586
+ * corner. Duplicate, coplanar and collinear vertices are fine.
1587
+ *
1588
+ * When every mesh has the same placement (one mesh, say), the hull is built
1589
+ * in their own space and the new mesh gets that placement, so it moves
1590
+ * with them; with one origin too, its vertices are exactly theirs.
1591
+ * Otherwise it is built in world space at the identity placement.
1592
+ *
1593
+ * The new mesh is added as one undo step: {@link Scene.undo} removes it and
1594
+ * {@link Scene.redo} brings it back with the same handle.
1595
+ *
1596
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty list or when the
1597
+ * vertices have no volume (all on one point, line or plane; the message
1598
+ * says which), `UNKNOWN_MESH` for a removed mesh.
1599
+ */
1600
+ convexHull(meshes, options) {
1601
+ const ids = this.#flatIds(hullMeshList(meshes));
1602
+ const normals = hullNormals(options);
1603
+ const r = call(() => this.#scene().convex_hull(ids, normals));
1604
+ return {
1605
+ mesh: this.#meshHandle(r[0], r[1]),
1606
+ ...decodeHullCounts(r)
1607
+ };
1608
+ }
1609
+ /**
1610
+ * Adds the convex hull of world `points` (flat positions or a packed point
1611
+ * cloud) as a new mesh at the identity placement, and returns it with its
1612
+ * counts. Exact and one undo step, as for {@link Scene.convexHull}.
1613
+ *
1614
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for fewer than four points, a
1615
+ * value that is not a finite number (or beyond `1e100`), or points without
1616
+ * volume (all on one point, line or plane; the message says which).
1617
+ */
1618
+ convexHullOfPoints(points, options) {
1619
+ const buf = hullPointsBuffer(points);
1620
+ const normals = hullNormals(options);
1621
+ const r = call(() => this.#scene().convex_hull_points(buf, normals));
1622
+ return {
1623
+ mesh: this.#meshHandle(r[0], r[1]),
1624
+ ...decodeHullCounts(r)
1625
+ };
1626
+ }
1627
+ /**
1628
+ * Fits a height map's frame to `meshes` (one mesh or several): an
1629
+ * orthographic image of square pixels looking along `options.direction`,
1630
+ * centred on the meshes, with their height range. `heightMap` samples it.
1631
+ *
1632
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty list, meshes
1633
+ * without a triangle or without an extent across the direction, an option
1634
+ * out of range, or an image over {@link MAX_HEIGHT_MAP_PIXELS};
1635
+ * `UNKNOWN_MESH` for a removed mesh.
1636
+ */
1637
+ heightMapFrame(meshes, options) {
1638
+ const ids = this.#flatIds(heightMapMeshList(meshes));
1639
+ const values = Float64Array.from(encodeHeightMapOptions(options));
1640
+ return decodeHeightMapFrame(call(() => this.#scene().height_map_frame(ids, values)));
1641
+ }
1642
+ /**
1643
+ * An orthographic depth image of `meshes` (one mesh or several, in their
1644
+ * placements): the height of each pixel above the frame's zero plane, NaN
1645
+ * where no surface is seen. A pixel's ray runs through its centre and takes
1646
+ * the first surface within the frame's range (either side of a triangle);
1647
+ * a ray exactly through an edge or vertex takes the nearest of the triangles
1648
+ * meeting there, so a watertight mesh has no cracks.
1649
+ *
1650
+ * `frame` is a frame (from {@link Scene.heightMapFrame}, say), or the options
1651
+ * to fit one with. `rows` samples a band of the image's rows, `[first, end)`:
1652
+ * the bands of an image hold exactly what sampling it whole would, so a large
1653
+ * image can be taken in steps.
1654
+ *
1655
+ * `addHeightfield` with the heights, the frame's pixel size and
1656
+ * `heightMapPlacement(frame)` makes a relief that lies on the surface seen.
1657
+ *
1658
+ * @example
1659
+ * ```ts
1660
+ * const { frame, heights } = scene.heightMap(mesh, { direction: [0, 0, -1], resolution: 1024 });
1661
+ * ```
1662
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty list, an invalid
1663
+ * frame, rows outside it, or as for {@link Scene.heightMapFrame};
1664
+ * `UNKNOWN_MESH` for a removed mesh, `STALE_BVH` for a stale manual mesh.
1665
+ */
1666
+ heightMap(meshes, frame, rows) {
1667
+ const ids = this.#flatIds(heightMapMeshList(meshes));
1668
+ let raw;
1669
+ if (isHeightMapFrame(frame)) raw = Float64Array.from(encodeHeightMapFrame(frame));
1670
+ else {
1671
+ const options = Float64Array.from(encodeHeightMapOptions(frame));
1672
+ raw = call(() => this.#scene().height_map_frame(ids, options));
1673
+ }
1674
+ const fitted = decodeHeightMapFrame(raw);
1675
+ const [first, end] = checkHeightMapRows(rows, fitted.height);
1676
+ const heights = call(() => this.#scene().height_map(ids, raw, first, end));
1677
+ return {
1678
+ frame: fitted,
1679
+ rows: [first, end],
1680
+ heights
1681
+ };
1682
+ }
1683
+ /**
1684
+ * Adds the relief of a grid of heights as a new mesh and returns it with its
1685
+ * counts: a closed, outward-wound solid from a flat base up to the heights,
1686
+ * with a vertex per sample at exactly its height (see `generateHeightfield`
1687
+ * for its frame). The buffers never leave the engine, so large reliefs cost
1688
+ * no copy on this side.
1689
+ *
1690
+ * The new mesh is added as one undo step: {@link Scene.undo} removes it and
1691
+ * {@link Scene.redo} brings it back with the same handle.
1692
+ *
1693
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for fewer than 2 samples on a
1694
+ * side, a wrong number of heights, a height that is infinite or not above
1695
+ * `-base`, or an invalid placement; `OUT_OF_MEMORY` when the relief does
1696
+ * not fit.
1697
+ */
1698
+ addHeightfield(field, options) {
1699
+ const f = checkHeightfield(field);
1700
+ const p = checkHeightfieldPlacement(options);
1701
+ const values = encodeHeightfield(f);
1702
+ const rotation = Float64Array.from(p.rotation);
1703
+ const translation = Float64Array.from(p.translation);
1704
+ const scale = p.scale === void 0 ? void 0 : Float64Array.from(p.scale);
1705
+ const r = call(() => this.#scene().add_heightfield(f.heights, f.width, f.height, values, rotation, translation, scale, p.normals));
1706
+ return {
1707
+ mesh: this.#meshHandle(r[0], r[1]),
1708
+ vertices: r[2],
1709
+ triangles: r[3]
1710
+ };
1711
+ }
1712
+ /**
1713
+ * Smooths noise (from a scan, say) out of `mesh` while keeping its sharp
1714
+ * features, as one undo step: the face normals are filtered over their
1715
+ * neighbours, except across edges sharper than `featureAngle`, and the
1716
+ * vertices move to fit them. Flat faces become flat again and the edges
1717
+ * between them stay sharp. The triangles and UVs are kept.
1718
+ *
1719
+ * With `region` (a face selection), only those triangles are smoothed and
1720
+ * no vertex that another triangle uses moves. The report has the
1721
+ * surface's readouts before and after. Nothing is recorded when nothing
1722
+ * moves.
1723
+ *
1724
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an option out of range or
1725
+ * a dead or out-of-range triangle in `region`, `UNKNOWN_MESH` for a
1726
+ * removed mesh. Nothing changes then.
1727
+ */
1728
+ denoise(mesh, options) {
1729
+ const { index, generation } = this.#id(mesh);
1730
+ const o = checkDenoiseOptions(options);
1731
+ const raw = call(() => this.#scene().denoise(index, generation, o.iterations ?? NaN, o.strength ?? NaN, o.featureAngle ?? NaN, o.region));
1732
+ return decodeDenoiseReport(raw);
1733
+ }
1734
+ /**
1735
+ * Improves `mesh`'s triangles without moving a vertex, as one undo step:
1736
+ * flips edges towards a Delaunay triangulation wherever that takes the
1737
+ * surface at most `dihedralLimit` degrees from what it was. Edges sharper
1738
+ * than the limit never flip, and the smallest corner angle never drops.
1739
+ * UVs are kept.
1740
+ *
1741
+ * With `region` (a face selection), only edges between two of its
1742
+ * triangles flip. The report has the surface's readouts before and after.
1743
+ * Nothing is recorded when nothing flips.
1744
+ *
1745
+ * @throws {FastMeshError} as {@link Scene.denoise}.
1746
+ */
1747
+ delaunayFlips(mesh, options) {
1748
+ const { index, generation } = this.#id(mesh);
1749
+ const o = checkDelaunayFlipOptions(options);
1750
+ const raw = call(() => this.#scene().delaunay_flips(index, generation, o.dihedralLimit ?? NaN, o.region));
1751
+ return decodeDelaunayFlipReport(raw);
1752
+ }
1753
+ /**
1754
+ * Plans the voxel grid of {@link Scene.wrap} for the same meshes and
1755
+ * options without running it: its dimensions, voxel size, voxel count and
1756
+ * estimated memory, and whether it is within `maxVoxels`. Cheap (one pass
1757
+ * over the vertices), so it can follow a settings form.
1758
+ *
1759
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty list, bad options,
1760
+ * meshes without triangles, or a voxel size that `f32` positions cannot
1761
+ * resolve; `UNKNOWN_MESH` for a removed mesh. A grid over the limit is not
1762
+ * an error here: it comes back with `fits: false`.
1763
+ */
1764
+ wrapPlan(meshes, options) {
1765
+ const ids = this.#flatIds(wrapMeshList(meshes));
1766
+ const values = encodeWrapOptions(checkWrapOptions(options));
1767
+ return decodeWrapPlan(call(() => this.#scene().wrap_plan(ids, values)));
1768
+ }
1769
+ /**
1770
+ * Wraps `meshes` (one mesh or several) in one closed envelope, added as a
1771
+ * new mesh, and returns it with its counts. A robust last resort for broken
1772
+ * scans and merged parts: the meshes may be open, holed, overlapping,
1773
+ * self-intersecting or wound either way, and are not changed.
1774
+ *
1775
+ * The envelope is closed, manifold, wound outward and free of
1776
+ * self-intersections. Gaps, slots and holes narrower than `gap` are closed,
1777
+ * and interior cavities are filled. Every vertex is within about half the
1778
+ * gap (and a voxel) of the meshes. It is built on a voxel grid: features
1779
+ * thinner than a voxel may be lost, and sharp edges are cut by up to a voxel,
1780
+ * less with `project`. A shell with a hole wider than the gap is open to the
1781
+ * outside, so its inside is not filled and its walls, with no thickness,
1782
+ * are lost: raise the gap over the hole. {@link Scene.wrapPlan} reports the
1783
+ * grid and its memory beforehand, and a grid over `maxVoxels` is refused.
1784
+ *
1785
+ * When every mesh has the same placement and it has no scale, the wrap is
1786
+ * built in their own space and the new mesh gets that placement; otherwise
1787
+ * it is built in world space at the identity placement. Lengths are world
1788
+ * units either way.
1789
+ *
1790
+ * The new mesh is added as one undo step: {@link Scene.undo} removes it and
1791
+ * {@link Scene.redo} brings it back with the same handle.
1792
+ *
1793
+ * At a million triangles this takes from about half a second to many
1794
+ * seconds, by detail and threads: use `WorkerScene.wrap` to keep the page
1795
+ * live.
1796
+ *
1797
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty list, bad options,
1798
+ * a grid over `maxVoxels` (the message has its size and memory), or meshes
1799
+ * that enclose no volume at this gap and voxel size (a flat sheet, or a
1800
+ * shell with a hole wider than the gap); `UNKNOWN_MESH` for a removed mesh;
1801
+ * `OUT_OF_MEMORY`.
1802
+ */
1803
+ wrap(meshes, options) {
1804
+ const ids = this.#flatIds(wrapMeshList(meshes));
1805
+ const checked = checkWrapOptions(options);
1806
+ const r = call(() => this.#scene().wrap_meshes(ids, encodeWrapOptions(checked), checked.normals));
1807
+ return {
1808
+ mesh: this.#meshHandle(r[0], r[1]),
1809
+ ...decodeWrapCounts(r)
1810
+ };
1811
+ }
1812
+ trimByCurve(mesh, optionsOrCurve, maybeOptions) {
1813
+ const { index, generation } = this.#id(mesh);
1814
+ const norm = normalizeTrimCurveArgs(optionsOrCurve, maybeOptions);
1815
+ const flatPoints = Float64Array.from(norm.points.flat());
1816
+ const r = call(() => this.#scene().trim_by_curve(index, generation, flatPoints, norm.closed, norm.deleteInside, optional(norm.snapTolerance, "snapTolerance")));
1817
+ return {
1818
+ kept: this.#meshHandle(r[0], r[1]),
1819
+ trianglesAdded: r[2],
1820
+ trianglesRemoved: r[3],
1821
+ imprintTriangles: r[4],
1822
+ cutTriangles: r[5],
1823
+ removedArea: r[6],
1824
+ verticesAdded: r[7],
1825
+ seamEdges: r[8]
1826
+ };
1827
+ }
1828
+ /**
1829
+ * Fills a single boundary loop with selectable continuity (`"flat"`, `"tangent"`, or `"curvature"`)
1830
+ * and nested island detection (one undo step).
1831
+ */
1832
+ fillHoleContinuity(mesh, loopIndex, options = {}) {
1833
+ const { index, generation } = this.#id(mesh);
1834
+ const loopIdx = checkU32Int(loopIndex, "loopIndex");
1835
+ const norm = normalizeFillHolesContinuityOptions(options);
1836
+ return decodeFillContinuityStats(call(() => this.#scene().fill_hole_continuity(index, generation, loopIdx, FILL_CONTINUITY_CODES[norm.continuity], optional(norm.maxHolePerimeter, "maxHolePerimeter"), optional(norm.maxHoleVertices, "maxHoleVertices"), norm.refinePatch, optional(norm.smoothIterations, "smoothIterations"), norm.detectIslands)));
1837
+ }
1838
+ /**
1839
+ * Fills all eligible boundary loops with selectable continuity (one undo step).
1840
+ */
1841
+ fillAllHolesContinuity(mesh, options = {}) {
1842
+ const { index, generation } = this.#id(mesh);
1843
+ const norm = normalizeFillHolesContinuityOptions(options);
1844
+ return decodeFillContinuityStats(call(() => this.#scene().fill_all_holes_continuity(index, generation, FILL_CONTINUITY_CODES[norm.continuity], optional(norm.maxHolePerimeter, "maxHolePerimeter"), optional(norm.maxHoleVertices, "maxHoleVertices"), norm.refinePatch, optional(norm.smoothIterations, "smoothIterations"), norm.detectIslands)));
1845
+ }
1846
+ /**
1847
+ * Bridges two boundary arcs (resolved from `loopA`/`loopB` vertex arrays when non-empty,
1848
+ * or via `options.loopAIndex`/`arcARange` and `loopBIndex`/`arcBRange`) in one undo step.
1849
+ */
1850
+ bridgePartialArcs(mesh, loopA = [], loopB = [], options = {}) {
1851
+ const { index, generation } = this.#id(mesh);
1852
+ const vertsA = normalizeU32List(loopA, "loopA");
1853
+ const vertsB = normalizeU32List(loopB, "loopB");
1854
+ const norm = normalizePartialBridgeOptions(options);
1855
+ const raw = call(() => this.#scene().bridge_partial_arcs(index, generation, Uint32Array.from(vertsA), Uint32Array.from(vertsB), norm.loopAIndex, norm.arcARange[0], norm.arcARange[1], norm.loopBIndex, norm.arcBRange[0], norm.arcBRange[1], norm.twistOffset, optional(norm.subdivisions, "subdivisions")));
1856
+ return {
1857
+ trianglesAdded: raw[0],
1858
+ verticesAdded: raw[1],
1859
+ resultingLoops: raw[2],
1860
+ arcAVertices: raw[3],
1861
+ arcBVertices: raw[4]
1862
+ };
1863
+ }
1864
+ /**
1865
+ * Applies localized dynamic topology remeshing inside sphere `(center, radius)`,
1866
+ * locking any `pinned` vertex IDs (one undo step).
1867
+ */
1868
+ applyDyntopo(mesh, center, radius, options = {}, pinned = []) {
1869
+ const { index, generation } = this.#id(mesh);
1870
+ const cr = normalizeDyntopoCenterRadius(center, radius);
1871
+ const norm = normalizeDyntopoOptions(options);
1872
+ const pinnedList = normalizeU32List(pinned, "pinned");
1873
+ return decodeDyntopoPatch(call(() => this.#scene().apply_dyntopo(index, generation, Float64Array.from(cr.center), cr.radius, DYNTOPO_MODE_CODES[norm.mode], optional(norm.detailSize, "detailSize"), optional(norm.minDetailRatio, "minDetailRatio"), optional(norm.maxDetailRatio, "maxDetailRatio"), norm.equalizeValence, norm.smoothTangent, Uint32Array.from(pinnedList))), 0);
1874
+ }
1875
+ /**
1876
+ * Applies localized dynamic topology remeshing followed by a brush dab (with optional
1877
+ * `protection`), coalescing cleanly inside an active `beginStep`/`endStep`.
1878
+ */
1879
+ dyntopoDab(mesh, dab, options = {}, protection) {
1880
+ const { index, generation } = this.#id(mesh);
1881
+ if (!isBrushSculptOp(dab)) throw invalid("dyntopoDab requires a brush sculpt operation");
1882
+ const norm = normalizeDyntopoOptions(options);
1883
+ const encoded = encodeRepair([protection !== void 0 ? {
1884
+ ...dab,
1885
+ protect: protection
1886
+ } : dab]);
1887
+ const raw = call(() => this.#scene().dyntopo_dab(index, generation, encoded.values, DYNTOPO_MODE_CODES[norm.mode], optional(norm.detailSize, "detailSize"), optional(norm.minDetailRatio, "minDetailRatio"), optional(norm.maxDetailRatio, "maxDetailRatio"), norm.equalizeValence, norm.smoothTangent));
1888
+ return {
1889
+ moved: raw[0],
1890
+ maxDisplacement: raw[1],
1891
+ ...decodeDyntopoPatch(raw, 2)
1892
+ };
1893
+ }
1894
+ /**
1895
+ * Rigidly aligns the mesh `moving` to the mesh `fixed` by point-to-plane ICP,
1896
+ * with the closest points found through `fixed`'s BVH and trimmed by
1897
+ * `options.overlap`. A drag of either mesh ends first, recording its moves
1898
+ * as one step, once the arguments have been checked.
1899
+ *
1900
+ * **The initial guess is the current placements.** ICP finds the nearest
1901
+ * fit, so put the meshes roughly in place first with `setPlacement`.
1902
+ *
1903
+ * **Applying.** By default a good result becomes `moving`'s placement as one
1904
+ * undo step (`applied` in the result): converged, with `rmse` within `maxRmse`
1905
+ * and enough points in range. Otherwise nothing moves, and `notApplied` says
1906
+ * why; `placement` still holds the estimate, for `setPlacement` if it will do.
1907
+ * `apply: false` only returns it.
1908
+ *
1909
+ * **Undetermined poses.** A plane's slide and a sphere's or a cylinder's spin
1910
+ * are not fixed by the data, though facets or noise can let the iteration
1911
+ * settle with a tiny `rmse`. These report `"underconstrained"` and list the
1912
+ * motions in `undetermined`. So do coarse regular meshes with exact fits close
1913
+ * by: a 16-sided sphere fits every 22.5 degrees. The check is local, so a
1914
+ * cube's 90-degree symmetry does not count. It adds a bounded cost: up to 12
1915
+ * restarts of up to 12 steps on at most 10,000 points.
1916
+ *
1917
+ * **Scales.** Only rotation and translation are solved. `moving`'s scale is
1918
+ * applied to its points and kept. `fixed`'s scale, uniform or not, is
1919
+ * followed exactly on a copy baked through it, so each such call costs a BVH
1920
+ * build. All distances are in world units.
1921
+ *
1922
+ * @deprecated Use `scene.align.register()` instead.
1923
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for one
1924
+ * mesh twice, a mesh without triangles or an invalid option; `STALE_BVH` for
1925
+ * a stale Manual `fixed`. Bad options and one mesh twice change nothing,
1926
+ * and a drag keeps running. The other errors come after a drag has ended, and
1927
+ * change nothing else.
1928
+ */
1929
+ register(moving, fixed, options = {}) {
1930
+ const m = this.#id(moving);
1931
+ const f = this.#id(fixed);
1932
+ checkRegisterOptions(moving === fixed, options);
1933
+ const maxIterations = optional(options.maxIterations, "maxIterations");
1934
+ const tolerance = optional(options.tolerance, "tolerance");
1935
+ const overlap = optional(options.overlap, "overlap");
1936
+ const maxDistance = optional(options.maxDistance, "maxDistance");
1937
+ const maxSamples = optional(options.maxSamples, "maxSamples");
1938
+ const maxRmse = optional(options.maxRmse, "maxRmse");
1939
+ const apply = options.apply ?? true;
1940
+ if (this.#drag?.mesh === moving || this.#drag?.mesh === fixed) this.#drag.end();
1941
+ const r = call(() => this.#scene().register(m.index, m.generation, f.index, f.generation, maxIterations, tolerance, overlap, maxDistance, maxSamples, apply, maxRmse));
1942
+ const status = REGISTER_STATUSES[r[17]];
1943
+ const undetermined = [];
1944
+ for (let at = 24; at < r.length; at += 10) undetermined.push({
1945
+ translation: vec3At(r, at),
1946
+ rotation: vec3At(r, at + 3),
1947
+ about: vec3At(r, at + 6),
1948
+ alternativeRmse: r[at + 9]
1949
+ });
1950
+ return {
1951
+ placement: {
1952
+ rotation: Array.from(r.subarray(0, 9)),
1953
+ translation: [
1954
+ r[9],
1955
+ r[10],
1956
+ r[11]
1957
+ ],
1958
+ scale: [
1959
+ r[12],
1960
+ r[13],
1961
+ r[14]
1962
+ ]
1963
+ },
1964
+ rmse: r[15],
1965
+ iterations: r[16],
1966
+ converged: status === "converged",
1967
+ status,
1968
+ applied: r[18] === 1,
1969
+ samples: r[19],
1970
+ inliers: r[20],
1971
+ conditioning: r[21],
1972
+ notApplied: REGISTER_NOT_APPLIED[r[22]],
1973
+ maxRmse: r[23],
1974
+ undetermined
1975
+ };
1976
+ }
1977
+ /**
1978
+ * Aligns `moving` onto `fixed` from N corresponding world-space landmark pairs
1979
+ * using Umeyama SVD (one undo step).
1980
+ */
1981
+ alignByLandmarks(moving, fixed, pairs, allowScaling = false) {
1982
+ const m = this.#id(moving);
1983
+ const f = this.#id(fixed);
1984
+ const norm = normalizeLandmarkPairs(moving === fixed, pairs, allowScaling);
1985
+ if (this.#drag?.mesh === moving || this.#drag?.mesh === fixed) this.#drag.end();
1986
+ const r = call(() => this.#scene().align_by_landmarks(m.index, m.generation, f.index, f.generation, norm.sourcePoints, norm.targetPoints, norm.allowScaling));
1987
+ return {
1988
+ placement: {
1989
+ rotation: Array.from(r.subarray(0, 9)),
1990
+ translation: vec3At(r, 9),
1991
+ scale: vec3At(r, 12)
1992
+ },
1993
+ scale: r[15],
1994
+ rmse: r[16]
1995
+ };
1996
+ }
1997
+ /**
1998
+ * Runs coarse pre-alignment (PCA centroid or OBB) followed by iterative ICP
1999
+ * with selectable error objective (`pointToPoint`, `pointToPlane`, or
2000
+ * `symmetricNormal`) and applies the placement to `moving` (one undo step).
2001
+ */
2002
+ registerMultistage(moving, fixed, options = {}) {
2003
+ const m = this.#id(moving);
2004
+ const f = this.#id(fixed);
2005
+ const norm = normalizeRegistrationOptions(moving === fixed, options);
2006
+ if (this.#drag?.mesh === moving || this.#drag?.mesh === fixed) this.#drag.end();
2007
+ const r = call(() => this.#scene().register_multistage(m.index, m.generation, f.index, f.generation, COARSE_ALIGN_CODES[norm.coarseMethod], ICP_OBJECTIVE_CODES[norm.objective], optional(norm.maxIterations, "maxIterations"), optional(norm.tolerance, "tolerance"), optional(norm.overlap, "overlap"), optional(norm.maxDistance, "maxDistance"), optional(norm.targetRmse, "targetRmse"), optional(norm.sampleCount, "sampleCount"), optional(norm.andersonWindow, "andersonWindow")));
2008
+ return {
2009
+ placement: {
2010
+ rotation: Array.from(r.subarray(0, 9)),
2011
+ translation: vec3At(r, 9),
2012
+ scale: vec3At(r, 12)
2013
+ },
2014
+ transform: Array.from(r.subarray(15, 31)),
2015
+ finalRmse: r[31],
2016
+ iterations: r[32],
2017
+ status: REGISTER_STATUSES[r[33]],
2018
+ converged: r[34] === 1
2019
+ };
2020
+ }
2021
+ /** Detects the dominant reflection symmetry plane of `mesh` in world space. */
2022
+ detectSymmetryPlane(mesh) {
2023
+ const { index, generation } = this.#id(mesh);
2024
+ const r = call(() => this.#scene().detect_symmetry_plane(index, generation));
2025
+ return {
2026
+ planeNormal: vec3At(r, 0),
2027
+ planePoint: vec3At(r, 3),
2028
+ symmetryErrorRms: r[6],
2029
+ symmetryScore: r[7]
2030
+ };
2031
+ }
2032
+ /**
2033
+ * Sets a mesh's placement: world = rotation · (scale · local) + translation,
2034
+ * where local is relative to the mesh origin. A quaternion is normalised
2035
+ * and converted in double precision. The scale defaults to `[1, 1, 1]`
2036
+ * (rigid) and must be 3 finite positive numbers.
2037
+ *
2038
+ * @throws `INVALID_ARGUMENT` when the rotation is not a proper rotation, the
2039
+ * scale is not 3 finite positive numbers, or a quaternion is zero.
2040
+ */
2041
+ setPlacement(mesh, placement) {
2042
+ const { index, generation } = this.#id(mesh);
2043
+ const r = Float64Array.from(rotationMatrix(placement.rotation));
2044
+ const t = Float64Array.from(placement.translation);
2045
+ const s = placement.scale === void 0 ? void 0 : Float64Array.from(placement.scale);
2046
+ call(() => this.#scene().set_placement(index, generation, r, t, s));
2047
+ }
2048
+ /** A mesh's placement, with the rotation as a row-major matrix. */
2049
+ placement(mesh) {
2050
+ const { index, generation } = this.#id(mesh);
2051
+ const p = call(() => this.#peek().placement(index, generation));
2052
+ return {
2053
+ rotation: Array.from(p.subarray(0, 9)),
2054
+ translation: [
2055
+ p[9],
2056
+ p[10],
2057
+ p[11]
2058
+ ],
2059
+ scale: [
2060
+ p[12],
2061
+ p[13],
2062
+ p[14]
2063
+ ]
2064
+ };
2065
+ }
2066
+ /**
2067
+ * The mesh's origin. `views(mesh).positions()` are relative to it, while
2068
+ * `edit`'s `setPositions` and `addVertices` take positions with it added.
2069
+ */
2070
+ origin(mesh) {
2071
+ const { index, generation } = this.#id(mesh);
2072
+ const o = call(() => this.#peek().origin(index, generation));
2073
+ return [
2074
+ o[0],
2075
+ o[1],
2076
+ o[2]
2077
+ ];
2078
+ }
2079
+ /**
2080
+ * The column-major world matrix of the local render coordinates,
2081
+ * `placement · translate(origin)`, ready for renderers (convert to `f32`
2082
+ * yourself). The rotation columns carry the scale; normals need the
2083
+ * inverse-transpose (three.js' normal matrix does this from the matrix).
2084
+ */
2085
+ matrix4(mesh) {
2086
+ const { index, generation } = this.#id(mesh);
2087
+ return call(() => this.#peek().matrix4(index, generation));
2088
+ }
2089
+ /**
2090
+ * Starts (`points`) or ends (`null`) an interaction: a gesture that changes
2091
+ * a placement or a mesh many times a second (a drag, a brush stroke), during
2092
+ * which a distance field too large to recompute per update stays live near
2093
+ * the contact, and is made exact when the gesture ends.
2094
+ *
2095
+ * While it lasts, a field with more finite values than `points` updates
2096
+ * only the vertices near its moved targets (within a margin that follows
2097
+ * the work, about `points` vertices an update), the vertices an edit moved
2098
+ * and a sweep of a quarter of `points` others. The rest keep their values
2099
+ * and colours, out of date by at most how far the meshes moved since, so
2100
+ * nothing turns far meanwhile. A smaller field updates as usual. Ending it
2101
+ * recomputes the fields it left out of date: their values and colours are
2102
+ * then those of an exact update. A gesture that changed nothing costs
2103
+ * nothing. The results do not depend on the thread count.
2104
+ *
2105
+ * @throws `INVALID_ARGUMENT` unless `points` is `null` or an integer in
2106
+ * `[1, 2^32)`.
2107
+ */
2108
+ setFieldInteraction(points) {
2109
+ const budget = checkInteractionPoints(points);
2110
+ call(() => this.#scene().set_field_interaction(budget ?? void 0));
2111
+ }
2112
+ /** Sets when the mesh's derived data follows its edits; see {@link UpdateMode}. */
2113
+ setMode(mesh, mode) {
2114
+ const { index, generation } = this.#id(mesh);
2115
+ const m = modeCode(mode);
2116
+ call(() => this.#scene().set_mode(index, generation, m));
2117
+ }
2118
+ /** When the mesh's derived data follows its edits; see {@link UpdateMode}. */
2119
+ mode(mesh) {
2120
+ const { index, generation } = this.#id(mesh);
2121
+ const code = call(() => this.#peek().mode(index, generation));
2122
+ return MODE_NAMES[code] ?? "eager";
2123
+ }
2124
+ /**
2125
+ * The box around the vertices the live triangles use, in the mesh's local
2126
+ * render coordinates ({@link Scene.matrix4} maps them to the world). Dead
2127
+ * slots keep stale positions, so they are excluded. `null` without live
2128
+ * triangles.
2129
+ */
2130
+ bounds(mesh) {
2131
+ const { index, generation } = this.#id(mesh);
2132
+ const b = call(() => this.#peek().bounds(index, generation));
2133
+ if (b.length === 0) return null;
2134
+ const min = [
2135
+ b[0],
2136
+ b[1],
2137
+ b[2]
2138
+ ];
2139
+ const max = [
2140
+ b[3],
2141
+ b[4],
2142
+ b[5]
2143
+ ];
2144
+ return {
2145
+ min,
2146
+ max,
2147
+ center: [
2148
+ (min[0] + max[0]) / 2,
2149
+ (min[1] + max[1]) / 2,
2150
+ (min[2] + max[2]) / 2
2151
+ ],
2152
+ size: [
2153
+ max[0] - min[0],
2154
+ max[1] - min[1],
2155
+ max[2] - min[2]
2156
+ ]
2157
+ };
2158
+ }
2159
+ /** Brings the mesh's derived data up to date now, whatever its mode. */
2160
+ update(mesh) {
2161
+ const { index, generation } = this.#id(mesh);
2162
+ call(() => this.#scene().update(index, generation));
2163
+ }
2164
+ /** Brings every mesh that is not `"manual"` up to date. */
2165
+ flush() {
2166
+ const s = this.#scene();
2167
+ call(() => s.flush());
2168
+ }
2169
+ /** Vertex slots, alive or dead: the vertex length of the render buffers. */
2170
+ vertexSlots(mesh) {
2171
+ const { index, generation } = this.#id(mesh);
2172
+ return call(() => this.#peek().vertex_slots(index, generation));
2173
+ }
2174
+ /** Triangle slots, alive or dead: the triangle length of the index buffer. */
2175
+ triangleSlots(mesh) {
2176
+ const { index, generation } = this.#id(mesh);
2177
+ return call(() => this.#peek().triangle_slots(index, generation));
2178
+ }
2179
+ /** Alive vertices. */
2180
+ vertexCount(mesh) {
2181
+ const { index, generation } = this.#id(mesh);
2182
+ return call(() => this.#peek().vertex_count(index, generation));
2183
+ }
2184
+ /** Alive triangles. */
2185
+ triangleCount(mesh) {
2186
+ const { index, generation } = this.#id(mesh);
2187
+ return call(() => this.#peek().triangle_count(index, generation));
2188
+ }
2189
+ /**
2190
+ * Zero-copy views of the mesh's render buffers. Each getter builds a fresh
2191
+ * view; re-acquire views after every scene call that may allocate, since a
2192
+ * kept one may read other data or be empty (see {@link MeshViews}).
2193
+ */
2194
+ views(mesh) {
2195
+ const { index, generation } = this.#id(mesh);
2196
+ call(() => this.#peek().vertex_slots(index, generation));
2197
+ return meshViews(() => this.#peek(), index, generation, this.#guard);
2198
+ }
2199
+ /**
2200
+ * Everything that changed since the previous call, one record per mesh.
2201
+ * There is a single consumer: apps that use {@link Scene.onChanges} call
2202
+ * {@link Scene.commitFrame} instead.
2203
+ */
2204
+ takeChanges() {
2205
+ this.#drag?.applyPending();
2206
+ const s = this.#scene();
2207
+ this.#settleHistory();
2208
+ const raw = decodeChanges(call(() => s.take_changes()));
2209
+ const out = raw.map((c) => ({
2210
+ mesh: this.#meshHandle(c.index, c.generation),
2211
+ added: c.added,
2212
+ removed: c.removed,
2213
+ ...c.restorable ? { restorable: true } : {},
2214
+ placementChanged: c.placementChanged,
2215
+ capacityChanged: c.capacityChanged,
2216
+ positions: c.positions,
2217
+ normals: c.normals,
2218
+ colors: c.colors,
2219
+ indices: c.indices,
2220
+ ...c.uvs === void 0 ? {} : { uvs: c.uvs },
2221
+ fieldsChanged: c.fields.map((f) => this.#rawHandle(this.#fields, () => new FieldHandle(), f)),
2222
+ sectionsChanged: c.sections.map((x) => this.#rawHandle(this.#sections, () => new SectionHandle(), x))
2223
+ }));
2224
+ for (const c of raw) if (c.removed && !c.restorable) this.#meshes.delete(`${c.index}:${c.generation}`);
2225
+ this.#removed.clear();
2226
+ if (this.#prune) {
2227
+ this.#prune = false;
2228
+ for (const [key, handle] of this.#meshes) {
2229
+ const { index, generation } = meshIds.get(handle);
2230
+ if (!s.has_mesh(index, generation) && !s.is_restorable(index, generation)) this.#meshes.delete(key);
2231
+ }
2232
+ }
2233
+ return out;
2234
+ }
2235
+ /**
2236
+ * Registers a listener for {@link Scene.commitFrame}. Returns a function
2237
+ * that unregisters it.
2238
+ */
2239
+ onChanges(listener) {
2240
+ this.#scene();
2241
+ this.#listeners.add(listener);
2242
+ return () => {
2243
+ this.#listeners.delete(listener);
2244
+ };
2245
+ }
2246
+ /**
2247
+ * Takes the changes once and delivers the same array to every listener,
2248
+ * then returns it. Call it once per animation frame. Every listener runs
2249
+ * even if one throws; the first error is rethrown afterwards.
2250
+ */
2251
+ commitFrame() {
2252
+ const changes = this.takeChanges();
2253
+ let failure;
2254
+ for (const listener of [...this.#listeners]) try {
2255
+ listener(changes);
2256
+ } catch (error) {
2257
+ failure ??= { error };
2258
+ }
2259
+ if (failure !== void 0) throw failure.error;
2260
+ return changes;
2261
+ }
2262
+ /**
2263
+ * Undoes the latest step; an active drag is ended first. Without an open
2264
+ * step around the drag, the drag is what gets undone; inside a caller's
2265
+ * open step, that whole step (drag included) is closed and undone. A mesh
2266
+ * the step added undoably leaves the scene, and one it removed undoably
2267
+ * comes back (see {@link MeshChange.added}). Returns `false` when there is
2268
+ * nothing to undo.
2269
+ */
2270
+ undo() {
2271
+ const s = this.#scene();
2272
+ this.#drag?.end();
2273
+ this.#prune = true;
2274
+ const done = call(() => s.undo());
2275
+ this.#stepDepth = 0;
2276
+ this.#settleHistory();
2277
+ return done;
2278
+ }
2279
+ /** Redoes the latest undone step. Returns `false` when there is nothing to redo. */
2280
+ redo() {
2281
+ const s = this.#scene();
2282
+ this.#drag?.end();
2283
+ this.#prune = true;
2284
+ const done = call(() => s.redo());
2285
+ this.#stepDepth = 0;
2286
+ this.#settleHistory();
2287
+ return done;
2288
+ }
2289
+ /** True if {@link Scene.undo} would undo something. */
2290
+ canUndo() {
2291
+ const s = this.#peek();
2292
+ return call(() => s.can_undo());
2293
+ }
2294
+ /** True if {@link Scene.redo} would redo something. */
2295
+ canRedo() {
2296
+ const s = this.#peek();
2297
+ return call(() => s.can_redo());
2298
+ }
2299
+ /** Closes an open step, then drops every undo and redo step. */
2300
+ clearHistory() {
2301
+ const s = this.#scene();
2302
+ this.#drag?.end();
2303
+ this.#prune = true;
2304
+ call(() => s.clear_history());
2305
+ this.#stepDepth = 0;
2306
+ this.#settleHistory();
2307
+ }
2308
+ /**
2309
+ * Records an entry of the application's own in the history, in the open
2310
+ * step or as a step of its own, for state that is not the scene's: a
2311
+ * selection, a list of curves, a document's title. Make the change, then
2312
+ * record how to take it back and make it again. The entry is undone, redone
2313
+ * and cancelled in order with mesh edits and with its step, counts against
2314
+ * the budget, and drops the steps undone before it.
2315
+ *
2316
+ * On undo its `undo` is called before {@link Scene.undo} returns, once
2317
+ * every mesh of the step has changed; the entries of one step are called in
2318
+ * reverse order, and in order on redo. A callback should not change the
2319
+ * scene (that would be a new step); an error it throws is reported
2320
+ * (`reportError`), and the undo stands.
2321
+ *
2322
+ * @throws `INVALID_ARGUMENT` for an entry without `undo` and `redo`, or with
2323
+ * bytes below 0. Nothing is recorded then, and no function is called.
2324
+ *
2325
+ * @example
2326
+ * ```ts
2327
+ * const before = doc.title;
2328
+ * const after = input.value;
2329
+ * doc.title = after;
2330
+ * scene.recordEntry({
2331
+ * undo: () => (doc.title = before),
2332
+ * redo: () => (doc.title = after),
2333
+ * bytes: 2 * (before.length + after.length),
2334
+ * });
2335
+ * ```
2336
+ */
2337
+ recordEntry(entry) {
2338
+ const { bytes, coalesce } = checkHistoryEntry(entry);
2339
+ const s = this.#scene();
2340
+ if (coalesce !== void 0 && (this.#coalesce.id === 0 || coalesce !== this.#coalesce.key)) this.#coalesce = {
2341
+ key: coalesce,
2342
+ id: this.#coalesce.id + 1
2343
+ };
2344
+ const id = this.#entries.add(entry);
2345
+ try {
2346
+ call(() => s.record_entry(id, bytes, coalesce === void 0 ? 0 : this.#coalesce.id));
2347
+ } catch (e) {
2348
+ this.#entries.forget(id);
2349
+ throw e;
2350
+ }
2351
+ this.#settleHistory();
2352
+ }
2353
+ /** The most bytes the history may hold; see {@link SceneOptions.historyBudget}. */
2354
+ historyBudget() {
2355
+ return call(() => this.#peek().history_budget());
2356
+ }
2357
+ /**
2358
+ * Changes the most bytes the history may hold
2359
+ * ({@link SceneOptions.historyBudget}). A smaller budget is met at once:
2360
+ * the oldest steps go first, then the undone steps furthest from being
2361
+ * redone. The meshes in the scene stay as they are, and an open step is
2362
+ * kept until it closes.
2363
+ *
2364
+ * @throws `INVALID_ARGUMENT` for anything but a number, 0 or more.
2365
+ */
2366
+ setHistoryBudget(bytes) {
2367
+ const budget = checkHistoryBudget(bytes);
2368
+ const s = this.#scene();
2369
+ this.#prune = true;
2370
+ call(() => s.set_history_budget(budget));
2371
+ this.#settleHistory();
2372
+ }
2373
+ /** The bytes the history holds now, the open step included. */
2374
+ historyBytes() {
2375
+ return call(() => this.#peek().history_bytes());
2376
+ }
2377
+ /**
2378
+ * Registers a listener called with each step the history could not keep,
2379
+ * since it is larger than the whole budget: an action that is permanent, or
2380
+ * one just undone that cannot be redone. Steps dropped later, to make room
2381
+ * for newer ones or by {@link Scene.setHistoryBudget}, are not reported.
2382
+ * It is called by the history calls themselves (`removeMesh`, `join`,
2383
+ * `endStep`, `undo`, ...), and within a microtask of any other. Returns a
2384
+ * function that unregisters it.
2385
+ *
2386
+ * @example
2387
+ * ```ts
2388
+ * scene.onPermanent(({ lost, gone }) => {
2389
+ * if (lost === "undo") {
2390
+ * notify(gone.length > 0 ? "The removal cannot be undone." : "The change cannot be undone.");
2391
+ * }
2392
+ * });
2393
+ * ```
2394
+ */
2395
+ onPermanent(listener) {
2396
+ this.#scene();
2397
+ if (this.#permanentListeners.size === 0) call(() => this.#peek().take_permanent());
2398
+ this.#permanentListeners.add(listener);
2399
+ return () => {
2400
+ this.#permanentListeners.delete(listener);
2401
+ };
2402
+ }
2403
+ /**
2404
+ * Opens a history step, or one more nesting level of the open one. Edits,
2405
+ * placement changes and undoable adds and removals until the matching
2406
+ * {@link Scene.endStep} are undone together.
2407
+ */
2408
+ beginStep() {
2409
+ const s = this.#scene();
2410
+ call(() => s.begin_step());
2411
+ this.#stepDepth++;
2412
+ }
2413
+ /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
2414
+ endStep() {
2415
+ const s = this.#scene();
2416
+ const drag = this.#drag;
2417
+ if (drag !== void 0 && this.#stepDepth > 0 && this.#stepDepth <= drag.depth) drag.applyPending();
2418
+ call(() => s.end_step());
2419
+ this.#stepDepth--;
2420
+ if (this.#drag !== void 0 && this.#stepDepth < this.#drag.depth) this.#drag.abandon();
2421
+ this.#settleHistory();
2422
+ }
2423
+ /**
2424
+ * Reverts and discards the open step, however deeply nested. The
2425
+ * application's entries in it are undone and dropped. Throws `STEP_NOT_OPEN`
2426
+ * when none is open.
2427
+ */
2428
+ cancelStep() {
2429
+ const s = this.#scene();
2430
+ this.#prune = true;
2431
+ call(() => s.cancel_step());
2432
+ this.#stepDepth = 0;
2433
+ this.#drag?.abandon();
2434
+ this.#settleHistory();
2435
+ }
2436
+ /**
2437
+ * Starts dragging a mesh: the moves until {@link DragSession.end} form one
2438
+ * undo step (nested in the open step, if there is one). One drag at a time.
2439
+ * Every {@link DragSession.move} recomputes the eager fields, so make at most
2440
+ * one move per animation frame, with the latest pointer pose, or pass
2441
+ * `{ coalesce: true }` to have the drag do that for you.
2442
+ */
2443
+ drag(mesh, options = {}) {
2444
+ this.#id(mesh);
2445
+ if (this.#drag !== void 0) throw invalid("a drag is already active; end or cancel it first");
2446
+ const coalesce = options.coalesce ?? false;
2447
+ const start = this.placement(mesh);
2448
+ const collisionActive = this.hasActiveCollisionResponse(mesh);
2449
+ const outermost = this.#stepDepth === 0;
2450
+ this.beginStep();
2451
+ const depth = this.#stepDepth;
2452
+ let active = true;
2453
+ let moved = false;
2454
+ /** The latest coalesced pose, not yet applied. */
2455
+ let pending;
2456
+ const finish = () => {
2457
+ if (!active) return false;
2458
+ active = false;
2459
+ this.#drag = void 0;
2460
+ return true;
2461
+ };
2462
+ const close = () => {
2463
+ while (this.#stepDepth >= depth) this.endStep();
2464
+ };
2465
+ const applyPose = (pose) => {
2466
+ if (!collisionActive) {
2467
+ this.setPlacement(mesh, pose);
2468
+ return;
2469
+ }
2470
+ moved = true;
2471
+ this.moveWithCollision(mesh, pose, false);
2472
+ };
2473
+ const applyPending = () => {
2474
+ if (pending !== void 0) {
2475
+ const pose = pending;
2476
+ pending = void 0;
2477
+ applyPose(pose);
2478
+ }
2479
+ };
2480
+ const session = {
2481
+ depth,
2482
+ mesh,
2483
+ get active() {
2484
+ return active;
2485
+ },
2486
+ move: (placement) => {
2487
+ if (!active) throw invalid("the drag is over");
2488
+ if (!coalesce) {
2489
+ applyPose(placement);
2490
+ return;
2491
+ }
2492
+ const rotation = rotationMatrix(placement.rotation);
2493
+ if (!rotation.every(Number.isFinite)) throw invalid("rotation must be finite numbers");
2494
+ const t = placement.translation;
2495
+ if (t?.length !== 3 || ![
2496
+ t[0],
2497
+ t[1],
2498
+ t[2]
2499
+ ].every(Number.isFinite)) throw invalid("translation must be 3 finite numbers");
2500
+ const s = placement.scale;
2501
+ if (s !== void 0 && (s.length !== 3 || ![
2502
+ s[0],
2503
+ s[1],
2504
+ s[2]
2505
+ ].every(Number.isFinite))) throw invalid("scale must be 3 finite numbers");
2506
+ pending = {
2507
+ rotation,
2508
+ translation: [
2509
+ t[0],
2510
+ t[1],
2511
+ t[2]
2512
+ ],
2513
+ ...s === void 0 ? {} : { scale: [
2514
+ s[0],
2515
+ s[1],
2516
+ s[2]
2517
+ ] }
2518
+ };
2519
+ },
2520
+ end: () => {
2521
+ if (finish()) try {
2522
+ applyPending();
2523
+ if (collisionActive && moved) this.commitCollisionInteraction(mesh);
2524
+ } finally {
2525
+ close();
2526
+ }
2527
+ },
2528
+ cancel: () => {
2529
+ if (!finish()) return;
2530
+ pending = void 0;
2531
+ if (outermost) {
2532
+ this.cancelStep();
2533
+ return;
2534
+ }
2535
+ try {
2536
+ this.setPlacement(mesh, start);
2537
+ } finally {
2538
+ close();
2539
+ }
2540
+ },
2541
+ abandon: () => {
2542
+ finish();
2543
+ },
2544
+ applyPending
2545
+ };
2546
+ this.#drag = session;
2547
+ return session;
2548
+ }
2549
+ /**
2550
+ * Edits a mesh's geometry with a list of ops, run in Rust as one
2551
+ * transaction: one undo step (or part of the open step), and when any op
2552
+ * fails nothing changes and nothing is recorded. Positions are world
2553
+ * coordinates, mapped to local with the mesh's placement and origin. Ids
2554
+ * may be {@link EditRef}s to ids added by earlier ops of the list; every
2555
+ * ref is checked before anything is written. Normals, colours, fields,
2556
+ * sections and the BVH follow by the mesh's mode.
2557
+ *
2558
+ * @throws `INVALID_INDEX` for a bad ref or an id that is not alive;
2559
+ * `INVALID_ARGUMENT` for a malformed op, positions not 3 per vertex or not
2560
+ * finite in local `f32`, or removing a vertex still in use.
2561
+ */
2562
+ edit(mesh, ops) {
2563
+ const { index, generation } = this.#id(mesh);
2564
+ const { words, values } = encodeEdit(ops);
2565
+ const out = call(() => this.#scene().edit(index, generation, words, values));
2566
+ const added = [];
2567
+ let at = 0;
2568
+ while (at < out.length) {
2569
+ const n = out[at];
2570
+ added.push(out.slice(at + 1, at + 1 + n));
2571
+ at += 1 + n;
2572
+ }
2573
+ return { added };
2574
+ }
2575
+ /**
2576
+ * Removes the mesh's dead slots and renumbers the rest. Its next change
2577
+ * record has every buffer `"all"` and `capacityChanged` when the slot counts
2578
+ * shrank. The mesh's earlier edits leave the history (its placement changes
2579
+ * stay undoable).
2580
+ */
2581
+ compact(mesh) {
2582
+ const { index, generation } = this.#id(mesh);
2583
+ call(() => this.#scene().compact(index, generation));
2584
+ }
2585
+ /**
2586
+ * A read-only report of the mesh's defects: boundary loops (whose ids
2587
+ * `fillHoles` takes), coincident vertices, degenerate and duplicate
2588
+ * triangles, non-manifold edges and vertices, components, orientation
2589
+ * conflicts and, on request, self-intersection.
2590
+ *
2591
+ * @deprecated Use `scene.inspect.analyze()` or `scene.repair.analyze()` instead.
2592
+ * @throws `INVALID_ARGUMENT` for a negative or non-finite `weldTolerance`; `STALE_BVH`, see {@link AnalyzeOptions.selfIntersection}.
2593
+ */
2594
+ analyze(mesh, options = {}) {
2595
+ const { index, generation } = this.#id(mesh);
2596
+ const maxListed = options.maxListed ?? 1e3;
2597
+ if (!Number.isInteger(maxListed) || maxListed < 0 || maxListed >= U32_LIMIT) throw invalid("maxListed must be a non-negative integer");
2598
+ const tolerance = options.weldTolerance ?? 0;
2599
+ const si = options.selfIntersection ?? false;
2600
+ return decodeAnalysis(new Reader(call(() => this.#scene().analyze(index, generation, tolerance, si, maxListed))));
2601
+ }
2602
+ /**
2603
+ * Scalar measurements of a mesh in world coordinates: its surface area
2604
+ * (always) and, when watertight, its enclosed volume. An open or
2605
+ * non-manifold mesh still gets its area; only `volume` is `null`, with
2606
+ * `volumeReason` saying why. A read-only call: it leaves every view
2607
+ * valid.
2608
+ *
2609
+ * @deprecated Use `scene.inspect.measure()` instead.
2610
+ */
2611
+ measure(mesh) {
2612
+ const { index, generation } = this.#id(mesh);
2613
+ const r = call(() => this.#peek().measure(index, generation));
2614
+ const closed = r[2] === 1;
2615
+ return {
2616
+ area: r[0],
2617
+ volume: Number.isNaN(r[1]) ? null : r[1],
2618
+ closed,
2619
+ volumeReason: closed ? null : r[3] === 2 ? "non-manifold" : "open",
2620
+ boundaryLoops: r[4],
2621
+ nonManifoldEdges: r[5],
2622
+ orientationConflicts: r[6]
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Runs one repair operation and returns its report, or a list of them in
2627
+ * order and returns their reports. A list is one transaction: one undo step,
2628
+ * and when any operation fails nothing changes and nothing is recorded.
2629
+ * `{ kind: "auto" }` runs the standard cleanup pipeline the same way and
2630
+ * returns a report per stage; see {@link AutoRepairRequest}.
2631
+ */
2632
+ #runRepair(mesh, op) {
2633
+ const { index, generation } = this.#id(mesh);
2634
+ if (isAutoRepair(op)) {
2635
+ const noLoops = /* @__PURE__ */ new Uint32Array();
2636
+ if (op.preset === void 0 && op.selfIntersectionMode === void 0 && op.voxelSize === void 0 && op.maxVoxels === void 0) {
2637
+ const values = Float64Array.of(AUTO_REPAIR_CODE, optional(op.weldTolerance, "weldTolerance"), optional(op.minTriangles, "minTriangles"), optional(op.maxEdges, "maxEdges"), op.fair === void 0 ? NaN : flagOf(op.fair, true));
2638
+ return decodeAutoReport(new Reader(call(() => this.#scene().repair(index, generation, values, noLoops))));
2639
+ }
2640
+ const preset = op.preset === void 0 ? NaN : codeIn(PRESET_CODES, op.preset, "preset");
2641
+ const siMode = op.selfIntersectionMode === void 0 ? NaN : codeIn(SELF_INTERSECTION_MODE_CODES, op.selfIntersectionMode, "selfIntersectionMode");
2642
+ const values = Float64Array.of(AUTO_REPAIR_PRESET_CODE, preset, siMode, optional(op.weldTolerance, "weldTolerance"), optional(op.minTriangles, "minTriangles"), optional(op.maxEdges, "maxEdges"), op.fair === void 0 ? NaN : flagOf(op.fair, true), optVoxelSize(op.voxelSize), optMaxVoxels(op.maxVoxels));
2643
+ return decodeAutoReport(new Reader(call(() => this.#scene().repair(index, generation, values, noLoops))));
2644
+ }
2645
+ const ops = Array.isArray(op) ? op : [op];
2646
+ const { values, loops } = encodeRepair(ops);
2647
+ const r = new Reader(call(() => this.#scene().repair(index, generation, values, loops)));
2648
+ const reports = ops.map((o) => decodeReport(o.op, r));
2649
+ return Array.isArray(op) ? reports : reports[0];
2650
+ }
2651
+ /**
2652
+ * Live triangle-used vertex ids of `mesh` inside the closed local-space
2653
+ * sphere `(center, radius)`, in ascending order. Brings a `"lazy"` BVH up
2654
+ * to date first; throws `STALE_BVH` on a stale `"manual"` mesh.
2655
+ *
2656
+ * @deprecated Use `scene.sculpt.verticesInSphere()` instead.
2657
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` when
2658
+ * `center` is not 3 finite numbers or `radius` is negative or non-finite;
2659
+ * `STALE_BVH` for a stale `"manual"` mesh.
2660
+ */
2661
+ verticesInSphere(mesh, center, radius) {
2662
+ const { index, generation } = this.#id(mesh);
2663
+ const c = center;
2664
+ if (c?.length !== 3 || ![
2665
+ c[0],
2666
+ c[1],
2667
+ c[2]
2668
+ ].every((x) => typeof x === "number" && Number.isFinite(x))) throw invalid("center must be 3 finite numbers");
2669
+ if (typeof radius !== "number" || !Number.isFinite(radius) || radius < 0) throw invalid("radius must be a finite non-negative number");
2670
+ return call(() => this.#scene().vertices_in_sphere(index, generation, c[0], c[1], c[2], radius));
2671
+ }
2672
+ /**
2673
+ * The nearest hit of a world ray over every mesh, or `null`. `direction`
2674
+ * need not be unit length; `distance` is in world units. Lazy meshes are
2675
+ * brought up to date first.
2676
+ *
2677
+ * @deprecated Use `scene.inspect.raycast()` instead.
2678
+ * @throws `INVALID_ARGUMENT` for a non-finite origin or a zero direction; `STALE_BVH` for a stale `"manual"` mesh.
2679
+ */
2680
+ raycast(origin, direction, options = {}) {
2681
+ const s = this.#scene();
2682
+ const o = Float64Array.from(origin);
2683
+ const d = Float64Array.from(direction);
2684
+ const cull = codeIn(CULLS, options.cull ?? "none", "cull");
2685
+ const min = options.minDistance ?? 0;
2686
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
2687
+ const h = call(() => s.raycast(o, d, min, max, cull));
2688
+ if (h.length === 0) return null;
2689
+ return {
2690
+ mesh: this.#meshHandle(h[0], h[1]),
2691
+ triangle: h[2],
2692
+ point: vec3At(h, 3),
2693
+ distance: h[6],
2694
+ barycentric: vec3At(h, 7)
2695
+ };
2696
+ }
2697
+ /**
2698
+ * The surface point nearest to a world point, over every mesh or one, or
2699
+ * `null` when none is within `maxDistance`.
2700
+ *
2701
+ * @deprecated Use `scene.inspect.closestPoint()` instead.
2702
+ */
2703
+ closestPoint(point, options = {}) {
2704
+ const s = this.#scene();
2705
+ const p = Float64Array.from(point);
2706
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
2707
+ let h;
2708
+ if (options.mesh === void 0) h = call(() => s.closest_point(p, max));
2709
+ else {
2710
+ const { index, generation } = this.#id(options.mesh);
2711
+ h = call(() => s.closest_point_on(index, generation, p, max));
2712
+ }
2713
+ if (h.length === 0) return null;
2714
+ return {
2715
+ mesh: this.#meshHandle(h[0], h[1]),
2716
+ triangle: h[2],
2717
+ point: vec3At(h, 3),
2718
+ distance: h[6]
2719
+ };
2720
+ }
2721
+ /**
2722
+ * The distance between two meshes' surfaces as placed, with a closest pair
2723
+ * of points, or `null` when it exceeds `maxDistance` (default `Infinity`)
2724
+ * or a mesh has no triangle.
2725
+ *
2726
+ * @deprecated Use `scene.inspect.meshDistance()` instead.
2727
+ */
2728
+ meshDistance(a, b, options = {}) {
2729
+ const ia = this.#id(a);
2730
+ const ib = this.#id(b);
2731
+ const max = options.maxDistance ?? Number.POSITIVE_INFINITY;
2732
+ const d = call(() => this.#scene().mesh_distance(ia.index, ia.generation, ib.index, ib.generation, max));
2733
+ if (d.length === 0) return null;
2734
+ return {
2735
+ distance: d[0],
2736
+ a: vec3At(d, 1),
2737
+ b: vec3At(d, 4),
2738
+ triangleA: d[7],
2739
+ triangleB: d[8]
2740
+ };
2741
+ }
2742
+ /**
2743
+ * Whether two meshes intersect or touch as placed.
2744
+ *
2745
+ * @deprecated Use `scene.inspect.intersects()` instead.
2746
+ */
2747
+ intersects(a, b) {
2748
+ const ia = this.#id(a);
2749
+ const ib = this.#id(b);
2750
+ return call(() => this.#scene().intersects(ia.index, ia.generation, ib.index, ib.generation));
2751
+ }
2752
+ /**
2753
+ * The live triangle slots of `mesh` that intersect or touch another of its
2754
+ * own triangles, ascending, each once. Triangles that share a vertex are
2755
+ * never tested against each other (neighbours always touch), and
2756
+ * degenerate triangles are skipped, as for
2757
+ * {@link AnalyzeOptions.selfIntersection}. The placement does not change
2758
+ * the answer. The mesh's BVH is brought up to date first.
2759
+ *
2760
+ * @throws `STALE_BVH` for a `"manual"` mesh whose BVH is stale.
2761
+ */
2762
+ selfIntersectingTriangles(mesh) {
2763
+ const { index, generation } = this.#id(mesh);
2764
+ return call(() => this.#scene().self_intersecting_triangles(index, generation));
2765
+ }
2766
+ /**
2767
+ * Every mesh pair (or every pair of `pairs`) within `margin`, sorted by mesh id.
2768
+ *
2769
+ * @deprecated Use `scene.inspect.findContacts()` instead.
2770
+ */
2771
+ findContacts(options = {}) {
2772
+ const s = this.#scene();
2773
+ const pairs = options.pairs === void 0 ? void 0 : this.#flatIds(options.pairs.flat());
2774
+ const msg = call(() => s.find_contacts(options.margin ?? 0, pairs));
2775
+ const out = [];
2776
+ let at = 1;
2777
+ for (let k = 0; k < msg[0]; k++) {
2778
+ const na = msg[at + 6];
2779
+ const nb = msg[at + 7];
2780
+ const start = at + 8;
2781
+ out.push({
2782
+ a: this.#meshHandle(msg[at], msg[at + 1]),
2783
+ b: this.#meshHandle(msg[at + 2], msg[at + 3]),
2784
+ intersecting: msg[at + 4] === 1,
2785
+ distance: msg[at + 5],
2786
+ trianglesA: Uint32Array.from(msg.subarray(start, start + na)),
2787
+ trianglesB: Uint32Array.from(msg.subarray(start + na, start + na + nb))
2788
+ });
2789
+ at = start + na + nb;
2790
+ }
2791
+ return out;
2792
+ }
2793
+ /** Evaluates printability overhang angles and support surface area in world coordinates. */
2794
+ overhangs(mesh, options = {}) {
2795
+ const { index, generation } = this.#id(mesh);
2796
+ const norm = normalizeOverhangOptions(options);
2797
+ const r = call(() => this.#scene().overhangs(index, generation, Float64Array.from(norm.buildDirection), optional(norm.criticalAngleDeg, "criticalAngleDeg")));
2798
+ return {
2799
+ totalSupportArea: r[0],
2800
+ overhangFaceCount: r[1],
2801
+ maxOverhangAngleDeg: r[2],
2802
+ vertexAnglesDeg: Float32Array.from(r.subarray(3))
2803
+ };
2804
+ }
2805
+ /** Evaluates triangle element quality metrics across `mesh` in world coordinates. */
2806
+ triangleQuality(mesh, metricOrOptions = "radiusRatio", sliverThreshold) {
2807
+ const { index, generation } = this.#id(mesh);
2808
+ const norm = normalizeQualityArgs(metricOrOptions, sliverThreshold);
2809
+ const r = call(() => this.#scene().triangle_quality(index, generation, QUALITY_METRIC_CODES[norm.metric], norm.sliverThreshold));
2810
+ return {
2811
+ min: r[0],
2812
+ max: r[1],
2813
+ mean: r[2],
2814
+ sliverTriangleCount: r[3],
2815
+ liveTriangleCount: r[4],
2816
+ vertexQuality: Float32Array.from(r.subarray(5))
2817
+ };
2818
+ }
2819
+ /** Computes vertex-to-surface Hausdorff / signed deviation from `source` to `target` in world units. */
2820
+ meshDeviation(source, target, options = {}) {
2821
+ const src = this.#id(source);
2822
+ const tgt = this.#id(target);
2823
+ const norm = normalizeDeviationOptions(options);
2824
+ const r = call(() => this.#scene().mesh_deviation(src.index, src.generation, tgt.index, tgt.generation, norm.signed, optional(norm.maxDistance, "maxDistance")));
2825
+ return {
2826
+ min: r[0],
2827
+ max: r[1],
2828
+ mean: r[2],
2829
+ rms: r[3],
2830
+ p95: r[4],
2831
+ sampleCount: r[5],
2832
+ vertexDeviations: Float32Array.from(r.subarray(6))
2833
+ };
2834
+ }
2835
+ /**
2836
+ * Computes per-vertex surface geodesic distances from `sources` in world
2837
+ * units; `inspect.geodesicDistances` says what `"heatMethod"` keeps.
2838
+ */
2839
+ geodesicDistances(mesh, sources, options = {}) {
2840
+ const { index, generation } = this.#id(mesh);
2841
+ const src = normalizeSourceVertices(sources);
2842
+ const norm = normalizeGeodesicOptions(options);
2843
+ throwIfAborted(options.signal);
2844
+ return call(() => this.#scene().geodesic_distances(index, generation, src, GEODESIC_METHOD_CODES[norm.method], optional(norm.maxDistance, "maxDistance"), optional(norm.timeStepScale, "timeStepScale")));
2845
+ }
2846
+ /** Frees what `"heatMethod"` queries keep for the next one of the same mesh. */
2847
+ releaseGeodesics() {
2848
+ call(() => this.#peek().release_geodesics());
2849
+ }
2850
+ /** Traces the intrinsic shortest surface path from `sources` to `targetVertex` in world coordinates. */
2851
+ shortestSurfacePath(mesh, sources, targetVertex, options = {}) {
2852
+ const { index, generation } = this.#id(mesh);
2853
+ const src = normalizeSourceVertices(sources);
2854
+ const target = normalizeSurfacePathTarget(targetVertex);
2855
+ const { distances, geodesic } = checkSurfacePathOptions(options);
2856
+ throwIfAborted(options.signal);
2857
+ const dists = distances ?? call(() => this.#scene().geodesic_distances(index, generation, src, GEODESIC_METHOD_CODES[geodesic.method], optional(geodesic.maxDistance, "maxDistance"), optional(geodesic.timeStepScale, "timeStepScale")));
2858
+ const r = call(() => this.#scene().shortest_surface_path(index, generation, dists, src, target));
2859
+ const points = [];
2860
+ for (let at = 0; at < r.length; at += 7) points.push({
2861
+ position: vec3At(r, at),
2862
+ triangle: r[at + 3],
2863
+ barycentric: vec3At(r, at + 4)
2864
+ });
2865
+ return points;
2866
+ }
2867
+ /**
2868
+ * Selects vertices of a mesh: a sphere brush, a lasso polygon, or the
2869
+ * connected component holding a seed vertex. The result is a snapshot
2870
+ * (ascending ids plus the mesh's content stamp); any edit, repair, compact,
2871
+ * undo or redo of the mesh invalidates it, and the selection methods then
2872
+ * throw `STALE_SELECTION` instead of silently remapping ids. Placement
2873
+ * changes keep selections valid. Only vertices a live triangle uses can
2874
+ * be selected (dead or never-used slots never are).
2875
+ *
2876
+ * @throws `UNKNOWN_MESH` for a removed mesh; `INVALID_ARGUMENT` for a bad
2877
+ * spec; `INVALID_INDEX` for an out-of-range component seed.
2878
+ */
2879
+ select(mesh, spec) {
2880
+ checkSpec(spec);
2881
+ this.#id(mesh);
2882
+ const views = this.views(mesh);
2883
+ const slots = this.vertexSlots(mesh);
2884
+ const positions = views.positions().slice();
2885
+ const topology = buildTopology(views.indices().slice(), slots);
2886
+ let ids;
2887
+ switch (spec.kind) {
2888
+ case "brush": {
2889
+ let center = spec.center;
2890
+ let radius = spec.radius;
2891
+ let stretch;
2892
+ if (spec.space === "world") {
2893
+ const matrix = this.matrix4(mesh);
2894
+ center = transformPoint(invertMatrix4(matrix), spec.center);
2895
+ const { scale } = this.placement(mesh);
2896
+ if (scale === void 0 || scale[0] === scale[1] && scale[1] === scale[2]) radius = spec.radius / meanStretch(matrix);
2897
+ else stretch = matrix;
2898
+ }
2899
+ ids = brushPick(positions, topology.used, center, radius, stretch);
2900
+ break;
2901
+ }
2902
+ case "lasso":
2903
+ ids = lassoPick(positions, topology.used, spec.polygon, spec.axis ?? "xy");
2904
+ break;
2905
+ case "component": ids = componentOf(topology, spec.seed);
2906
+ }
2907
+ return {
2908
+ mesh,
2909
+ vertices: Uint32Array.from(ids),
2910
+ stamp: meshAdds(this).stamp(mesh)
2911
+ };
2912
+ }
2913
+ /**
2914
+ * Whether `sel` is still usable: its mesh is alive and no topology edit
2915
+ * landed since it was taken. Never throws.
2916
+ */
2917
+ selectionAlive(sel) {
2918
+ try {
2919
+ if (sel === null || typeof sel !== "object" || !(sel.vertices instanceof Uint32Array)) return false;
2920
+ this.#id(sel.mesh);
2921
+ return Number.isInteger(sel.stamp) && sel.stamp === meshAdds(this).stamp(sel.mesh);
2922
+ } catch {
2923
+ return false;
2924
+ }
2925
+ }
2926
+ /** Reads the mesh's topology and checks `sel` against its stamp. */
2927
+ #selectionTopology(sel) {
2928
+ this.#id(sel.mesh);
2929
+ checkSelection(sel, sel.mesh, meshAdds(this).stamp(sel.mesh));
2930
+ return buildTopology(this.views(sel.mesh).indices().slice(), this.vertexSlots(sel.mesh));
2931
+ }
2932
+ /**
2933
+ * Grows a selection by `steps` rings of edge neighbours (staying on live
2934
+ * vertices). The result carries the current stamp, so a fresh selection
2935
+ * can be grown right after an edit. `steps` 0 returns an equal copy.
2936
+ *
2937
+ * @throws `STALE_SELECTION` when the mesh changed since the selection;
2938
+ * `UNKNOWN_MESH` for a removed mesh.
2939
+ */
2940
+ selectGrow(sel, steps = 1) {
2941
+ const topology = this.#selectionTopology(sel);
2942
+ return {
2943
+ mesh: sel.mesh,
2944
+ vertices: Uint32Array.from(growIds(topology, sel.vertices, steps)),
2945
+ stamp: meshAdds(this).stamp(sel.mesh)
2946
+ };
2947
+ }
2948
+ /**
2949
+ * Shrinks a selection by `steps` rings, dropping the members with a live
2950
+ * neighbour outside the set. Interior selections (no boundary) survive
2951
+ * unchanged; shrinking past the core gives an empty (still valid)
2952
+ * selection.
2953
+ *
2954
+ * @throws `STALE_SELECTION` when the mesh changed since the selection;
2955
+ * `UNKNOWN_MESH` for a removed mesh.
2956
+ */
2957
+ selectShrink(sel, steps = 1) {
2958
+ const topology = this.#selectionTopology(sel);
2959
+ return {
2960
+ mesh: sel.mesh,
2961
+ vertices: Uint32Array.from(shrinkIds(topology, sel.vertices, steps)),
2962
+ stamp: meshAdds(this).stamp(sel.mesh)
2963
+ };
2964
+ }
2965
+ /**
2966
+ * Inverts a selection: every live vertex outside it. The result carries
2967
+ * the current stamp.
2968
+ *
2969
+ * @throws `STALE_SELECTION` when the mesh changed since the selection;
2970
+ * `UNKNOWN_MESH` for a removed mesh.
2971
+ */
2972
+ selectInvert(sel) {
2973
+ const topology = this.#selectionTopology(sel);
2974
+ const inSet = new Set(sel.vertices);
2975
+ const out = [];
2976
+ for (let v = 0; v < topology.used.length; v++) if (topology.used[v] === 1 && !inSet.has(v)) out.push(v);
2977
+ return {
2978
+ mesh: sel.mesh,
2979
+ vertices: Uint32Array.from(out),
2980
+ stamp: meshAdds(this).stamp(sel.mesh)
2981
+ };
2982
+ }
2983
+ /**
2984
+ * Isolates a selection: removes the triangles fully outside it (no
2985
+ * selected vertex), one undo step. Boundary triangles with at least one
2986
+ * selected vertex stay. An empty selection selects nothing to keep and
2987
+ * throws `INVALID_ARGUMENT` rather than clearing the mesh.
2988
+ *
2989
+ * @throws `STALE_SELECTION` when the mesh changed since the selection;
2990
+ * `UNKNOWN_MESH` for a removed mesh.
2991
+ */
2992
+ isolate(mesh, sel) {
2993
+ this.#id(mesh);
2994
+ checkSelection(sel, mesh, meshAdds(this).stamp(mesh));
2995
+ if (sel.vertices.length === 0) throw invalid("isolate needs a non-empty selection");
2996
+ const inSet = new Set(sel.vertices);
2997
+ const indices = this.views(mesh).indices().slice();
2998
+ const drop = [];
2999
+ for (let t = 0; t * 3 + 2 < indices.length; t++) {
3000
+ const a = indices[t * 3];
3001
+ const b = indices[t * 3 + 1];
3002
+ const c = indices[t * 3 + 2];
3003
+ if (a === 0 && b === 0 && c === 0) continue;
3004
+ if (!inSet.has(a) && !inSet.has(b) && !inSet.has(c)) drop.push(t);
3005
+ }
3006
+ if (drop.length > 0) this.edit(mesh, [{
3007
+ op: "removeTriangles",
3008
+ triangles: Uint32Array.from(drop)
3009
+ }]);
3010
+ return {
3011
+ removedTriangles: drop.length,
3012
+ selection: {
3013
+ mesh,
3014
+ vertices: sel.vertices.slice(),
3015
+ stamp: meshAdds(this).stamp(mesh)
3016
+ }
3017
+ };
3018
+ }
3019
+ /**
3020
+ * Adds a signed distance field: one value per vertex slot of `on`, the
3021
+ * distance to `to` as placed (negative inside), `Infinity` beyond
3022
+ * `maxDistance`, NaN for dead or unused vertices. With several meshes in
3023
+ * `to`, the smallest over them, ties going to the earliest. It follows
3024
+ * edits and placements by the mesh modes, like normals. Removing a mesh of
3025
+ * `to` removes it from the field, or the field with its last target.
3026
+ *
3027
+ * @deprecated Use `scene.inspect.addDistanceField()` instead.
3028
+ * @throws `INVALID_ARGUMENT` when `to` is empty, holds `on` or a mesh twice, `maxDistance` is negative or NaN, or the name is taken.
3029
+ */
3030
+ addDistanceField(desc) {
3031
+ return this.#addField(desc, false);
3032
+ }
3033
+ /**
3034
+ * Adds a per-vertex wall-thickness field: one value per vertex slot of
3035
+ * `on`, the distance to the opposite surface along the vertex's smooth
3036
+ * normal, in world units. Open sheets and rims read NaN, hits beyond
3037
+ * `maxDistance` read `Infinity`. It follows edits and placements by the
3038
+ * mesh modes, like normals, and colours like any field.
3039
+ *
3040
+ * @deprecated Use `scene.inspect.addThicknessField()` instead.
3041
+ * @throws `INVALID_ARGUMENT` when `maxDistance` is negative or NaN, or the name is taken.
3042
+ */
3043
+ addThicknessField(desc) {
3044
+ const s = this.#scene();
3045
+ const ids = this.#flatIds([desc.on]);
3046
+ if (typeof desc.name !== "string") throw invalid("name must be a string");
3047
+ const raw = call(() => s.add_thickness_field(desc.name, ids, desc.maxDistance));
3048
+ return this.#rawHandle(this.#fields, () => new FieldHandle(), raw);
3049
+ }
3050
+ /**
3051
+ * Adds a per-vertex curvature field: one value per vertex slot of `on`,
3052
+ * the signed mean curvature there, in 1/world-units (positive on domes,
3053
+ * negative in bowls, zero on flats). It follows edits and placements by
3054
+ * the mesh modes, like normals, and colours like any field.
3055
+ *
3056
+ * @deprecated Use `scene.inspect.addCurvatureField()` instead.
3057
+ * @throws `INVALID_ARGUMENT` when the name is taken.
3058
+ */
3059
+ addCurvatureField(desc) {
3060
+ const s = this.#scene();
3061
+ const ids = this.#flatIds([desc.on]);
3062
+ if (typeof desc.name !== "string") throw invalid("name must be a string");
3063
+ const raw = call(() => s.add_curvature_field(desc.name, ids));
3064
+ return this.#rawHandle(this.#fields, () => new FieldHandle(), raw);
3065
+ }
3066
+ /** `addDistanceField`, or with `deferred` its internal variant that computes nothing yet. */
3067
+ #addField(desc, deferred) {
3068
+ const s = this.#scene();
3069
+ const ids = this.#flatIds([desc.on, ...targetsOf(desc.to)]);
3070
+ const sign = codeIn(SIGNS, desc.sign ?? "auto", "sign");
3071
+ if (typeof desc.name !== "string") throw invalid("name must be a string");
3072
+ 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));
3073
+ return this.#rawHandle(this.#fields, () => new FieldHandle(), raw);
3074
+ }
3075
+ /** Removes a field, and a colouring by it. Its handle then gives `UNKNOWN_FIELD`. */
3076
+ removeField(field) {
3077
+ const raw = this.#field(field);
3078
+ call(() => this.#scene().remove_field(raw));
3079
+ }
3080
+ /**
3081
+ * A zero-copy view of the field's values as of its last update, one per
3082
+ * vertex slot. Like render views, it is only valid until the next call
3083
+ * that may allocate (a kept one may read other data or be empty): get it
3084
+ * right before use.
3085
+ */
3086
+ fieldValues(field) {
3087
+ const raw = this.#field(field);
3088
+ const s = this.#peek();
3089
+ const ptr = call(() => s.field_values_ptr(raw));
3090
+ const view = new Float32Array(wasmMemory().buffer, ptr, call(() => s.field_values_len(raw)));
3091
+ return this.#guard === void 0 ? view : this.#guard.wrap(view);
3092
+ }
3093
+ /**
3094
+ * Per vertex slot, the index in {@link Scene.fieldTargets} of the target
3095
+ * the field's value came from, or `0xffffffff` for none (`Infinity` or
3096
+ * NaN). A copy, as of the field's last update.
3097
+ */
3098
+ fieldNearest(field) {
3099
+ const raw = this.#field(field);
3100
+ return call(() => this.#peek().field_nearest(raw));
3101
+ }
3102
+ /** The field's target meshes, in index order (a removed target leaves the list). */
3103
+ fieldTargets(field) {
3104
+ const raw = this.#field(field);
3105
+ const flat = call(() => this.#peek().field_targets(raw));
3106
+ const out = [];
3107
+ for (let i = 0; i < flat.length; i += 2) out.push(this.#meshHandle(flat[i], flat[i + 1]));
3108
+ return out;
3109
+ }
3110
+ /**
3111
+ * What the sign data found out about each of the field's targets, in the
3112
+ * order of {@link Scene.fieldTargets}.
3113
+ */
3114
+ fieldTargetStatus(field) {
3115
+ const raw = this.#field(field);
3116
+ const st = call(() => this.#peek().field_target_status(raw));
3117
+ const out = [];
3118
+ for (let i = 0; i < st.length; i += 5) out.push({
3119
+ mode: st[i] === 2 ? "winding" : "pseudonormal",
3120
+ closed: st[i + 1] === 1,
3121
+ consistentOrientation: st[i + 2] === 1,
3122
+ nonManifoldVertices: st[i + 3],
3123
+ degenerateTriangles: st[i + 4]
3124
+ });
3125
+ return out;
3126
+ }
3127
+ /**
3128
+ * Whether the field is current, and what its sign data found out about the
3129
+ * target meshes, together (see {@link FieldStatus.sign}).
3130
+ */
3131
+ fieldStatus(field) {
3132
+ const raw = this.#field(field);
3133
+ const st = call(() => this.#peek().field_status(raw));
3134
+ return {
3135
+ current: st[0] === 1,
3136
+ sign: {
3137
+ mode: st[1] === 2 ? "winding" : "pseudonormal",
3138
+ closed: st[2] === 1,
3139
+ consistentOrientation: st[3] === 1,
3140
+ nonManifoldVertices: st[4],
3141
+ degenerateTriangles: st[5]
3142
+ }
3143
+ };
3144
+ }
3145
+ /**
3146
+ * Colours a mesh from one of its fields (`views(mesh).colors()`), or turns
3147
+ * colouring off with `null`, after which `colors()` returns `null`. Every
3148
+ * vertex is recoloured and reported as `"all"`; later field updates (edits,
3149
+ * drags) report only the vertices whose colour may change. A display
3150
+ * setting: never recorded in history.
3151
+ *
3152
+ * @throws `INVALID_ARGUMENT` when the field is not on `mesh` or the rule is invalid; `UNKNOWN_FIELD`.
3153
+ */
3154
+ setColoring(mesh, rule) {
3155
+ const { index, generation } = this.#id(mesh);
3156
+ if (rule === null) {
3157
+ call(() => this.#scene().clear_coloring(index, generation));
3158
+ this.#rules.delete(mesh);
3159
+ return;
3160
+ }
3161
+ const field = this.#field(rule.field);
3162
+ const { map, values } = encodeRule(rule);
3163
+ call(() => this.#scene().set_coloring(index, generation, field, map, values));
3164
+ this.#rules.set(mesh, copyRule(rule));
3165
+ }
3166
+ /**
3167
+ * The rule the mesh is coloured by (a frozen copy of the one given to
3168
+ * {@link Scene.setColoring}, the same object on every read), or `null`
3169
+ * without colouring (never set, turned off, or its field removed).
3170
+ *
3171
+ * @throws `UNKNOWN_MESH`.
3172
+ */
3173
+ coloring(mesh) {
3174
+ const { index, generation } = this.#id(mesh);
3175
+ return call(() => this.#peek().values_ptr(index, generation)) !== 0 ? this.#rules.get(mesh) ?? null : null;
3176
+ }
3177
+ static {
3178
+ meshAddsOf = (scene) => ({
3179
+ beginUpload: (vertices, triangles, options = {}) => {
3180
+ const s = scene.#scene();
3181
+ const mode = modeCode(options.mode ?? "eager");
3182
+ const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
3183
+ return call(() => s.begin_add_mesh_upload(vertices, triangles, origin, mode, options.normals ?? true));
3184
+ },
3185
+ pushPositions: (token, chunk) => call(() => scene.#scene().add_mesh_push_positions(token, chunk)),
3186
+ pushIndices: (token, chunk) => call(() => scene.#scene().add_mesh_push_indices(token, chunk)),
3187
+ pushUvs: (token, chunk) => call(() => scene.#scene().add_mesh_push_uvs(token, chunk)),
3188
+ step: (token, budget) => call(() => scene.#scene().add_mesh_step(token, budget)),
3189
+ buffers: (token) => {
3190
+ const [pp, pl, np, nl, ip, il] = call(() => scene.#peek().add_mesh_buffers(token));
3191
+ const memory = wasmMemory().buffer;
3192
+ return {
3193
+ positions: new Float32Array(memory, pp, pl),
3194
+ normals: np === 0 ? null : new Float32Array(memory, np, nl),
3195
+ indices: new Uint32Array(memory, ip, il)
3196
+ };
3197
+ },
3198
+ finish: (token) => {
3199
+ const id = call(() => scene.#scene().finish_add_mesh(token));
3200
+ return scene.#meshHandle(id[0], id[1]);
3201
+ },
3202
+ stamp: (mesh) => {
3203
+ const { index, generation } = scene.#id(mesh);
3204
+ return call(() => scene.#peek().content_stamp(index, generation));
3205
+ },
3206
+ drop: (token) => call(() => scene.#peek().drop_add_mesh(token))
3207
+ });
3208
+ }
3209
+ static {
3210
+ geodesicStepsOf = (scene) => ({
3211
+ begin: (mesh, sources, options = {}) => {
3212
+ const { index, generation } = scene.#id(mesh);
3213
+ const src = normalizeSourceVertices(sources);
3214
+ const norm = normalizeGeodesicOptions(options);
3215
+ return call(() => scene.#peek().begin_geodesic_distances(index, generation, src, GEODESIC_METHOD_CODES[norm.method], optional(norm.maxDistance, "maxDistance"), optional(norm.timeStepScale, "timeStepScale")));
3216
+ },
3217
+ step: (token, work) => call(() => scene.#peek().step_geodesic_distances(token, work)),
3218
+ finish: (token) => call(() => scene.#peek().finish_geodesic_distances(token)),
3219
+ drop: (token) => call(() => scene.#peek().drop_geodesic_distances(token))
3220
+ });
3221
+ }
3222
+ static {
3223
+ fieldStepsOf = (scene) => ({
3224
+ setDefer: (on) => call(() => scene.#peek().set_defer_fields(on)),
3225
+ step: (points) => {
3226
+ const s = scene.#scene();
3227
+ const state = call(() => s.field_step(points));
3228
+ return state === 0 ? "idle" : state === 1 ? "pending" : "done";
3229
+ },
3230
+ addDeferred: (desc) => scene.#addField(desc, true),
3231
+ stepField: (field, points) => {
3232
+ const raw = scene.#field(field);
3233
+ const s = scene.#scene();
3234
+ const state = call(() => s.field_step_field(raw, points));
3235
+ return state === 0 ? "idle" : state === 1 ? "pending" : "done";
3236
+ },
3237
+ withdraw: (field) => {
3238
+ const raw = scene.#field(field);
3239
+ return call(() => scene.#scene().withdraw_field(raw));
3240
+ },
3241
+ abandon: () => call(() => scene.#peek().abandon_field_step()),
3242
+ meshes: () => {
3243
+ const flat = call(() => scene.#peek().field_step_meshes());
3244
+ const out = [];
3245
+ for (let k = 0; k < flat.length; k += 2) out.push(scene.#meshHandle(flat[k], flat[k + 1]));
3246
+ return out;
3247
+ }
3248
+ });
3249
+ }
3250
+ /**
3251
+ * Adds a plane section of `meshes`. Results of `"eager"` meshes are computed
3252
+ * right away; others on {@link Scene.updateSections} or `flush()`.
3253
+ *
3254
+ * @throws `INVALID_ARGUMENT` for a zero normal or a mesh listed twice.
3255
+ */
3256
+ addSection(desc) {
3257
+ const s = this.#scene();
3258
+ const plane = this.#plane(desc.plane);
3259
+ const meshes = this.#flatIds(desc.meshes);
3260
+ const raw = call(() => s.add_section(plane, meshes, desc.fill ?? false));
3261
+ return this.#rawHandle(this.#sections, () => new SectionHandle(), raw);
3262
+ }
3263
+ /** Moves a section's plane. */
3264
+ setSectionPlane(section, plane) {
3265
+ const raw = this.#section(section);
3266
+ const p = this.#plane(plane);
3267
+ call(() => this.#scene().set_section_plane(raw, p));
3268
+ }
3269
+ /**
3270
+ * A section's plane as last set by {@link Scene.addSection} or
3271
+ * {@link Scene.setSectionPlane}, the normal normalised. Results not yet
3272
+ * recomputed (`"stale"`) may still be cut with an earlier plane.
3273
+ */
3274
+ sectionPlane(section) {
3275
+ const raw = this.#section(section);
3276
+ const p = call(() => this.#peek().section_desc_plane(raw));
3277
+ return {
3278
+ origin: vec3At(p, 0),
3279
+ normal: vec3At(p, 3)
3280
+ };
3281
+ }
3282
+ /** Changes the meshes a section cuts. */
3283
+ setSectionMeshes(section, meshes) {
3284
+ const raw = this.#section(section);
3285
+ const ids = this.#flatIds(meshes);
3286
+ call(() => this.#scene().set_section_meshes(raw, ids));
3287
+ }
3288
+ /** Turns a section's fill on or off. */
3289
+ setSectionFill(section, fill) {
3290
+ const raw = this.#section(section);
3291
+ call(() => this.#scene().set_section_fill(raw, fill));
3292
+ }
3293
+ /** Removes a section. Its handle then gives `UNKNOWN_SECTION`. */
3294
+ removeSection(section) {
3295
+ const raw = this.#section(section);
3296
+ call(() => this.#scene().remove_section(raw));
3297
+ }
3298
+ /** Computes every stale section result, whatever the mesh modes. */
3299
+ updateSections() {
3300
+ const s = this.#scene();
3301
+ call(() => s.update_sections());
3302
+ }
3303
+ /**
3304
+ * A section's result for one of its meshes as of its last computation
3305
+ * (empty before the first), copied, in world coordinates.
3306
+ *
3307
+ * @throws `INVALID_ARGUMENT` when the section does not cut `mesh`.
3308
+ */
3309
+ section(section, mesh) {
3310
+ const raw = this.#section(section);
3311
+ const { index, generation } = this.#id(mesh);
3312
+ const r = call(() => this.#peek().section(raw, index, generation));
3313
+ const contours = [];
3314
+ let at = 4;
3315
+ for (let k = 0; k < r[3]; k++) {
3316
+ const n = 3 * r[at + 1];
3317
+ const points64 = r.slice(at + 2, at + 2 + n);
3318
+ contours.push({
3319
+ closed: r[at] === 1,
3320
+ points: Float32Array.from(points64),
3321
+ points64
3322
+ });
3323
+ at += 2 + n;
3324
+ }
3325
+ const result = {
3326
+ status: r[0] === 0 ? "current" : "stale",
3327
+ contours,
3328
+ length: r[1],
3329
+ area: r[2]
3330
+ };
3331
+ if (r[at] === 1) {
3332
+ const np = 3 * r[at + 1];
3333
+ const positions64 = r.slice(at + 2, at + 2 + np);
3334
+ const positions = Float32Array.from(positions64);
3335
+ at += 2 + np;
3336
+ result.fill = {
3337
+ positions,
3338
+ positions64,
3339
+ indices: Uint32Array.from(r.subarray(at + 1, at + 1 + 3 * r[at]))
3340
+ };
3341
+ }
3342
+ return result;
3343
+ }
3344
+ /**
3345
+ * The closest pair between two meshes' contours in a section, measured in
3346
+ * the plane, or `null` when either has none or their results were cut with
3347
+ * different planes (call {@link Scene.updateSections} first).
3348
+ */
3349
+ sectionGap(section, a, b) {
3350
+ const raw = this.#section(section);
3351
+ const ia = this.#id(a);
3352
+ const ib = this.#id(b);
3353
+ const g = call(() => this.#scene().section_gap(raw, ia.index, ia.generation, ib.index, ib.generation));
3354
+ return g.length === 0 ? null : {
3355
+ distance: g[0],
3356
+ a: vec3At(g, 1),
3357
+ b: vec3At(g, 4)
3358
+ };
3359
+ }
3360
+ #hasNormals(index, generation) {
3361
+ const s = this.#peek();
3362
+ return s.normals_len(index, generation) > 0 || s.vertex_count(index, generation) === 0;
3363
+ }
3364
+ /**
3365
+ * Selects triangles enclosed by or intersecting a screen-space rectangle or lasso in NDC. The
3366
+ * camera is in world coordinates and taken in `f64`: see {@link ScreenSelectOptions.viewProj}.
3367
+ */
3368
+ selectFacesScreen(mesh, shape, options) {
3369
+ const { index, generation } = this.#id(mesh);
3370
+ const n = normalizeScreenSelectArgs(shape, options);
3371
+ return call(() => this.#scene().select_faces_screen(index, generation, n.shapeKind, n.shapeData, n.viewProj, Float64Array.from(n.cameraOrigin), Float64Array.from(n.cameraForward), n.isOrthographic, n.visibleOnly, n.rejectBackfaces, n.includeTouching));
3372
+ }
3373
+ /** Selects triangles intersecting a world-space sphere (optionally restricted by a normal cone). */
3374
+ selectFacesInSphere(mesh, center, radius, normalCone) {
3375
+ const { index, generation } = this.#id(mesh);
3376
+ const n = normalizeSelectInSphereArgs(center, radius, normalCone);
3377
+ return call(() => this.#scene().select_faces_in_sphere(index, generation, n.center, n.radius, n.normal, n.coneAngleRad));
3378
+ }
3379
+ /** Flood-fills triangles across edges whose dihedral angle does not exceed `maxDihedralRad`. */
3380
+ selectByCreaseAngle(mesh, seedTri, maxDihedralRad) {
3381
+ const { index, generation } = this.#id(mesh);
3382
+ return call(() => this.#peek().select_by_crease_angle(index, generation, checkU32Arg(seedTri, "seedTri"), checkNonNegativeArg(maxDihedralRad, "maxDihedralRad")));
3383
+ }
3384
+ /** Selects the edge-connected shell containing `seedTri`. */
3385
+ selectConnectedShell(mesh, seedTri) {
3386
+ const { index, generation } = this.#id(mesh);
3387
+ return call(() => this.#peek().select_connected_shell(index, generation, checkU32Arg(seedTri, "seedTri")));
3388
+ }
3389
+ /** Selects small edge-connected face islands bounded by `maxFaceCount` and optional `maxArea`. */
3390
+ selectSmallFaceIslands(mesh, maxFaceCount, maxArea) {
3391
+ const { index, generation } = this.#id(mesh);
3392
+ const n = normalizeSelectSmallIslandsArgs(maxFaceCount, maxArea);
3393
+ return call(() => this.#peek().select_small_face_islands(index, generation, n.maxFaceCount, n.maxArea));
3394
+ }
3395
+ /** Expands `selectedTris` outward by `rings` topological rings. */
3396
+ growFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
3397
+ const { index, generation } = this.#id(mesh);
3398
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
3399
+ return call(() => this.#peek().grow_face_selection(index, generation, n.selectedTris, n.rings, n.adjacency));
3400
+ }
3401
+ /** Erodes `selectedTris` inward by `rings` topological rings. */
3402
+ shrinkFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
3403
+ const { index, generation } = this.#id(mesh);
3404
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
3405
+ return call(() => this.#peek().shrink_face_selection(index, generation, n.selectedTris, n.rings, n.adjacency));
3406
+ }
3407
+ /** Fills interior unselected triangle holes up to `maxHoleTris`. */
3408
+ fillSelectionHoles(mesh, selectedTris, maxHoleTris) {
3409
+ const { index, generation } = this.#id(mesh);
3410
+ return call(() => this.#peek().fill_selection_holes(index, generation, normalizeU32Selection(selectedTris), checkU32Arg(maxHoleTris, "maxHoleTris")));
3411
+ }
3412
+ /** Smooths jagged boundaries of a face selection via majority-neighbor voting. */
3413
+ smoothSelectionBoundary(mesh, selectedTris, iterations = 1) {
3414
+ const { index, generation } = this.#id(mesh);
3415
+ return call(() => this.#peek().smooth_selection_boundary(index, generation, normalizeU32Selection(selectedTris), checkU32Arg(iterations, "iterations")));
3416
+ }
3417
+ /** Converts a face selection into per-vertex `[0, 1]` coverage weights aligned with `vertexSlots()`. */
3418
+ faceSelectionToVertexMask(mesh, selectedTris) {
3419
+ const { index, generation } = this.#id(mesh);
3420
+ return call(() => this.#peek().face_selection_to_vertex_mask(index, generation, normalizeU32Selection(selectedTris)));
3421
+ }
3422
+ /** Converts a per-vertex scalar mask into selected triangle indices. */
3423
+ vertexMaskToFaceSelection(mesh, mask, threshold = .5, requireAllVertices = false) {
3424
+ const { index, generation } = this.#id(mesh);
3425
+ const n = normalizeVertexMaskSelectArgs(mask, threshold, requireAllVertices);
3426
+ return call(() => this.#peek().vertex_mask_to_face_selection(index, generation, n.mask, n.threshold, n.requireAllVertices));
3427
+ }
3428
+ /** Deletes `selectedTris` from `mesh` in one undo step. */
3429
+ deleteSelectedFaces(mesh, selectedTris) {
3430
+ const { index, generation } = this.#id(mesh);
3431
+ const raw = call(() => this.#scene().delete_selected_faces(index, generation, normalizeU32Selection(selectedTris)));
3432
+ return decodeFaceEditReport(raw);
3433
+ }
3434
+ /**
3435
+ * Extrudes `triangles` of `mesh`: moves them by `options.distance` (world
3436
+ * units) and builds side walls between where the selection's boundary was
3437
+ * and where it went, as one undo step. A closed, consistently wound mesh
3438
+ * stays closed and consistently wound.
3439
+ *
3440
+ * Each region of the selection moves along its average normal by default;
3441
+ * see {@link ExtrudeFacesOptions.direction}. Selections with holes get walls
3442
+ * around them, and regions that touch at a vertex separate there. Selected
3443
+ * edges on the mesh's open boundary get walls too. The triangles keep their
3444
+ * slots and are the moved faces, so the same selection extrudes them again.
3445
+ *
3446
+ * Self-intersections of the result are reported, not refused: pushing a
3447
+ * face through the other side of a thin part, say, gives a closed mesh that
3448
+ * crosses itself.
3449
+ *
3450
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for an empty selection, a slot
3451
+ * without a live triangle, a distance or direction that is zero or not
3452
+ * finite, a selected edge shared by three or more triangles, selected
3453
+ * triangles wound against each other, or a region whose normals cancel out
3454
+ * (give a direction then); `UNKNOWN_MESH` for a removed mesh. The mesh is
3455
+ * unchanged on error.
3456
+ */
3457
+ extrudeFaces(mesh, triangles, options) {
3458
+ const { index, generation } = this.#id(mesh);
3459
+ const tris = normalizeU32Selection(triangles, "triangles");
3460
+ const { distance, mode, direction, check } = extrudeFacesArgs(options);
3461
+ return decodeExtrudeFaces(call(() => this.#scene().extrude_faces(index, generation, tris, distance, mode, direction, check)));
3462
+ }
3463
+ /**
3464
+ * Turns an open surface into a solid, as one undo step: runs boundary loops
3465
+ * of `mesh` along a world direction (down by default) to a flat plane
3466
+ * perpendicular to it, joins each with a wall and closes it with a flat cap.
3467
+ * The plane is at `options.height`, or `options.offset` past the mesh's
3468
+ * furthest vertex.
3469
+ *
3470
+ * By default only the longest loop is extruded, so fill smaller holes first
3471
+ * (or pass `loops: "all"`, which makes them holes through the solid). A
3472
+ * surface that faces the base is turned around, so that the solid faces
3473
+ * outward ({@link ExtrudeBaseResult.flipped}).
3474
+ *
3475
+ * Self-intersections of the result are reported, not refused: a plane that
3476
+ * cuts through the surface, say.
3477
+ *
3478
+ * @throws {FastMeshError} `INVALID_ARGUMENT` when the mesh has no boundary
3479
+ * loop, a loop is open or not clean (orient or repair the mesh first), a
3480
+ * boundary vertex does not lie before the plane, or a loop's outline on
3481
+ * the plane crosses itself; `STALE_LOOPS` for a loop id that matches no
3482
+ * loop; `UNKNOWN_MESH` for a removed mesh. The mesh is unchanged on error.
3483
+ */
3484
+ extrudeBase(mesh, options) {
3485
+ const { index, generation } = this.#id(mesh);
3486
+ const a = extrudeBaseArgs(options);
3487
+ return decodeExtrudeBase(call(() => this.#scene().extrude_base(index, generation, a.direction, a.plane, a.value, a.which, a.loops, a.refine, a.check)));
3488
+ }
3489
+ /**
3490
+ * Extracts `selectedTris` into a new standalone mesh preserving exact world
3491
+ * coordinates, as one undo step: {@link Scene.undo} removes the new mesh and
3492
+ * {@link Scene.redo} brings it back with the same handle.
3493
+ */
3494
+ extractSelectedFaces(mesh, selectedTris, options = {}) {
3495
+ const { index, generation } = this.#id(mesh);
3496
+ const normals = checkBooleanArg(options.normals, this.#hasNormals(index, generation), "normals");
3497
+ const id = call(() => this.#scene().extract_selected_faces(index, generation, normalizeU32Selection(selectedTris), normals));
3498
+ return this.#meshHandle(id[0], id[1]);
3499
+ }
3500
+ /**
3501
+ * Splits `selectedTris` off into a new detached mesh and removes them from
3502
+ * `mesh`, as one undo step: {@link Scene.undo} makes `mesh` whole again and
3503
+ * removes the new mesh, which {@link Scene.redo} brings back with the same
3504
+ * handle.
3505
+ */
3506
+ splitSelectedFaces(mesh, selectedTris, options = {}) {
3507
+ const { index, generation } = this.#id(mesh);
3508
+ const normals = checkBooleanArg(options.normals, this.#hasNormals(index, generation), "normals");
3509
+ const raw = call(() => this.#scene().split_selected_faces(index, generation, normalizeU32Selection(selectedTris), normals));
3510
+ return {
3511
+ detached: this.#meshHandle(raw[0], raw[1]),
3512
+ removedTriangles: raw[2],
3513
+ removedVertices: raw[3]
3514
+ };
3515
+ }
3516
+ /**
3517
+ * Builds a zero-offset FFD lattice around `mesh`, in its local coordinates
3518
+ * and along its own axes; `padding` is in its own units.
3519
+ */
3520
+ buildFfdLattice(mesh, dims, basis = "bernstein", padding = 0) {
3521
+ const { index, generation } = this.#id(mesh);
3522
+ const n = normalizeBuildFfdLatticeArgs(dims, basis, padding);
3523
+ return decodeFfdLattice(call(() => this.#peek().build_ffd_lattice(index, generation, n.dims, n.basis, n.padding)));
3524
+ }
3525
+ /** Applies Free-Form Deformation (FFD) in one undo step. */
3526
+ applyFfd(mesh, options) {
3527
+ const { index, generation } = this.#id(mesh);
3528
+ const n = normalizeFfdArgs(options);
3529
+ return decodeFreeformReport(call(() => this.#scene().apply_ffd(index, generation, n.dims, n.basis, n.frame15, n.offsets, n.outsideMode, n.regionCenter, n.regionRadius, n.vertices, n.protectedVerts, n.protectionWeights)));
3530
+ }
3531
+ /** Applies As-Rigid-As-Possible (ARAP) surface deformation in one undo step. */
3532
+ applyArap(mesh, options) {
3533
+ const { index, generation } = this.#id(mesh);
3534
+ const n = normalizeArapArgs(options);
3535
+ return decodeFreeformReport(call(() => this.#scene().apply_arap(index, generation, n.anchorVerts, n.anchorPos, n.anchorHasPos, n.handleVerts, n.handleTargets, n.weights, n.solver, n.iterations, n.tolerance, n.regionCenter, n.regionRadius, n.vertices, n.protectedVerts, n.protectionWeights)));
3536
+ }
3537
+ /** Applies a regularized elastic Kelvinlet deformation in one undo step. */
3538
+ applyKelvinlet(mesh, options) {
3539
+ const { index, generation } = this.#id(mesh);
3540
+ const n = normalizeKelvinletArgs(options);
3541
+ return decodeFreeformReport(call(() => this.#scene().apply_kelvinlet(index, generation, n.center, n.loadKind, n.loadData, n.epsilon, n.nu, n.mu, n.scaleMode, n.scaleAlpha, n.symX, n.symY, n.symZ, n.regionCenter, n.regionRadius, n.vertices, n.protectedVerts, n.protectionWeights)));
3542
+ }
3543
+ /** Runs an XPBD soft-body solve with optional self-collision handling in one undo step. */
3544
+ applyXpbd(mesh, options) {
3545
+ const { index, generation } = this.#id(mesh);
3546
+ const n = normalizeXpbdArgs(options);
3547
+ return decodeFreeformReport(call(() => this.#scene().apply_xpbd(index, generation, n.substeps, n.iterations, n.dt, n.stretchCompliance, n.bendCompliance, n.volumeCompliance, n.damping, n.gravity, n.pinVerts, n.pinTargets, n.handleVerts, n.handleTargets, n.handleCompliances, n.selfCollision, n.collisionThickness, n.protectedVerts, n.protectionWeights)));
3548
+ }
3549
+ /** Sets the scene's fallback inter-object collision rule. */
3550
+ setDefaultCollisionRule(rule) {
3551
+ const flat = encodeCollisionRule(normalizeCollisionRule(rule));
3552
+ call(() => this.#scene().set_default_collision_rule(flat));
3553
+ }
3554
+ /** Returns the scene's fallback inter-object collision rule. */
3555
+ defaultCollisionRule() {
3556
+ return decodeCollisionRule(call(() => this.#peek().default_collision_rule()));
3557
+ }
3558
+ /** Configures the collision response rule for unordered pair `(a, b)`. */
3559
+ setCollisionRule(a, b, rule) {
3560
+ const ia = this.#id(a);
3561
+ const ib = this.#id(b);
3562
+ const flat = encodeCollisionRule(normalizeCollisionRule(rule));
3563
+ call(() => this.#scene().set_collision_rule(ia.index, ia.generation, ib.index, ib.generation, flat));
3564
+ }
3565
+ /** Clears any pair-specific collision override for `(a, b)`, returning `true` if one existed. */
3566
+ clearCollisionRule(a, b) {
3567
+ const ia = this.#id(a);
3568
+ const ib = this.#id(b);
3569
+ return call(() => this.#scene().clear_collision_rule(ia.index, ia.generation, ib.index, ib.generation));
3570
+ }
3571
+ /** Returns the effective collision rule for `(a, b)`. */
3572
+ collisionRule(a, b) {
3573
+ const ia = this.#id(a);
3574
+ const ib = this.#id(b);
3575
+ return decodeCollisionRule(call(() => this.#peek().collision_rule(ia.index, ia.generation, ib.index, ib.generation)));
3576
+ }
3577
+ /** True when `mesh` participates in at least one active non-passThrough collision rule. */
3578
+ hasActiveCollisionResponse(mesh) {
3579
+ const { index, generation } = this.#id(mesh);
3580
+ return call(() => this.#peek().has_active_collision_response(index, generation));
3581
+ }
3582
+ /** Moves `mesh` toward `placement` with inter-object collision detection and response. */
3583
+ moveWithCollision(mesh, placement, isRelease = false) {
3584
+ const { index, generation } = this.#id(mesh);
3585
+ const n = normalizePlacementInputArgs(placement);
3586
+ const scale = n.scale ? [
3587
+ n.scale[0],
3588
+ n.scale[1],
3589
+ n.scale[2]
3590
+ ] : this.placement(mesh).scale ?? [
3591
+ 1,
3592
+ 1,
3593
+ 1
3594
+ ];
3595
+ const raw = call(() => this.#scene().move_with_collision(index, generation, n.rotation, n.translation, n.scale, checkBooleanArg(isRelease, false, "isRelease")));
3596
+ return decodeCollisionStepReport(raw, (i, g) => this.#meshHandle(i, g), scale);
3597
+ }
3598
+ /** Finalizes queued release actions (deferred cuts, elastic recovery) for `mesh`. */
3599
+ commitCollisionInteraction(mesh) {
3600
+ const { index, generation } = this.#id(mesh);
3601
+ const scale = this.placement(mesh).scale;
3602
+ const raw = call(() => this.#scene().commit_collision_interaction(index, generation));
3603
+ return decodeCollisionStepReport(raw, (i, g) => this.#meshHandle(i, g), scale);
3604
+ }
3605
+ /**
3606
+ * Fits a geometric primitive (`plane`, `sphere`, `cylinder`, `cone`, or
3607
+ * `auto`) in world space, as precisely far from the world origin as near it.
3608
+ */
3609
+ fitPrimitive(mesh, options = {}) {
3610
+ const { index, generation } = this.#id(mesh);
3611
+ const n = normalizeFitPrimitiveArgs(options);
3612
+ return decodeFitPrimitiveReport(call(() => this.#peek().fit_primitive(index, generation, n.subsetTris, n.kind, n.inlierThreshold, n.ransacIterations, n.lmIterations, n.seed, n.minInlierRatio, n.normalWeight)));
3613
+ }
3614
+ /** Rigidly aligns `mesh`'s fitted datum onto `targetAxis` and `targetOrigin` in one undo step. */
3615
+ alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin) {
3616
+ const { index, generation } = this.#id(mesh);
3617
+ const n = normalizeAlignToPrimitiveArgs(primitive, targetAxis, targetOrigin);
3618
+ return decodePlacement15(call(() => this.#scene().align_to_fitted_primitive(index, generation, n.prim9, n.targetAxis, n.targetOrigin)));
3619
+ }
3620
+ /**
3621
+ * Slices world-space planar contours through `mesh`, as precisely far from
3622
+ * the world origin as near it: take the points from `points3d64` there
3623
+ * (`points3d` is `f32`). `origin` may be anywhere on the plane.
3624
+ */
3625
+ sliceContours(mesh, origin, normal) {
3626
+ const { index, generation } = this.#id(mesh);
3627
+ const n = normalizeSliceContoursArgs(origin, normal);
3628
+ return decodeContourSlices(call(() => this.#peek().slice_contours(index, generation, n.origin, n.normal)))[0];
3629
+ }
3630
+ /** Slices an evenly spaced stack of `count` parallel contours through `mesh`, each as {@link Scene.sliceContours}. */
3631
+ sliceContourStack(mesh, origin, normal, spacing, count) {
3632
+ const { index, generation } = this.#id(mesh);
3633
+ const n = normalizeSliceContourStackArgs(origin, normal, spacing, count);
3634
+ return decodeContourSlices(call(() => this.#peek().slice_contour_stack(index, generation, n.origin, n.normal, n.spacing, n.count)));
3635
+ }
3636
+ /**
3637
+ * Reconstructs a triangle mesh from a packed point cloud and adds it to the
3638
+ * scene, as one undo step: {@link Scene.undo} removes it and
3639
+ * {@link Scene.redo} brings it back with the same handle.
3640
+ *
3641
+ * The cloud's `origin` is the mesh's {@link Scene.origin}. Without one, and
3642
+ * for a bare buffer, the positions are world positions in `f32`, which far
3643
+ * from the world origin are off by up to half of its steps (0.004 at 1e5):
3644
+ * see {@link PackedPointCloud} for clouds there.
3645
+ */
3646
+ reconstructPointCloud(cloud, options = {}) {
3647
+ const buf = cloudBuffer(cloud);
3648
+ const at = cloudOrigin(cloud);
3649
+ const origin = at === void 0 ? void 0 : Float64Array.from(at);
3650
+ const n = normalizeReconstructArgs(options);
3651
+ const id = call(() => this.#scene().reconstruct_point_cloud(buf, n.method, n.voxelSize, n.ballRadius, n.kNeighbors, n.normals, origin));
3652
+ return this.#meshHandle(id[0], id[1]);
3653
+ }
3654
+ /** Hollows `mesh` with optional per-vertex wall thickness modulation in one undo step. */
3655
+ hollowMesh(mesh, options) {
3656
+ const { index, generation } = this.#id(mesh);
3657
+ const n = normalizeHollowArgs(options);
3658
+ return decodeHollowReport(call(() => this.#scene().hollow_mesh(index, generation, n.wallThickness, n.backend, n.voxelSize, n.maxVoxels, n.maxCavityTriangles, n.minCavityVolume, n.modulationVerts, n.modulationWeights)));
3659
+ }
3660
+ /**
3661
+ * Plans the voxel grid of {@link Scene.latticeFill} for the same mesh and
3662
+ * options without running it: its dimensions, voxel size, voxel count,
3663
+ * estimated triangles and memory, the share of space the walls fill, and
3664
+ * whether the grid is within `maxVoxels`. Costs a few passes over the mesh
3665
+ * (tens of milliseconds at a million triangles), so it can follow a
3666
+ * settings form.
3667
+ *
3668
+ * @throws {FastMeshError} as {@link Scene.latticeFill}, except that the mesh
3669
+ * is not checked for being closed, and that a grid over the limit comes
3670
+ * back with `fits: false`.
3671
+ */
3672
+ latticePlan(mesh, options) {
3673
+ const { index, generation } = this.#id(mesh);
3674
+ const values = encodeLatticeOptions(checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS));
3675
+ return decodeLatticePlan(call(() => this.#scene().lattice_plan(index, generation, values)));
3676
+ }
3677
+ /**
3678
+ * Fills the inside of the closed, outward-wound `mesh`, or the cavity of a
3679
+ * hollowed one, with a lattice: walls of uniform thickness that follow a
3680
+ * gyroid, Schwarz P or diamond surface. One undo step.
3681
+ *
3682
+ * - Without a shell, filling the inside turns the mesh into an open
3683
+ * lattice, cut off at its surface.
3684
+ * - With `shellThickness`, the mesh's surface is kept as it is, and the
3685
+ * space between the walls is carved out from that depth on, so shell and
3686
+ * walls are one solid.
3687
+ * - In a cavity, the walls grow out of the shell that is there, whose outer
3688
+ * surface is kept as it is.
3689
+ *
3690
+ * The result is closed, manifold and free of self-intersections, as far as
3691
+ * the surface that is kept is. It is built on a voxel grid that follows
3692
+ * from the lengths, or from `voxelSize`: edges where walls meet the mesh's
3693
+ * surface are cut by a fraction of a voxel. {@link Scene.latticePlan}
3694
+ * reports the grid, the triangles and the memory beforehand, and
3695
+ * {@link Scene.latticePreview} shows the walls on a small grid.
3696
+ *
3697
+ * Lengths and volumes are measured in the world. The cells are aligned with
3698
+ * the mesh's own axes, around the middle of its bounds. Its UVs are
3699
+ * dropped. A lattice has many triangles (about 2,000 per gyroid cell at ten
3700
+ * voxels a cell, 12,000 at 25) and takes seconds at a few million: use
3701
+ * `WorkerScene.latticeFill` to keep the page live.
3702
+ *
3703
+ * @throws {FastMeshError} `INVALID_ARGUMENT` for bad options, a mesh that is
3704
+ * not closed and consistently wound outward, `region: "cavity"` without
3705
+ * a cavity, a grid over `maxVoxels` (the message has its size and
3706
+ * memory) or too coarse for the walls, the shell, the cells or the wall
3707
+ * around a cavity, or a lattice that leaves nothing, or nothing open;
3708
+ * `UNKNOWN_MESH` for a removed mesh; `OUT_OF_MEMORY`. The mesh is
3709
+ * unchanged on error.
3710
+ */
3711
+ latticeFill(mesh, options) {
3712
+ const { index, generation } = this.#id(mesh);
3713
+ const values = encodeLatticeOptions(checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS));
3714
+ return decodeLatticeReport(call(() => this.#scene().lattice_fill(index, generation, values)));
3715
+ }
3716
+ /**
3717
+ * The walls {@link Scene.latticeFill} would put into `mesh`, on a small
3718
+ * grid, without changing the mesh: buffers in its local frame, to draw at
3719
+ * its `matrix4`. The grid has at most `maxVoxels` voxels (default
3720
+ * {@link DEFAULT_LATTICE_PREVIEW_VOXELS}); walls it is too coarse for are
3721
+ * drawn two voxels thick (`plan.wallThickness`), and a part with too many
3722
+ * cells for it shows its middle only (`plan.cropped`). With a shell the
3723
+ * walls start at its inner face.
3724
+ *
3725
+ * @throws {FastMeshError} as {@link Scene.latticeFill}, except that the grid
3726
+ * always fits and that a lattice without walls is an empty preview.
3727
+ */
3728
+ latticePreview(mesh, options) {
3729
+ const { index, generation } = this.#id(mesh);
3730
+ const checked = checkLatticeOptions(options, DEFAULT_LATTICE_PREVIEW_VOXELS);
3731
+ const values = encodeLatticeOptions(checked);
3732
+ return decodeLatticePreview(call(() => this.#scene().lattice_preview(index, generation, values, checked.maxVoxels)));
3733
+ }
3734
+ /**
3735
+ * Punches a tapered/chamfered drain hole in `mesh` (with optional plug
3736
+ * generation) in one undo step: {@link Scene.undo} fills the hole again and
3737
+ * removes the plug, which {@link Scene.redo} brings back with the same
3738
+ * handle.
3739
+ */
3740
+ punchDrainHole(mesh, options) {
3741
+ const { index, generation } = this.#id(mesh);
3742
+ const n = normalizeDrainHoleArgs(options);
3743
+ const plugNormals = n.plugNormals ?? this.#hasNormals(index, generation);
3744
+ const raw = call(() => this.#scene().punch_drain_hole(index, generation, n.surfacePoint, n.surfaceNormal, n.diameter, n.depth, n.outerChamfer, n.taperAngleDeg, n.segments, n.booleanMethod, n.fallbackBvhSdf, n.generatePlug, n.plugClearance, plugNormals));
3745
+ return decodeDrainHoleReport(raw, (i, g) => this.#meshHandle(i, g));
3746
+ }
3747
+ /**
3748
+ * Places `stamp` onto `target` at a hit point/normal, optionally unioning/engraving/conformance-wrapping,
3749
+ * in one undo step. Kept separate, the placed stamp is a new mesh with the hit point as its
3750
+ * {@link Scene.origin}, which {@link Scene.undo} removes and {@link Scene.redo} brings back with
3751
+ * the same handle.
3752
+ *
3753
+ * The zero of the stamp's own coordinates goes to the hit point, or `options.stampAnchor`, which
3754
+ * says what happens with a stamp far from that zero. A `stampAnchor` far from the stamp puts it
3755
+ * as far from the hit point: kept separate (and not conforming) it is placed as precisely there,
3756
+ * around an origin of its own; merged into a target it has the precision of that mesh's `f32`
3757
+ * positions at that distance.
3758
+ */
3759
+ placeMesh(target, stamp, options) {
3760
+ const t = this.#id(target);
3761
+ const s = this.#id(stamp);
3762
+ const n = normalizePlaceMeshArgs(options);
3763
+ const normals = n.normals ?? this.#hasNormals(s.index, s.generation);
3764
+ const raw = call(() => this.#scene().place_mesh(t.index, t.generation, s.index, s.generation, n.hitPoint, n.hitNormal, n.upAxis, n.twistAngleRad, n.uniformScale, n.embedDepth, n.mode, n.conformToSurface, n.booleanMethod, normals, n.stampAnchor));
3765
+ return decodePlaceMeshReport(raw, (i, g) => this.#meshHandle(i, g));
3766
+ }
3767
+ };
3768
+ // src/height-map-wasm.ts
3769
+ /**
3770
+ * Generates the relief of a grid of heights: a closed, welded, outward-wound
3771
+ * solid from a flat base up to the heights, with a vertex per sample at
3772
+ * exactly its height. `x` runs along the rows, `y` against them (the first
3773
+ * row is at the top, as in an image) and `z` is the height; it is centred on
3774
+ * the origin in `x` and `y`, height 0 is `z = 0` and the base is `z = -base`.
3775
+ * Each cell is split along its flatter diagonal.
3776
+ *
3777
+ * `scene.addHeightfield` adds the same relief to a scene without its buffers
3778
+ * leaving the engine, and on a `WorkerScene`, `scene.generateHeightfield(field)`
3779
+ * runs this generator in its Worker, so the main thread needs no wasm.
3780
+ *
3781
+ * @example
3782
+ * ```ts
3783
+ * const { positions, indices } = generateHeightfield({ heights, width: 256, height: 256, pixelSize: 0.1, base: 2 });
3784
+ * ```
3785
+ * @throws `INVALID_ARGUMENT` for fewer than 2 samples on a side, a wrong
3786
+ * number of heights, or a height that is infinite or not above `-base`;
3787
+ * `OUT_OF_MEMORY` when the buffers cannot be allocated.
3788
+ */
3789
+ function generateHeightfield(field) {
3790
+ ensureInitialized("generateHeightfield()");
3791
+ return generateCheckedHeightfield(checkHeightfield(field));
3792
+ }
3793
+ /** Internal (the Worker engine): {@link generateHeightfield} of a checked grid. */
3794
+ function generateCheckedHeightfield(f) {
3795
+ const options = encodeHeightfield(f);
3796
+ return decodePrimitiveMesh(call(() => activeWasmScene().generateHeightfield(f.heights, f.width, f.height, options)));
3797
+ }
3798
+ // src/primitives-wasm.ts
3799
+ /**
3800
+ * Generates a primitive shape: a box, cylinder, cone, UV sphere,
3801
+ * icosphere, torus, arrow, n-gon prism or plane, centred on the origin,
3802
+ * welded, closed (except the plane) and wound outward; see
3803
+ * {@link PrimitiveShape} for each shape's options and defaults.
3804
+ *
3805
+ * Add it to a scene with `scene.addMesh(mesh.positions, mesh.indices)`
3806
+ * (translate the positions or set a placement to move it), or upload it as
3807
+ * a vertex and index buffer. On a `WorkerScene`, `scene.generatePrimitive(shape)`
3808
+ * runs the same generator in its Worker, so the main thread needs no wasm.
3809
+ *
3810
+ * @example
3811
+ * ```ts
3812
+ * const { positions, indices } = generatePrimitive({ kind: "cylinder", radius: 2, height: 5, segments: 64 });
3813
+ * ```
3814
+ * @throws `INVALID_ARGUMENT` for an unknown kind or a parameter out of
3815
+ * range; `OUT_OF_MEMORY` when the buffers cannot be allocated.
3816
+ */
3817
+ function generatePrimitive(shape) {
3818
+ ensureInitialized("generatePrimitive()");
3819
+ return generateEncodedPrimitive(encodePrimitive(shape));
3820
+ }
3821
+ /** Internal (the Worker engine): {@link generatePrimitive} of an encoded shape. */
3822
+ function generateEncodedPrimitive(shape) {
3823
+ if (!Array.isArray(shape?.params)) throw new FastMeshError("INVALID_ARGUMENT", "an encoded primitive needs a kind and parameters");
3824
+ const params = Float64Array.from(shape.params);
3825
+ return decodePrimitiveMesh(call(() => activeWasmScene().generatePrimitive(shape.kind, params)));
3826
+ }
3827
+ export { Scene as a, meshAdds as c, generateHeightfield as i, useWasmScene as l, generatePrimitive as n, fieldSteps as o, generateCheckedHeightfield as r, geodesicSteps as s, generateEncodedPrimitive as t };