fast-mesh-wasm 0.7.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 (49) hide show
  1. package/README.md +43 -3
  2. package/dist/client-CJWOKQMM.d.ts +664 -0
  3. package/dist/{client-DFgvktkT.js → client-DQADH6KL.js} +1753 -123
  4. package/dist/{engine-BL5_sWAf.js → engine-D2124Vml.js} +983 -51
  5. package/dist/io.d.ts +7 -2
  6. package/dist/io.js +6 -6
  7. package/dist/{mesh-DIWD2F5-.js → mesh-BtWBMRMO.js} +2 -1
  8. package/dist/{mesh-BHTFxsXc.d.ts → mesh-DTm2Fnqa.d.ts} +3 -2
  9. package/dist/node.d.ts +4 -2
  10. package/dist/node.js +4 -4
  11. package/dist/primitives-6T0eQiSm.d.ts +157 -0
  12. package/dist/{scene-DUsj6uJD.js → primitives-wasm-C30Bk4ut.js} +1359 -64
  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-DFR0JDAS.d.ts → protocol-Da0kmXuF.d.ts} +417 -3
  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-BAzHRRkt.js → store-BxzcXy9y.js} +415 -65
  23. package/dist/{store-8HWG90Jg.d.ts → store-LM3iU8E4.d.ts} +98 -10
  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 +541 -8
  30. package/dist/wasm/fast_mesh_wasm.js +2083 -93
  31. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +94 -0
  33. package/dist/wasm-threads/fast_mesh_wasm.d.ts +541 -8
  34. package/dist/wasm-threads/fast_mesh_wasm.js +2084 -94
  35. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +94 -0
  37. package/dist/wave6-wasm-Bt4vTlKz.js +146 -0
  38. package/dist/web.d.ts +4 -2
  39. package/dist/web.js +4 -4
  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-nvmbhtn-.d.ts +0 -398
  48. package/dist/scene-like-CR_Dpohm.d.ts +0 -2511
  49. package/dist/views-BSy-Qeg8.js +0 -584
@@ -1,5 +1,5 @@
1
- import { _ as createBooleanDomain, a as encodeRule, c as SectionHandle, d as checkRegisterOptions, f as createSculptDomain, g as createDeformDomain, h as createInspectDomain, i as copyRule, l as rotationMatrix, m as createRemeshDomain, n as meshViews, o as FieldHandle, p as createRepairDomain, r as checkInteractionPoints, s as MeshHandle, t as ViewGuard, u as targetsOf, v as createAlignDomain } from "./views-BSy-Qeg8.js";
2
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
3
  import { WasmScene } from "./wasm/fast_mesh_wasm.js";
4
4
  // src/changes.ts
5
5
  const ADDED = 1;
@@ -12,6 +12,7 @@ const COLORS_ALL = 64;
12
12
  const INDICES_ALL = 128;
13
13
  const UVS = 256;
14
14
  const UVS_ALL = 512;
15
+ const RESTORABLE = 1024;
15
16
  /** Decodes `[record_count, record...]`. */
16
17
  function decodeChanges(msg) {
17
18
  let at = 0;
@@ -45,6 +46,7 @@ function decodeChanges(msg) {
45
46
  generation,
46
47
  added: (flags & ADDED) !== 0,
47
48
  removed: (flags & REMOVED) !== 0,
49
+ restorable: (flags & RESTORABLE) !== 0,
48
50
  placementChanged: (flags & PLACEMENT) !== 0,
49
51
  capacityChanged: (flags & CAPACITY) !== 0,
50
52
  positions: ranges((flags & POSITIONS_ALL) !== 0),
@@ -130,15 +132,30 @@ function buildTopology(indices, slots) {
130
132
  liveTriangles: Uint32Array.from(live)
131
133
  };
132
134
  }
133
- /** Every used vertex within `radius` of `center` (squared distances). */
134
- function brushPick(positions, used, center, radius) {
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) {
135
141
  const out = [];
136
142
  const r2 = radius * radius;
143
+ const m = stretch;
137
144
  for (let v = 0; v < used.length; v++) {
138
145
  if (used[v] === 0) continue;
139
- const dx = positions[v * 3] - center[0];
140
- const dy = positions[v * 3 + 1] - center[1];
141
- const dz = positions[v * 3 + 2] - center[2];
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
+ }
142
159
  if (dx * dx + dy * dy + dz * dz <= r2) out.push(v);
143
160
  }
144
161
  return out;
@@ -312,6 +329,10 @@ let RawScene = WasmScene;
312
329
  function useWasmScene(ctor) {
313
330
  RawScene = ctor;
314
331
  }
332
+ /** Internal: the `WasmScene` class new scenes wrap ({@link useWasmScene}), for its statics. */
333
+ function activeWasmScene() {
334
+ return RawScene;
335
+ }
315
336
  const meshIds = /* @__PURE__ */ new WeakMap();
316
337
  const rawIds = /* @__PURE__ */ new WeakMap();
317
338
  /** The repair list's prefix code for a {@link VertexProtection}. */
@@ -359,9 +380,9 @@ function invalid(message) {
359
380
  return new FastMeshError("INVALID_ARGUMENT", message);
360
381
  }
361
382
  /**
362
- * The mean stretch of a column-major 4x4's linear part: the cube root of
363
- * its determinant. World-space brush radii divide by it, exact for rigid
364
- * placements and a documented approximation under non-uniform scale.
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.
365
386
  */
366
387
  function meanStretch(m) {
367
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]);
@@ -477,7 +498,7 @@ const REPAIR_CODES = {
477
498
  relax: 10,
478
499
  offset: 11,
479
500
  shell: 12,
480
- simplify: 13,
501
+ simplify: 28,
481
502
  subdivide: 14,
482
503
  splitStretched: 16,
483
504
  captureRestSizes: 17,
@@ -488,7 +509,8 @@ const REPAIR_CODES = {
488
509
  twist: 22,
489
510
  makeManifold: 23,
490
511
  resolveSelfIntersections: 24,
491
- cleanupSlivers: 25
512
+ cleanupSlivers: 25,
513
+ remeshSurface: 27
492
514
  };
493
515
  /** The op code of a legacy {@link AutoRepairRequest}; see `crate::edit` in the Rust crate. */
494
516
  const AUTO_REPAIR_CODE = 15;
@@ -561,6 +583,10 @@ const OFFSET_ALGORITHM_CODES = {
561
583
  bvhSdf: 2
562
584
  };
563
585
  const SUBDIVIDE_METHOD_CODES = { loop: 0 };
586
+ const SURFACE_REMESH_MODE_CODES = {
587
+ isotropic: 0,
588
+ adaptive: 1
589
+ };
564
590
  /** An optional number for the binding: NaN when unset; an explicit NaN is rejected. */
565
591
  /** The `status` codes of `WasmScene.register`, in order. */
566
592
  const REGISTER_STATUSES = [
@@ -694,7 +720,7 @@ function encodeRepair(ops) {
694
720
  values.push(optional(o.areaEpsilon, "areaEpsilon"), flagOf(o.removeUnusedVertices, true));
695
721
  break;
696
722
  case "removeSmallComponents":
697
- values.push(optional(o.minTriangles, "minTriangles"), optional(o.minArea, "minArea"), flagOf(o.keepLargest, true));
723
+ values.push(optional(o.minTriangles, "minTriangles"), optional(o.minArea, "minArea"), flagOf(o.keepLargest, true), flagOf(o.keepCavities, true));
698
724
  break;
699
725
  case "orient": break;
700
726
  case "fillHoles": {
@@ -770,7 +796,12 @@ function encodeRepair(ops) {
770
796
  values.push(optional(o.thickness, "thickness"));
771
797
  break;
772
798
  case "simplify":
773
- values.push(optional(o.targetTriangles, "targetTriangles"), flagOf(o.preserveBoundary, true));
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"));
774
805
  break;
775
806
  case "subdivide":
776
807
  values.push(o.method === void 0 ? NaN : codeIn(SUBDIVIDE_METHOD_CODES, o.method, "method"), optional(o.levels, "levels"));
@@ -929,7 +960,17 @@ function decodeReport(op, r) {
929
960
  case "simplify": return {
930
961
  collapsed: r.next(),
931
962
  trianglesRemoved: r.next(),
932
- verticesRemoved: 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()
933
974
  };
934
975
  case "subdivide": return {
935
976
  verticesAdded: r.next(),
@@ -1006,7 +1047,8 @@ function decodeAnalysis(r) {
1006
1047
  const components = r.many(() => ({
1007
1048
  triangles: r.list(),
1008
1049
  area: r.next(),
1009
- closed: r.flag()
1050
+ closed: r.flag(),
1051
+ cavity: r.flag()
1010
1052
  }));
1011
1053
  const orientationConflicts = r.next();
1012
1054
  const si = r.next();
@@ -1041,10 +1083,41 @@ function fieldSteps(scene) {
1041
1083
  }
1042
1084
  /** Set by `Scene`'s static block. */
1043
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
+ }
1044
1111
  /** @internal The stepped mesh adds of `scene` (see {@link MeshAdds}); for the Worker engine. */
1045
1112
  function meshAdds(scene) {
1046
1113
  return meshAddsOf(scene);
1047
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
+ }
1048
1121
  /**
1049
1122
  * A scene of editable meshes. Create it after `await init()`; release it with
1050
1123
  * {@link Scene.free} or a `using` declaration (otherwise it is freed when
@@ -1058,8 +1131,10 @@ function meshAdds(scene) {
1058
1131
  var Scene = class {
1059
1132
  #raw;
1060
1133
  #guard;
1061
- /** Live meshes' handles by `"index:generation"`. */
1134
+ /** Handles by `"index:generation"`, of live meshes and of those undo or redo can bring back. */
1062
1135
  #meshes = /* @__PURE__ */ new Map();
1136
+ /** A handle in `#meshes` may be of a mesh the history has dropped since. */
1137
+ #prune = false;
1063
1138
  /** Handles of meshes removed since the last `takeChanges`, for their removal records. */
1064
1139
  #removed = /* @__PURE__ */ new Map();
1065
1140
  /** The rule each coloured mesh was last given by `setColoring`. */
@@ -1072,6 +1147,16 @@ var Scene = class {
1072
1147
  #fields = /* @__PURE__ */ new Map();
1073
1148
  #sections = /* @__PURE__ */ new Map();
1074
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;
1075
1160
  /** History step nesting depth, mirrored from the calls made through this class. */
1076
1161
  #stepDepth = 0;
1077
1162
  #drag;
@@ -1081,7 +1166,24 @@ var Scene = class {
1081
1166
  repair = createRepairDomain({
1082
1167
  repair: ((mesh, op) => this.#runRepair(mesh, op)),
1083
1168
  analyze: (mesh, options) => this.analyze(mesh, options),
1084
- join: (target, source, options) => this.join(target, source, 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)
1085
1187
  });
1086
1188
  /**
1087
1189
  * Callable sculpt domain (`scene.sculpt(mesh, op)` and `scene.sculpt.<method>(...)`).
@@ -1091,20 +1193,34 @@ var Scene = class {
1091
1193
  verticesInSphere: (mesh, center, radius) => this.verticesInSphere(mesh, center, radius),
1092
1194
  beginStep: () => this.beginStep(),
1093
1195
  endStep: () => this.endStep(),
1094
- cancelStep: () => this.cancelStep()
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)
1095
1199
  });
1096
1200
  /** Remesh, simplification, subdivision, and volumetric reconstruction domain. */
1097
1201
  remesh = createRemeshDomain({ repair: ((mesh, op) => this.#runRepair(mesh, op)) });
1098
- /** Callable boolean, cutting, offsetting, and shell domain. */
1202
+ /** Callable boolean, cutting, trimming, offsetting, and shell domain. */
1099
1203
  boolean = createBooleanDomain({
1100
1204
  isAsync: false,
1101
1205
  repair: ((mesh, op) => this.#runRepair(mesh, op)),
1102
- boolean: (target, source, op) => this.#runBoolean(target, source, op),
1103
- cutByPlane: (mesh, plane, options) => this.cutByPlane(mesh, plane, options)
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)
1104
1213
  });
1105
1214
  /** Surface deformation and vertex-protection domain. */
1106
- deform = createDeformDomain({ sculpt: ((mesh, op) => this.#runRepair(mesh, op)) });
1107
- /** Defect analysis, metrology, queries, fields, and section inspection 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. */
1108
1224
  inspect = createInspectDomain({
1109
1225
  analyze: (mesh, options) => this.analyze(mesh, options),
1110
1226
  measure: (mesh) => this.measure(mesh),
@@ -1113,7 +1229,14 @@ var Scene = class {
1113
1229
  closestPoint: (point, options) => this.closestPoint(point, options),
1114
1230
  meshDistance: (a, b, options) => this.meshDistance(a, b, options),
1115
1231
  intersects: (a, b) => this.intersects(a, b),
1232
+ selfIntersectingTriangles: (mesh) => this.selfIntersectingTriangles(mesh),
1116
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),
1117
1240
  addDistanceField: (desc) => this.addDistanceField(desc),
1118
1241
  addThicknessField: (desc) => this.addThicknessField(desc),
1119
1242
  addCurvatureField: (desc) => this.addCurvatureField(desc),
@@ -1132,13 +1255,26 @@ var Scene = class {
1132
1255
  removeSection: (section) => this.removeSection(section),
1133
1256
  section: (section, mesh) => this.section(section, mesh),
1134
1257
  sectionGap: (section, a, b) => this.sectionGap(section, a, b),
1135
- updateSections: () => this.updateSections()
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)
1136
1271
  });
1137
- /** Rigid registration and alignment domain. */
1138
- align = createAlignDomain({ register: (moving, fixed, options) => this.register(moving, fixed, options) });
1139
1272
  constructor(options = {}) {
1140
1273
  ensureInitialized("new Scene()");
1141
- this.#raw = call(() => new RawScene());
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));
1142
1278
  this.#guard = options.debug ? new ViewGuard() : void 0;
1143
1279
  finalizer.register(this, this.#raw, this);
1144
1280
  }
@@ -1149,6 +1285,7 @@ var Scene = class {
1149
1285
  this.#raw = void 0;
1150
1286
  this.#guard?.bump();
1151
1287
  this.#drag = void 0;
1288
+ this.#entries.dropAll();
1152
1289
  finalizer.unregister(this);
1153
1290
  release(raw);
1154
1291
  }
@@ -1160,8 +1297,37 @@ var Scene = class {
1160
1297
  #scene() {
1161
1298
  const s = this.#peek();
1162
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
+ }
1163
1309
  return s;
1164
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
+ }
1165
1331
  /** The live raw scene, for a read-only call that leaves every view valid. */
1166
1332
  #peek() {
1167
1333
  if (this.#raw === void 0) throw invalid("scene is freed");
@@ -1249,33 +1415,84 @@ var Scene = class {
1249
1415
  const p = toFloat64(positions);
1250
1416
  const i = toUint32(indices);
1251
1417
  const normals = options.normals ?? true;
1252
- if (options.uvs === void 0) {
1253
- const id = call(() => s.add_mesh(p, i, origin, mode, normals));
1254
- return this.#meshHandle(id[0], id[1]);
1255
- }
1256
- const uvs = options.uvs instanceof Float32Array ? options.uvs : Float32Array.from(options.uvs);
1257
- const id = call(() => s.add_mesh_with_uvs(p, i, uvs, origin, mode, normals));
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
+ });
1258
1423
  return this.#meshHandle(id[0], id[1]);
1259
1424
  }
1260
1425
  /**
1261
1426
  * Removes a mesh. Its handle then gives `UNKNOWN_MESH`. An active drag of
1262
1427
  * the mesh is ended first, closing its step; the mesh's history entries
1263
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.
1264
1441
  */
1265
- removeMesh(mesh) {
1442
+ removeMesh(mesh, options = {}) {
1266
1443
  const { index, generation } = this.#id(mesh);
1267
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
+ }
1268
1451
  call(() => this.#scene().remove_mesh(index, generation));
1269
1452
  const key = `${index}:${generation}`;
1270
1453
  this.#meshes.delete(key);
1271
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));
1272
1486
  }
1273
1487
  /**
1274
1488
  * Joins `source` into `target`: copies the source's geometry into the
1275
1489
  * target (keeping its world shape), bridges `options.loopA` to the copied
1276
- * `options.loopB`, and removes the source. The copy and the bridge undo as
1277
- * one step; the removal is permanent. A drag of the source ends first,
1278
- * recording its moves as one step, so they survive a failed join.
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.
1279
1496
  *
1280
1497
  * @deprecated Use `scene.repair.join()` instead.
1281
1498
  * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for one
@@ -1291,9 +1508,8 @@ var Scene = class {
1291
1508
  const maxEdges = optional(options.maxEdges, "maxEdges");
1292
1509
  if (this.#drag?.mesh === source) this.#drag.end();
1293
1510
  const r = call(() => this.#scene().join(ta.index, ta.generation, sb.index, sb.generation, Uint32Array.from(loops), maxEdges));
1294
- const key = `${sb.index}:${sb.generation}`;
1295
- this.#meshes.delete(key);
1296
- this.#removed.set(key, source);
1511
+ this.#settleHistory();
1512
+ this.#prune = true;
1297
1513
  return {
1298
1514
  verticesAdded: r[0],
1299
1515
  trianglesAdded: r[1],
@@ -1311,8 +1527,8 @@ var Scene = class {
1311
1527
  * boundary of an open mesh stays open. A mesh without UVs is read by vertex
1312
1528
  * index, so its split vertices are such a boundary: weld it first.
1313
1529
  *
1314
- * The cut undoes in one step; the added mesh stays, like the removed
1315
- * source of {@link Scene.join}.
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.
1316
1532
  *
1317
1533
  * @deprecated Use `scene.boolean.cut()` instead.
1318
1534
  * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` when
@@ -1345,18 +1561,337 @@ var Scene = class {
1345
1561
  * input that is not closed, manifold and consistently wound. A failed
1346
1562
  * boolean changes nothing.
1347
1563
  */
1348
- #runBoolean(target, source, op) {
1564
+ #runBoolean(target, source, op, options) {
1349
1565
  const ta = this.#id(target);
1350
1566
  const sb = this.#id(source);
1351
- const code = codeIn({
1352
- union: 0,
1353
- subtract: 1,
1354
- intersect: 2
1355
- }, op, "op");
1356
- const r = call(() => this.#scene().boolean(ta.index, ta.generation, sb.index, sb.generation, code));
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")));
1357
1576
  return this.#meshHandle(r[0], r[1]);
1358
1577
  }
1359
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
+ /**
1360
1895
  * Rigidly aligns the mesh `moving` to the mesh `fixed` by point-to-plane ICP,
1361
1896
  * with the closest points found through `fixed`'s BVH and trimmed by
1362
1897
  * `options.overlap`. A drag of either mesh ends first, recording its moves
@@ -1440,6 +1975,61 @@ var Scene = class {
1440
1975
  };
1441
1976
  }
1442
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
+ /**
1443
2033
  * Sets a mesh's placement: world = rotation · (scale · local) + translation,
1444
2034
  * where local is relative to the mesh origin. A quaternion is normalised
1445
2035
  * and converted in double precision. The scale defaults to `[1, 1, 1]`
@@ -1614,11 +2204,13 @@ var Scene = class {
1614
2204
  takeChanges() {
1615
2205
  this.#drag?.applyPending();
1616
2206
  const s = this.#scene();
2207
+ this.#settleHistory();
1617
2208
  const raw = decodeChanges(call(() => s.take_changes()));
1618
2209
  const out = raw.map((c) => ({
1619
2210
  mesh: this.#meshHandle(c.index, c.generation),
1620
2211
  added: c.added,
1621
2212
  removed: c.removed,
2213
+ ...c.restorable ? { restorable: true } : {},
1622
2214
  placementChanged: c.placementChanged,
1623
2215
  capacityChanged: c.capacityChanged,
1624
2216
  positions: c.positions,
@@ -1629,8 +2221,15 @@ var Scene = class {
1629
2221
  fieldsChanged: c.fields.map((f) => this.#rawHandle(this.#fields, () => new FieldHandle(), f)),
1630
2222
  sectionsChanged: c.sections.map((x) => this.#rawHandle(this.#sections, () => new SectionHandle(), x))
1631
2223
  }));
1632
- for (const c of raw) if (c.removed) this.#meshes.delete(`${c.index}:${c.generation}`);
2224
+ for (const c of raw) if (c.removed && !c.restorable) this.#meshes.delete(`${c.index}:${c.generation}`);
1633
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
+ }
1634
2233
  return out;
1635
2234
  }
1636
2235
  /**
@@ -1663,22 +2262,28 @@ var Scene = class {
1663
2262
  /**
1664
2263
  * Undoes the latest step; an active drag is ended first. Without an open
1665
2264
  * step around the drag, the drag is what gets undone; inside a caller's
1666
- * open step, that whole step (drag included) is closed and undone. Returns
1667
- * `false` when there is nothing to undo.
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.
1668
2269
  */
1669
2270
  undo() {
1670
2271
  const s = this.#scene();
1671
2272
  this.#drag?.end();
2273
+ this.#prune = true;
1672
2274
  const done = call(() => s.undo());
1673
2275
  this.#stepDepth = 0;
2276
+ this.#settleHistory();
1674
2277
  return done;
1675
2278
  }
1676
2279
  /** Redoes the latest undone step. Returns `false` when there is nothing to redo. */
1677
2280
  redo() {
1678
2281
  const s = this.#scene();
1679
2282
  this.#drag?.end();
2283
+ this.#prune = true;
1680
2284
  const done = call(() => s.redo());
1681
2285
  this.#stepDepth = 0;
2286
+ this.#settleHistory();
1682
2287
  return done;
1683
2288
  }
1684
2289
  /** True if {@link Scene.undo} would undo something. */
@@ -1695,13 +2300,110 @@ var Scene = class {
1695
2300
  clearHistory() {
1696
2301
  const s = this.#scene();
1697
2302
  this.#drag?.end();
2303
+ this.#prune = true;
1698
2304
  call(() => s.clear_history());
1699
2305
  this.#stepDepth = 0;
2306
+ this.#settleHistory();
1700
2307
  }
1701
2308
  /**
1702
- * Opens a history step, or one more nesting level of the open one. Edits
1703
- * and placement changes until the matching {@link Scene.endStep} are
1704
- * undone together.
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.
1705
2407
  */
1706
2408
  beginStep() {
1707
2409
  const s = this.#scene();
@@ -1716,13 +2418,20 @@ var Scene = class {
1716
2418
  call(() => s.end_step());
1717
2419
  this.#stepDepth--;
1718
2420
  if (this.#drag !== void 0 && this.#stepDepth < this.#drag.depth) this.#drag.abandon();
2421
+ this.#settleHistory();
1719
2422
  }
1720
- /** Reverts and discards the open step, however deeply nested. Throws `STEP_NOT_OPEN` when none is open. */
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
+ */
1721
2428
  cancelStep() {
1722
2429
  const s = this.#scene();
2430
+ this.#prune = true;
1723
2431
  call(() => s.cancel_step());
1724
2432
  this.#stepDepth = 0;
1725
2433
  this.#drag?.abandon();
2434
+ this.#settleHistory();
1726
2435
  }
1727
2436
  /**
1728
2437
  * Starts dragging a mesh: the moves until {@link DragSession.end} form one
@@ -1736,10 +2445,12 @@ var Scene = class {
1736
2445
  if (this.#drag !== void 0) throw invalid("a drag is already active; end or cancel it first");
1737
2446
  const coalesce = options.coalesce ?? false;
1738
2447
  const start = this.placement(mesh);
2448
+ const collisionActive = this.hasActiveCollisionResponse(mesh);
1739
2449
  const outermost = this.#stepDepth === 0;
1740
2450
  this.beginStep();
1741
2451
  const depth = this.#stepDepth;
1742
2452
  let active = true;
2453
+ let moved = false;
1743
2454
  /** The latest coalesced pose, not yet applied. */
1744
2455
  let pending;
1745
2456
  const finish = () => {
@@ -1751,11 +2462,19 @@ var Scene = class {
1751
2462
  const close = () => {
1752
2463
  while (this.#stepDepth >= depth) this.endStep();
1753
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
+ };
1754
2473
  const applyPending = () => {
1755
2474
  if (pending !== void 0) {
1756
2475
  const pose = pending;
1757
2476
  pending = void 0;
1758
- this.setPlacement(mesh, pose);
2477
+ applyPose(pose);
1759
2478
  }
1760
2479
  };
1761
2480
  const session = {
@@ -1767,7 +2486,7 @@ var Scene = class {
1767
2486
  move: (placement) => {
1768
2487
  if (!active) throw invalid("the drag is over");
1769
2488
  if (!coalesce) {
1770
- this.setPlacement(mesh, placement);
2489
+ applyPose(placement);
1771
2490
  return;
1772
2491
  }
1773
2492
  const rotation = rotationMatrix(placement.rotation);
@@ -1801,6 +2520,7 @@ var Scene = class {
1801
2520
  end: () => {
1802
2521
  if (finish()) try {
1803
2522
  applyPending();
2523
+ if (collisionActive && moved) this.commitCollisionInteraction(mesh);
1804
2524
  } finally {
1805
2525
  close();
1806
2526
  }
@@ -2030,6 +2750,20 @@ var Scene = class {
2030
2750
  return call(() => this.#scene().intersects(ia.index, ia.generation, ib.index, ib.generation));
2031
2751
  }
2032
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
+ /**
2033
2767
  * Every mesh pair (or every pair of `pairs`) within `margin`, sorted by mesh id.
2034
2768
  *
2035
2769
  * @deprecated Use `scene.inspect.findContacts()` instead.
@@ -2056,6 +2790,80 @@ var Scene = class {
2056
2790
  }
2057
2791
  return out;
2058
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
+ }
2059
2867
  /**
2060
2868
  * Selects vertices of a mesh: a sphere brush, a lasso polygon, or the
2061
2869
  * connected component holding a seed vertex. The result is a snapshot
@@ -2080,11 +2888,15 @@ var Scene = class {
2080
2888
  case "brush": {
2081
2889
  let center = spec.center;
2082
2890
  let radius = spec.radius;
2891
+ let stretch;
2083
2892
  if (spec.space === "world") {
2084
- center = transformPoint(invertMatrix4(this.matrix4(mesh)), spec.center);
2085
- radius = spec.radius / meanStretch(this.matrix4(mesh));
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;
2086
2898
  }
2087
- ids = brushPick(positions, topology.used, center, radius);
2899
+ ids = brushPick(positions, topology.used, center, radius, stretch);
2088
2900
  break;
2089
2901
  }
2090
2902
  case "lasso":
@@ -2394,6 +3206,19 @@ var Scene = class {
2394
3206
  drop: (token) => call(() => scene.#peek().drop_add_mesh(token))
2395
3207
  });
2396
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
+ }
2397
3222
  static {
2398
3223
  fieldStepsOf = (scene) => ({
2399
3224
  setDefer: (on) => call(() => scene.#peek().set_defer_fields(on)),
@@ -2489,9 +3314,11 @@ var Scene = class {
2489
3314
  let at = 4;
2490
3315
  for (let k = 0; k < r[3]; k++) {
2491
3316
  const n = 3 * r[at + 1];
3317
+ const points64 = r.slice(at + 2, at + 2 + n);
2492
3318
  contours.push({
2493
3319
  closed: r[at] === 1,
2494
- points: Float32Array.from(r.subarray(at + 2, at + 2 + n))
3320
+ points: Float32Array.from(points64),
3321
+ points64
2495
3322
  });
2496
3323
  at += 2 + n;
2497
3324
  }
@@ -2503,10 +3330,12 @@ var Scene = class {
2503
3330
  };
2504
3331
  if (r[at] === 1) {
2505
3332
  const np = 3 * r[at + 1];
2506
- const positions = Float32Array.from(r.subarray(at + 2, at + 2 + np));
3333
+ const positions64 = r.slice(at + 2, at + 2 + np);
3334
+ const positions = Float32Array.from(positions64);
2507
3335
  at += 2 + np;
2508
3336
  result.fill = {
2509
3337
  positions,
3338
+ positions64,
2510
3339
  indices: Uint32Array.from(r.subarray(at + 1, at + 1 + 3 * r[at]))
2511
3340
  };
2512
3341
  }
@@ -2528,5 +3357,471 @@ var Scene = class {
2528
3357
  b: vec3At(g, 4)
2529
3358
  };
2530
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
+ }
2531
3767
  };
2532
- export { useWasmScene as i, fieldSteps as n, meshAdds as r, Scene as t };
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 };