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,6 +1,6 @@
1
- import { _ as createBooleanDomain, c as SectionHandle, d as checkRegisterOptions, f as createSculptDomain, g as createDeformDomain, h as createInspectDomain, i as copyRule, l as rotationMatrix, m as createRemeshDomain, 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";
1
+ import { $ as checkU32Arg, $t as normalizeBooleanArgs, A as checkLatticeOptions, At as normalizeSelectSmallIslandsArgs, Cn as checkHeightfieldPlacement, Ct as normalizeHollowArgs, D as checkRegisterOptions, Dn as encodeHeightMapOptions, Dt as normalizeReconstructArgs, E as wrapMeshList, En as encodeHeightMapFrame, Et as normalizePlacementInputArgs, Fn as rotationMatrix, Ft as normalizeXpbdArgs, H as extrudeFacesArgs, I as hullMeshList, In as targetsOf, J as DEFAULT_COLLISION_RULE, Jt as checkSurfacePathOptions, L as hullNormals, Mn as FieldHandle, Mt as normalizeSliceContoursArgs, Nn as MeshHandle, Nt as normalizeU32Selection, O as DEFAULT_LATTICE_MAX_VOXELS, Ot as normalizeScreenSelectArgs, Pn as SectionHandle, Pt as normalizeVertexMaskSelectArgs, Qt as isBrushSculptOp, R as hullPointsBuffer, S as checkWrapOptions, Sn as checkHeightfield, St as normalizeGrowShrinkArgs, Tt as normalizePlaceMeshArgs, U as checkDelaunayFlipOptions, V as extrudeBaseArgs, W as checkDenoiseOptions, X as checkBooleanArg, Yt as checkU32Int, _ as createDeformDomain, _t as normalizeBuildFfdLatticeArgs, an as normalizeGeodesicOptions, bt as normalizeFfdArgs, c as EntryBook, cn as normalizePartialBridgeOptions, dn as normalizeSourceVertices, en as normalizeCsgBatchArgs, et as cloudBuffer, f as tellPermanent, fn as normalizeSurfacePathTarget, g as createInspectDomain, gn as throwIfAborted, gt as normalizeArapArgs, h as createRemeshDomain, hn as normalizeVec3, ht as normalizeAlignToPrimitiveArgs, i as copyRule, in as normalizeFillHolesContinuityOptions, jn as isHeightMapFrame, jt as normalizeSliceContourStackArgs, k as DEFAULT_LATTICE_PREVIEW_VOXELS, kn as heightMapMeshList, kt as normalizeSelectInSphereArgs, l as checkHistoryBudget, ln as normalizeQualityArgs, m as createRepairDomain, mn as normalizeU32List, nn as normalizeDyntopoCenterRadius, on as normalizeLandmarkPairs, p as createSculptDomain, pn as normalizeTrimCurveArgs, r as checkInteractionPoints, rn as normalizeDyntopoOptions, sn as normalizeOverhangOptions, t as ViewGuard, tn as normalizeDeviationOptions, tt as cloudOrigin, u as checkHistoryEntry, un as normalizeRegistrationOptions, v as createBooleanDomain, vt as normalizeCollisionRule, wt as normalizeKelvinletArgs, xt as normalizeFitPrimitiveArgs, y as createAlignDomain, yn as encodePrimitive, yt as normalizeDrainHoleArgs } from "./views-DPMbo0Sl.js";
2
2
  import { o as reportListenerError, t as FastMeshError } from "./core-4OcWKu3r.js";
3
- import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-Ci9LLiwO.js";
3
+ import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-Bvjmvlb3.js";
4
4
  // src/worker/client.ts
5
5
  /**
6
6
  * Starts a Worker running the scene engine and resolves once it is ready.
@@ -11,6 +11,7 @@ async function createWorkerScene(options = {}) {
11
11
  const threads = options.threads === void 0 ? void 0 : Math.min(Math.max(options.threads, 1), 64);
12
12
  const background = options.backgroundAddTriangles;
13
13
  if (background !== void 0 && (typeof background !== "number" || Number.isNaN(background) || background < 0)) throw invalid(`backgroundAddTriangles must be a number, 0 or more (got ${String(background)})`);
14
+ const budget = options.historyBudget === void 0 ? void 0 : checkHistoryBudget(options.historyBudget);
14
15
  const make = () => options.createWorker?.() ?? (options.workerUrl === void 0 ? new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" }) : new Worker(options.workerUrl, { type: "module" }));
15
16
  const dev = import.meta.env?.DEV === true;
16
17
  const debug = (options.debug ?? false) || dev;
@@ -21,7 +22,8 @@ async function createWorkerScene(options = {}) {
21
22
  kind: "init",
22
23
  threads: skipped ? 1 : threads,
23
24
  debug,
24
- ...background === void 0 ? {} : { backgroundAddTriangles: background }
25
+ ...background === void 0 ? {} : { backgroundAddTriangles: background },
26
+ ...budget === void 0 ? {} : { historyBudget: budget }
25
27
  }
26
28
  });
27
29
  try {
@@ -75,7 +77,7 @@ function transferOf(batch) {
75
77
  for (const req of batch) if (req.kind === "addMesh") {
76
78
  transfer.push(req.positions, req.indices);
77
79
  if (req.uvs !== void 0) transfer.push(req.uvs);
78
- }
80
+ } else if (req.kind === "addHeightfield") transfer.push(req.field.heights.buffer);
79
81
  return transfer;
80
82
  }
81
83
  /** The most failed requests kept for `restart()`. */
@@ -203,7 +205,7 @@ function sortOf(req) {
203
205
  ...base,
204
206
  kind: "removal"
205
207
  };
206
- if (req.kind === "setPlacement" || req.kind === "drag" || req.kind === "coloring" || req.kind === "field" || req.kind === "section") return {
208
+ if (req.kind === "setPlacement" || req.kind === "drag" || req.kind === "coloring" || req.kind === "field" || req.kind === "section" || req.kind === "historyBudget") return {
207
209
  ...base,
208
210
  kind: "declarative",
209
211
  covers: coversOf(req)
@@ -247,6 +249,12 @@ const THREADS_UNAVAILABLE = "fast-mesh-wasm: the multithreaded engine cannot run
247
249
  let addFieldKeyedOf;
248
250
  /** Set by `WorkerScene`'s static block: the internal {@link watchStatusKeys}. */
249
251
  let watchStatusKeysOf;
252
+ /** Set by `WorkerScene`'s static block: the internal {@link fieldTargets}. */
253
+ let fieldTargetsOf;
254
+ /** Set by `WorkerScene`'s static block: the internal {@link sectionMeshes}. */
255
+ let sectionMeshesOf;
256
+ /** Set by `WorkerScene`'s static block: the internal {@link presenceVersion}. */
257
+ let presenceVersionOf;
250
258
  /**
251
259
  * A scene whose engine runs in a Worker, from {@link createWorkerScene}. It
252
260
  * mirrors `Scene` (always `"eager"`) with these differences:
@@ -337,6 +345,7 @@ var WorkerScene = class WorkerScene {
337
345
  #optimistic = /* @__PURE__ */ new Set();
338
346
  #listeners = /* @__PURE__ */ new Set();
339
347
  #statusListeners = /* @__PURE__ */ new Set();
348
+ #permanentListeners = /* @__PURE__ */ new Set();
340
349
  #status = /* @__PURE__ */ new Map();
341
350
  /** Called with each key whose status is set or forgotten, at once (see {@link watchStatusKeys}). */
342
351
  #statusSinks = /* @__PURE__ */ new Set();
@@ -347,9 +356,15 @@ var WorkerScene = class WorkerScene {
347
356
  canUndo: false,
348
357
  canRedo: false
349
358
  };
359
+ #historyBytes = 0;
360
+ /** The application's entries in the history, or on their way to it. */
361
+ #entries = new EntryBook();
362
+ /** See {@link presenceVersion}. */
363
+ #presenceVersion = 0;
350
364
  /** The values mirror is on (a `values()` read asked for it). */
351
365
  #values = false;
352
366
  #drag;
367
+ #stepDepth = 0;
353
368
  #poison;
354
369
  #terminated = false;
355
370
  /** The current Worker's start. */
@@ -377,31 +392,74 @@ var WorkerScene = class WorkerScene {
377
392
  #warned = false;
378
393
  /** The current Worker's crash channel (see `#watch`), while it may run threaded. */
379
394
  #crashWatch;
395
+ /** Default collision response rule persisted across Worker restarts. */
396
+ #defaultCollisionRule = { ...DEFAULT_COLLISION_RULE };
397
+ /**
398
+ * Explicit per-pair collision rules keyed canonically by sorted ClientId
399
+ * pair; those of a parked mesh wait here for its way back.
400
+ */
401
+ #collisionRules = /* @__PURE__ */ new Map();
380
402
  /**
381
403
  * Callable async repair domain (`worker.repair(mesh, op)` and `worker.repair.<method>(...)`).
382
404
  */
383
405
  repair = createRepairDomain({
384
406
  repair: ((mesh, op) => this.#runRepair(mesh, op)),
385
407
  analyze: (mesh, options) => this.analyze(mesh, options),
386
- join: (target, source, options) => this.join(target, source, options)
408
+ join: (target, source, options) => this.join(target, source, options),
409
+ fillHoleContinuity: (mesh, loopIndex, options) => this.fillHoleContinuity(mesh, loopIndex, options),
410
+ fillAllHolesContinuity: (mesh, options) => this.fillAllHolesContinuity(mesh, options),
411
+ bridgePartialArcs: (mesh, loopA, loopB, options) => this.bridgePartialArcs(mesh, loopA, loopB, options),
412
+ selectFacesScreen: (mesh, shape, options) => this.selectFacesScreen(mesh, shape, options),
413
+ selectFacesInSphere: (mesh, center, radius, normalCone) => this.selectFacesInSphere(mesh, center, radius, normalCone),
414
+ selectByCreaseAngle: (mesh, seedTri, maxDihedralRad) => this.selectByCreaseAngle(mesh, seedTri, maxDihedralRad),
415
+ selectConnectedShell: (mesh, seedTri) => this.selectConnectedShell(mesh, seedTri),
416
+ selectSmallFaceIslands: (mesh, maxFaceCount, maxArea) => this.selectSmallFaceIslands(mesh, maxFaceCount, maxArea),
417
+ growFaceSelection: (mesh, selectedTris, rings, adjacency) => this.growFaceSelection(mesh, selectedTris, rings, adjacency),
418
+ shrinkFaceSelection: (mesh, selectedTris, rings, adjacency) => this.shrinkFaceSelection(mesh, selectedTris, rings, adjacency),
419
+ fillSelectionHoles: (mesh, selectedTris, maxHoleTris) => this.fillSelectionHoles(mesh, selectedTris, maxHoleTris),
420
+ smoothSelectionBoundary: (mesh, selectedTris, iterations) => this.smoothSelectionBoundary(mesh, selectedTris, iterations),
421
+ faceSelectionToVertexMask: (mesh, selectedTris) => this.faceSelectionToVertexMask(mesh, selectedTris),
422
+ vertexMaskToFaceSelection: (mesh, mask, threshold, requireAllVertices) => this.vertexMaskToFaceSelection(mesh, mask, threshold, requireAllVertices),
423
+ deleteSelectedFaces: (mesh, selectedTris) => this.deleteSelectedFaces(mesh, selectedTris),
424
+ extractSelectedFaces: (mesh, selectedTris, options) => this.extractSelectedFaces(mesh, selectedTris, options),
425
+ splitSelectedFaces: (mesh, selectedTris, options) => this.splitSelectedFaces(mesh, selectedTris, options)
387
426
  });
388
427
  /**
389
428
  * Callable async sculpt domain (`worker.sculpt(mesh, op)` and `worker.sculpt.<method>(...)`).
390
429
  */
391
430
  sculpt = createSculptDomain({
392
431
  sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
393
- verticesInSphere: (mesh, center, radius) => this.verticesInSphere(mesh, center, radius)
432
+ verticesInSphere: (mesh, center, radius) => this.verticesInSphere(mesh, center, radius),
433
+ beginStep: () => this.beginStep(),
434
+ endStep: () => this.endStep(),
435
+ cancelStep: () => this.cancelStep(),
436
+ applyDyntopo: (mesh, center, radius, options, pinned) => this.applyDyntopo(mesh, center, radius, options, pinned),
437
+ dyntopoDab: (mesh, dab, options, protection) => this.dyntopoDab(mesh, dab, options, protection)
394
438
  });
395
439
  /** Async remesh, simplification, subdivision, and volumetric reconstruction domain. */
396
440
  remesh = createRemeshDomain({ repair: ((mesh, op) => this.#runRepair(mesh, op)) });
397
- /** Callable async boolean, offsetting, and shell domain (`offset` and `shell` execute in worker). */
441
+ /** Callable async boolean, CSG batch, cut, curve-trim, offset, and shell domain. */
398
442
  boolean = createBooleanDomain({
399
443
  isAsync: true,
400
- repair: ((mesh, op) => this.#runRepair(mesh, op))
444
+ repair: ((mesh, op) => this.#runRepair(mesh, op)),
445
+ boolean: (target, source, op, options) => this.#runBoolean(target, source, op, options),
446
+ booleanBatch: (meshesOrTree, treeOrOptions, maybeOptions) => Array.isArray(meshesOrTree) ? this.booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) : this.booleanBatch(meshesOrTree, treeOrOptions),
447
+ cutByPlane: (mesh, plane, options) => this.cutByPlane(mesh, plane, options),
448
+ trimByCurve: (mesh, optionsOrCurve, maybeOptions) => Array.isArray(optionsOrCurve) ? this.trimByCurve(mesh, optionsOrCurve, maybeOptions) : this.trimByCurve(mesh, optionsOrCurve),
449
+ hollowMesh: (mesh, options) => this.hollowMesh(mesh, options),
450
+ punchDrainHole: (mesh, options) => this.punchDrainHole(mesh, options),
451
+ placeMesh: (target, stamp, options) => this.placeMesh(target, stamp, options)
401
452
  });
402
453
  /** Async surface deformation and vertex-protection domain. */
403
- deform = createDeformDomain({ sculpt: ((mesh, op) => this.#runRepair(mesh, op)) });
404
- /** Async defect analysis, metrology, queries, fields, and section inspection domain. */
454
+ deform = createDeformDomain({
455
+ sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
456
+ buildFfdLattice: (mesh, dims, basis, padding) => this.buildFfdLattice(mesh, dims, basis, padding),
457
+ applyFfd: (mesh, options) => this.applyFfd(mesh, options),
458
+ applyArap: (mesh, options) => this.applyArap(mesh, options),
459
+ applyKelvinlet: (mesh, options) => this.applyKelvinlet(mesh, options),
460
+ applyXpbd: (mesh, options) => this.applyXpbd(mesh, options)
461
+ });
462
+ /** Async defect analysis, printability/quality inspection, metrology, geodesics, queries, fields, and section domain. */
405
463
  inspect = createInspectDomain({
406
464
  analyze: (mesh, options) => this.analyze(mesh, options),
407
465
  measure: (mesh) => this.measure(mesh),
@@ -410,7 +468,14 @@ var WorkerScene = class WorkerScene {
410
468
  closestPoint: (point, options) => this.closestPoint(point, options),
411
469
  meshDistance: (a, b, options) => this.meshDistance(a, b, options),
412
470
  intersects: (a, b) => this.intersects(a, b),
471
+ selfIntersectingTriangles: (mesh) => this.selfIntersectingTriangles(mesh),
413
472
  findContacts: (options) => this.findContacts(options),
473
+ overhangs: (mesh, options) => this.overhangs(mesh, options),
474
+ triangleQuality: (mesh, metricOrOptions, sliverThreshold) => this.triangleQuality(mesh, metricOrOptions, sliverThreshold),
475
+ meshDeviation: (source, target, options) => this.meshDeviation(source, target, options),
476
+ geodesicDistances: (mesh, sources, options) => this.geodesicDistances(mesh, sources, options),
477
+ releaseGeodesics: () => this.releaseGeodesics(),
478
+ shortestSurfacePath: (mesh, sources, targetVertex, options) => this.shortestSurfacePath(mesh, sources, targetVertex, options),
414
479
  addDistanceField: (desc) => this.addDistanceField(desc),
415
480
  removeField: (field) => this.removeField(field),
416
481
  fieldValues: (field) => this.fetchFieldValues(field),
@@ -426,10 +491,20 @@ var WorkerScene = class WorkerScene {
426
491
  setSectionFill: (section, fill) => this.setSectionFill(section, fill),
427
492
  removeSection: (section) => this.removeSection(section),
428
493
  section: (section, mesh) => this.section(section, mesh),
429
- sectionGap: (section, a, b) => this.sectionGap(section, a, b)
494
+ sectionGap: (section, a, b) => this.sectionGap(section, a, b),
495
+ fitPrimitive: (mesh, options) => this.fitPrimitive(mesh, options),
496
+ alignToFittedPrimitive: (mesh, primitive, targetAxis, targetOrigin) => this.alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin),
497
+ sliceContours: (mesh, origin, normal) => this.sliceContours(mesh, origin, normal),
498
+ sliceContourStack: (mesh, origin, normal, spacing, count) => this.sliceContourStack(mesh, origin, normal, spacing, count),
499
+ reconstructPointCloud: (cloud, options) => this.reconstructPointCloud(cloud, options)
500
+ });
501
+ /** Async rigid registration, multi-stage alignment, landmark SVD, and symmetry domain. */
502
+ align = createAlignDomain({
503
+ register: (moving, fixed, options) => this.register(moving, fixed, options),
504
+ alignByLandmarks: (moving, fixed, pairs, allowScaling) => this.alignByLandmarks(moving, fixed, pairs, allowScaling),
505
+ registerMultistage: (moving, fixed, options) => this.registerMultistage(moving, fixed, options),
506
+ detectSymmetryPlane: (mesh) => this.detectSymmetryPlane(mesh)
430
507
  });
431
- /** Async rigid registration and alignment domain. */
432
- align = createAlignDomain({ register: (moving, fixed, options) => this.register(moving, fixed, options) });
433
508
  /** Use {@link createWorkerScene}. */
434
509
  constructor(make, options) {
435
510
  this.#make = make;
@@ -618,27 +693,58 @@ var WorkerScene = class WorkerScene {
618
693
  }
619
694
  return req.rev;
620
695
  }
621
- /** Queues a request with a reply and sends soon; resolves with `map(value)`. */
622
- #ask(make, map) {
696
+ /**
697
+ * Queues a request with a reply and sends soon; resolves with `map(value)`.
698
+ * With a `signal`, an abort rejects at once with its reason and cancels
699
+ * the query (see {@link WorkerScene.#cancel}).
700
+ */
701
+ #ask(make, map, signal) {
623
702
  return new Promise((resolve, reject) => {
624
703
  this.#alive();
625
704
  const qid = ++this.#qid;
626
705
  const req = make(++this.#rev, qid);
706
+ throwIfAborted(signal);
707
+ const abort = () => this.#cancel(qid, signal?.reason);
708
+ signal?.addEventListener("abort", abort, { once: true });
627
709
  this.#replies.set(qid, {
628
710
  resolve: (v) => {
711
+ signal?.removeEventListener("abort", abort);
629
712
  try {
630
713
  resolve(map(v));
631
714
  } catch (e) {
632
715
  reject(e);
633
716
  }
634
717
  },
635
- reject
718
+ reject: (e) => {
719
+ signal?.removeEventListener("abort", abort);
720
+ reject(e);
721
+ }
636
722
  });
637
723
  this.#push(req);
638
724
  this.#scheduleFlush();
639
725
  });
640
726
  }
641
727
  /**
728
+ * Cancels a query: rejects its promise with `reason`, and takes it out of
729
+ * the requests not sent yet, or else tells the Worker to drop it.
730
+ */
731
+ #cancel(qid, reason) {
732
+ const pending = this.#replies.get(qid);
733
+ if (pending === void 0) return;
734
+ this.#replies.delete(qid);
735
+ const at = this.#queue.findIndex((req) => req.qid === qid);
736
+ if (at >= 0) this.#queue.splice(at, 1);
737
+ else if (!this.#terminated && this.#poison === void 0) {
738
+ this.#push({
739
+ kind: "cancel",
740
+ rev: ++this.#rev,
741
+ qid
742
+ });
743
+ this.#scheduleFlush();
744
+ }
745
+ pending.reject(reason);
746
+ }
747
+ /**
642
748
  * Makes sure a queued promise call gets sent: with a frame loop, by the
643
749
  * next `commitFrame()` or else the fallback timer, so pointer-rate queries
644
750
  * never send the frame's moves early; without one, on a microtask.
@@ -660,14 +766,14 @@ var WorkerScene = class WorkerScene {
660
766
  }
661
767
  }
662
768
  /** A query by name, with its reply mapped. */
663
- #query(name, args, map) {
769
+ #query(name, args, map, signal) {
664
770
  return this.#ask((rev, qid) => ({
665
771
  kind: "query",
666
772
  rev,
667
773
  qid,
668
774
  name,
669
775
  args: args()
670
- }), (v) => map(v));
776
+ }), (v) => map(v), signal);
671
777
  }
672
778
  /**
673
779
  * Sends the queued requests as one batch, coalesced; returns it when it
@@ -686,6 +792,7 @@ var WorkerScene = class WorkerScene {
686
792
  }
687
793
  const transfer = [];
688
794
  for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
795
+ else if (req.kind === "addHeightfield") transfer.push(req.field.heights.buffer);
689
796
  try {
690
797
  if (this.#handoff !== void 0) {
691
798
  const held = structuredClone(batch, { transfer });
@@ -711,6 +818,7 @@ var WorkerScene = class WorkerScene {
711
818
  #fail(batch, error, log = true) {
712
819
  for (const req of batch) {
713
820
  if (log) this.#logFailed(req);
821
+ if (req.kind === "entry") this.#entries.tell(req.id, "drop");
714
822
  const key = keyOf(req);
715
823
  if (key !== void 0 && this.#latest.get(key) === req.rev) this.#setStatus(key, {
716
824
  status: "error",
@@ -744,6 +852,7 @@ var WorkerScene = class WorkerScene {
744
852
  this.#drag.active = false;
745
853
  this.#drag = void 0;
746
854
  }
855
+ this.#stepDepth = 0;
747
856
  for (const st of this.#meshes.values()) {
748
857
  if (st.local !== void 0 && !samePose(st.local, st.pose)) this.#optimistic.add(st);
749
858
  st.local = void 0;
@@ -765,6 +874,7 @@ var WorkerScene = class WorkerScene {
765
874
  this.#batchDone.delete(batch);
766
875
  }
767
876
  this.#releaseHolds();
877
+ this.#entries.dropAll();
768
878
  this.#statusChanged();
769
879
  }
770
880
  #receive(msg) {
@@ -810,6 +920,7 @@ var WorkerScene = class WorkerScene {
810
920
  });
811
921
  for (const req of batch) this.#logFailed(req);
812
922
  this.#releaseHolds();
923
+ this.#entries.dropAll();
813
924
  this.#applyStatus(r);
814
925
  this.#applyReplies(r);
815
926
  for (const req of batch) {
@@ -829,15 +940,23 @@ var WorkerScene = class WorkerScene {
829
940
  for (const k of st.pendingRules.keys()) if (k <= rev) st.pendingRules.delete(k);
830
941
  }
831
942
  for (const c of r.changes) this.#applyChange(c);
943
+ const permanent = this.#permanentSteps(r);
944
+ this.#applyPresence(r);
832
945
  for (const st of this.#meshes.values()) if (st.colors === null) st.shown = null;
833
946
  for (const p of r.placements) {
834
947
  const st = this.#meshes.get(p.id);
835
- if (st !== void 0) st.pose = {
836
- rotation: p.rotation,
837
- translation: p.translation,
838
- scale: p.scale,
839
- matrix4: Float64Array.from(p.matrix4)
840
- };
948
+ if (st !== void 0) {
949
+ st.pose = {
950
+ rotation: p.rotation,
951
+ translation: p.translation,
952
+ scale: p.scale,
953
+ matrix4: Float64Array.from(p.matrix4)
954
+ };
955
+ if (p.authoritative && st.local !== void 0 && st.localUntil === Number.POSITIVE_INFINITY && r.rev >= (this.#latest.get(`placement:${st.id}`) ?? 0) && !samePose(st.local, st.pose)) {
956
+ st.local = st.pose;
957
+ this.#optimistic.add(st);
958
+ }
959
+ }
841
960
  }
842
961
  for (const s of r.sections) {
843
962
  const st = this.#sections.get(s.section);
@@ -857,9 +976,42 @@ var WorkerScene = class WorkerScene {
857
976
  this.#history = { ...r.history };
858
977
  this.#statusChanged();
859
978
  }
979
+ this.#historyBytes = r.historyBytes ?? 0;
860
980
  this.#applyStatus(r);
981
+ this.#applyEntries(r);
982
+ tellPermanent(this.#permanentListeners, permanent);
861
983
  this.#applyReplies(r);
862
984
  }
985
+ /**
986
+ * Calls the application's entries the result undid, redid or dropped. An
987
+ * entry recorded here since the request that undid (or redid) them was made
988
+ * comes after it in the history, but its change is made already: it steps
989
+ * back first and forward again after, so that the callbacks run in the
990
+ * history's order.
991
+ */
992
+ #applyEntries(r) {
993
+ const events = r.entries ?? [];
994
+ for (let k = 0; k < events.length;) {
995
+ const { id, what, rev } = events[k];
996
+ if (what === "drop") {
997
+ this.#entries.tell(id, what);
998
+ k++;
999
+ continue;
1000
+ }
1001
+ const later = this.#entries.after(rev);
1002
+ for (const l of [...later].reverse()) this.#entries.tell(l, "undo");
1003
+ for (; k < events.length && events[k].rev === rev && events[k].what !== "drop"; k++) this.#entries.tell(events[k].id, events[k].what);
1004
+ for (const l of later) this.#entries.tell(l, "redo");
1005
+ }
1006
+ }
1007
+ #permanentSteps(r) {
1008
+ const handles = (ids) => ids.flatMap((id) => this.#meshes.get(id)?.handle ?? []);
1009
+ return (r.permanent ?? []).map((p) => ({
1010
+ ...p,
1011
+ meshes: handles(p.meshes),
1012
+ gone: handles(p.gone)
1013
+ }));
1014
+ }
863
1015
  #applyStatus(r) {
864
1016
  for (const s of r.status) {
865
1017
  const latest = this.#latest.get(s.key) ?? 0;
@@ -890,11 +1042,18 @@ var WorkerScene = class WorkerScene {
890
1042
  if (st === void 0) return;
891
1043
  if (c.removed) {
892
1044
  st.live = false;
1045
+ if (c.restorable === true) st.parkedRule = st.shown;
893
1046
  this.#clearMirrors(st);
894
1047
  } else {
895
1048
  if (c.added) {
896
1049
  st.live = true;
897
1050
  st.add = void 0;
1051
+ st.shown ??= st.parkedRule;
1052
+ st.parkedRule = null;
1053
+ if (c.origin !== void 0) {
1054
+ st.origin = [...c.origin];
1055
+ st.pose = poseOf(st.pose.rotation, st.pose.translation, st.origin, st.pose.scale);
1056
+ }
898
1057
  }
899
1058
  for (const name of BUFFERS) this.#applyBuffer(st, name, c);
900
1059
  if (c.bounds !== void 0) st.bounds = cloneBounds(c.bounds);
@@ -903,6 +1062,7 @@ var WorkerScene = class WorkerScene {
903
1062
  mesh: st.handle,
904
1063
  added: c.added,
905
1064
  removed: c.removed,
1065
+ ...c.restorable === true ? { restorable: true } : {},
906
1066
  placementChanged: c.placementChanged,
907
1067
  capacityChanged: c.capacityChanged,
908
1068
  positions: c.positions,
@@ -916,6 +1076,79 @@ var WorkerScene = class WorkerScene {
916
1076
  const prev = this.#changes.get(st);
917
1077
  this.#changes.set(st, prev === void 0 ? record : merge(prev, record));
918
1078
  }
1079
+ /**
1080
+ * Follows the meshes that undoable adds and removals, and their undo and
1081
+ * redo, moved out of the engine's scene or back into it. A removal
1082
+ * requested after the result's batch decides instead.
1083
+ */
1084
+ #applyPresence(r) {
1085
+ if (r.presence === void 0 && r.fieldTargets === void 0 && r.sectionMeshes === void 0) return;
1086
+ this.#presenceVersion++;
1087
+ this.#statusChanged();
1088
+ const moved = (r.presence ?? []).flatMap(({ id, state }) => {
1089
+ const st = this.#meshes.get(id);
1090
+ return st === void 0 || r.rev < st.removedRev ? [] : [{
1091
+ st,
1092
+ state
1093
+ }];
1094
+ });
1095
+ const left = [];
1096
+ for (const { st, state } of moved) {
1097
+ if (state === "live") {
1098
+ st.removed = false;
1099
+ st.parked = false;
1100
+ st.gone = false;
1101
+ st.removedRev = 0;
1102
+ continue;
1103
+ }
1104
+ if (!st.removed) left.push(st);
1105
+ st.removed = true;
1106
+ st.parked = state === "parked";
1107
+ st.live = false;
1108
+ st.add = void 0;
1109
+ st.local = void 0;
1110
+ st.localUntil = 0;
1111
+ st.requested = void 0;
1112
+ st.requestedUntil = 0;
1113
+ if (!st.gone && this.#changes.get(st)?.removed !== true) {
1114
+ this.#clearMirrors(st);
1115
+ this.#removedHere(st);
1116
+ }
1117
+ }
1118
+ for (const st of left) {
1119
+ this.#dropLinks(st);
1120
+ this.#dropCollisionRules(st, r.rev);
1121
+ }
1122
+ for (const { section, meshes } of r.sectionMeshes ?? []) {
1123
+ const s = this.#sections.get(section);
1124
+ if (s !== void 0 && !s.removed && (this.#latest.get(`section:${section}:meshes`) ?? 0) <= r.rev) s.meshes = meshes.flatMap((id) => this.#meshes.get(id) ?? []);
1125
+ }
1126
+ for (const { field, to } of r.fieldTargets ?? []) {
1127
+ const f = this.#fields.get(field);
1128
+ if (f === void 0 || f.removed) continue;
1129
+ if (to === null) this.#fieldRemoved(f, r.rev);
1130
+ else f.desc = {
1131
+ ...f.desc,
1132
+ to
1133
+ };
1134
+ }
1135
+ for (const { st, state } of moved) if (state === "gone" && st.gone) this.#forgetMesh(st);
1136
+ }
1137
+ /** Keeps only a tombstone of a mesh removed for good, once its removal is delivered. */
1138
+ #forgetMesh(st) {
1139
+ this.#dropCollisionRules(st);
1140
+ this.#meshes.delete(st.id);
1141
+ this.#byMesh.delete(st.handle);
1142
+ this.#tombstones.add(st.handle);
1143
+ const id = st.id;
1144
+ this.#forgetKeys([
1145
+ `mesh:${id}`,
1146
+ `placement:${id}`,
1147
+ `edit:${id}`,
1148
+ `display:${id}`
1149
+ ], []);
1150
+ this.#statusChanged();
1151
+ }
919
1152
  #clearMirrors(st) {
920
1153
  st.positions = /* @__PURE__ */ new Float32Array(0);
921
1154
  st.indices = /* @__PURE__ */ new Uint32Array(0);
@@ -1050,7 +1283,8 @@ var WorkerScene = class WorkerScene {
1050
1283
  * it that do not need it run meanwhile, so a reply to one of them can
1051
1284
  * arrive before the mesh. Until it lands, `status("mesh:<id>")` reads
1052
1285
  * `"computing"` and its views are empty; its buffers arrive with that
1053
- * status turning `"ready"`.
1286
+ * status turning `"ready"`. An `undoable` add is never in the background:
1287
+ * it lands in the step it was made in, and undo removes the mesh again.
1054
1288
  */
1055
1289
  addMesh(positions, indices, options = {}) {
1056
1290
  this.#alive();
@@ -1062,17 +1296,36 @@ var WorkerScene = class WorkerScene {
1062
1296
  options.origin[1],
1063
1297
  options.origin[2]
1064
1298
  ];
1065
- const id = ++this.#nextMesh;
1066
- const handle = new MeshHandle();
1067
- const known = origin ?? [
1299
+ const st = this.#allocMeshState(origin ?? [
1068
1300
  0,
1069
1301
  0,
1070
1302
  0
1071
- ];
1303
+ ], options.normals ?? true);
1304
+ const undoable = options.undoable === true;
1305
+ st.add = {
1306
+ kind: "addMesh",
1307
+ rev: ++this.#rev,
1308
+ id: st.id,
1309
+ positions: p.buffer,
1310
+ f64: !(p instanceof Float32Array),
1311
+ indices: i.buffer,
1312
+ ...uvs === void 0 ? {} : { uvs: uvs.buffer },
1313
+ options: {
1314
+ origin,
1315
+ normals: st.normalsOn,
1316
+ ...undoable ? { undoable } : {}
1317
+ }
1318
+ };
1319
+ this.#push(st.add);
1320
+ return st.handle;
1321
+ }
1322
+ #allocMeshState(knownOrigin, normalsOn) {
1323
+ const id = ++this.#nextMesh;
1324
+ const handle = new MeshHandle();
1072
1325
  const st = {
1073
1326
  id,
1074
1327
  handle,
1075
- origin: known,
1328
+ origin: knownOrigin,
1076
1329
  positions: /* @__PURE__ */ new Float32Array(0),
1077
1330
  normals: null,
1078
1331
  colors: null,
@@ -1086,7 +1339,7 @@ var WorkerScene = class WorkerScene {
1086
1339
  0,
1087
1340
  0,
1088
1341
  0
1089
- ], known, [
1342
+ ], knownOrigin, [
1090
1343
  1,
1091
1344
  1,
1092
1345
  1
@@ -1096,51 +1349,83 @@ var WorkerScene = class WorkerScene {
1096
1349
  requested: void 0,
1097
1350
  requestedUntil: 0,
1098
1351
  removed: false,
1352
+ removedRev: 0,
1353
+ parked: false,
1099
1354
  gone: false,
1355
+ parkedRule: null,
1100
1356
  coloring: null,
1101
1357
  live: false,
1102
- normalsOn: options.normals ?? true,
1358
+ normalsOn,
1103
1359
  add: void 0,
1104
1360
  sent: false
1105
1361
  };
1106
1362
  this.#meshes.set(id, st);
1107
1363
  this.#byMesh.set(handle, st);
1108
- st.add = {
1109
- kind: "addMesh",
1110
- rev: ++this.#rev,
1111
- id,
1112
- positions: p.buffer,
1113
- f64: !(p instanceof Float32Array),
1114
- indices: i.buffer,
1115
- ...uvs === void 0 ? {} : { uvs: uvs.buffer },
1116
- options: {
1117
- origin,
1118
- normals: st.normalsOn
1119
- }
1120
- };
1121
- this.#push(st.add);
1122
- return handle;
1364
+ return st;
1365
+ }
1366
+ #discardPlaceholder(st) {
1367
+ if (st !== void 0 && !st.live) {
1368
+ st.removed = true;
1369
+ st.gone = true;
1370
+ this.#meshes.delete(st.id);
1371
+ this.#byMesh.delete(st.handle);
1372
+ }
1373
+ }
1374
+ #endDragOn(...meshes) {
1375
+ if (this.#drag !== void 0 && meshes.includes(this.#drag.mesh)) this.#drag.end();
1123
1376
  }
1124
1377
  /**
1125
1378
  * Removes a mesh, ending an active drag of it first. Later calls on it give
1126
1379
  * `UNKNOWN_MESH`; its mirrors stay readable until the removal is delivered
1127
1380
  * by `commitFrame()`.
1381
+ *
1382
+ * With `undoable` the removal is an undo step (or part of the open one):
1383
+ * {@link WorkerScene.undo} brings the mesh back with the same handle, as
1384
+ * `Scene.removeMesh` does. A {@link WorkerScene.restart} clears the history,
1385
+ * so it makes the removal permanent, and so does one larger than the
1386
+ * history budget: {@link WorkerScene.onPermanent} tells once the result is
1387
+ * in, and {@link WorkerScene.removalBytes} before.
1128
1388
  */
1129
- removeMesh(mesh) {
1389
+ removeMesh(mesh, options = {}) {
1130
1390
  const st = this.#live(mesh);
1131
1391
  if (this.#drag?.mesh === st) this.#drag.end();
1392
+ const undoable = options.undoable === true;
1132
1393
  const rev = ++this.#rev;
1394
+ st.parked = undoable;
1133
1395
  this.#noteRemoved(st, rev);
1134
1396
  this.#push({
1135
1397
  kind: "removeMesh",
1136
1398
  rev,
1137
- id: st.id
1399
+ id: st.id,
1400
+ ...undoable ? { undoable } : {}
1138
1401
  });
1139
1402
  }
1140
1403
  /**
1404
+ * Whether the scene has `mesh`: `false` once its removal is requested, or
1405
+ * a result says that the undo of its add (or the redo of its removal) took
1406
+ * it out.
1407
+ */
1408
+ has(mesh) {
1409
+ return !(mesh instanceof MeshHandle && this.#tombstones.has(mesh)) && !this.#state(mesh).removed;
1410
+ }
1411
+ /**
1412
+ * Whether undo or redo can still bring back a removed `mesh`, as of the
1413
+ * latest result (see `Scene.isRestorable`).
1414
+ */
1415
+ isRestorable(mesh) {
1416
+ if (mesh instanceof MeshHandle && this.#tombstones.has(mesh)) return false;
1417
+ const st = this.#state(mesh);
1418
+ return st.removed && st.parked;
1419
+ }
1420
+ /** About the bytes of history an undoable removal of `mesh` takes; see `Scene.removalBytes`. */
1421
+ removalBytes(mesh) {
1422
+ return this.#query("removalBytes", () => ({ mesh: this.#live(mesh).id }), (v) => v);
1423
+ }
1424
+ /**
1141
1425
  * Joins `source` into `target`; see `Scene.join`. The source stays usable
1142
1426
  * until the join lands: only a successful result removes it (a failed join
1143
- * changes nothing, engine-side or here).
1427
+ * changes nothing, engine-side or here), as part of the join's undo step.
1428
+ * {@link WorkerScene.undo} brings it back.
1144
1429
  *
1145
1430
  * @deprecated Use `workerScene.repair.join()` instead.
1146
1431
  */
@@ -1149,29 +1434,31 @@ var WorkerScene = class WorkerScene {
1149
1434
  const st = this.#live(source);
1150
1435
  if (this.#drag?.mesh === st) this.#drag.end();
1151
1436
  const payload = copyInput(options, "options");
1152
- let rev = 0;
1153
- return this.#ask((r, qid) => {
1154
- rev = r;
1155
- return {
1156
- kind: "join",
1157
- rev: r,
1158
- target: ta.id,
1159
- source: st.id,
1160
- payload,
1161
- qid
1162
- };
1163
- }, (v) => v).then((report) => {
1164
- this.#noteRemoved(st, rev);
1165
- return report;
1166
- });
1437
+ return this.#ask((rev, qid) => ({
1438
+ kind: "join",
1439
+ rev,
1440
+ target: ta.id,
1441
+ source: st.id,
1442
+ payload,
1443
+ qid
1444
+ }), (v) => v);
1167
1445
  }
1168
1446
  /**
1169
1447
  * Notes a mesh as removed at `rev`: later calls on it give `UNKNOWN_MESH`,
1170
- * fields on it (or only to it) are dropped and its section entries go. The
1171
- * engine does the same when the removal lands.
1448
+ * and its links go ({@link WorkerScene.#dropLinks}).
1172
1449
  */
1173
1450
  #noteRemoved(st, rev) {
1174
1451
  st.removed = true;
1452
+ st.removedRev = rev;
1453
+ if (!st.parked) this.#dropFieldsOf(st, rev);
1454
+ this.#dropLinks(st);
1455
+ }
1456
+ /**
1457
+ * Drops the fields on a mesh removed for good (or only to it). The engine
1458
+ * does the same when the removal lands; for a parked mesh it says what is
1459
+ * left of the fields ({@link WorkerScene.#applyPresence}).
1460
+ */
1461
+ #dropFieldsOf(st, rev) {
1175
1462
  for (const f of this.#fields.values()) {
1176
1463
  if (f.removed) continue;
1177
1464
  if (f.desc.on === st.id || f.desc.to.length === 1 && f.desc.to[0] === st.id) this.#fieldRemoved(f, rev);
@@ -1180,7 +1467,18 @@ var WorkerScene = class WorkerScene {
1180
1467
  to: f.desc.to.filter((m) => m !== st.id)
1181
1468
  };
1182
1469
  }
1470
+ }
1471
+ /**
1472
+ * A removed mesh's section entries go, as they do in the engine, and its
1473
+ * collision rules, unless it is parked: they come back with it.
1474
+ */
1475
+ #dropLinks(st) {
1183
1476
  for (const s of this.#sections.values()) if (!s.removed) s.meshes = s.meshes.filter((m) => m !== st);
1477
+ if (!st.parked) this.#dropCollisionRules(st);
1478
+ }
1479
+ /** Drops the collision rules of a mesh's pairs: those requested after `rev` only, if given. */
1480
+ #dropCollisionRules(st, rev = 0) {
1481
+ for (const [key, entry] of [...this.#collisionRules.entries()]) if ((entry.a === st || entry.b === st) && entry.rev > rev) this.#collisionRules.delete(key);
1184
1482
  }
1185
1483
  /**
1186
1484
  * Rigidly aligns `moving` to `fixed` by ICP from their placements as the
@@ -1211,6 +1509,249 @@ var WorkerScene = class WorkerScene {
1211
1509
  }), (v) => v);
1212
1510
  }
1213
1511
  /**
1512
+ * Aligns `moving` to `fixed` using corresponding world-space landmark pairs
1513
+ * via Umeyama N-point SVD (see `Scene.alignByLandmarks`).
1514
+ */
1515
+ alignByLandmarks(moving, fixed, pairs, allowScaling = false) {
1516
+ return this.#ask((rev, qid) => {
1517
+ const m = this.#live(moving);
1518
+ const f = this.#live(fixed);
1519
+ normalizeLandmarkPairs(m === f, pairs, allowScaling);
1520
+ this.#endDragOn(m, f);
1521
+ return {
1522
+ kind: "alignByLandmarks",
1523
+ rev,
1524
+ moving: m.id,
1525
+ fixed: f.id,
1526
+ pairs: pairs.map((p) => ({
1527
+ source: normalizeVec3(p.source, "pair.source"),
1528
+ target: normalizeVec3(p.target, "pair.target")
1529
+ })),
1530
+ allowScaling,
1531
+ qid
1532
+ };
1533
+ }, (v) => v);
1534
+ }
1535
+ /**
1536
+ * Runs multi-stage coarse + fine ICP registration from `moving` to `fixed`
1537
+ * (see `Scene.registerMultistage`).
1538
+ */
1539
+ registerMultistage(moving, fixed, options = {}) {
1540
+ return this.#ask((rev, qid) => {
1541
+ const m = this.#live(moving);
1542
+ const f = this.#live(fixed);
1543
+ const payload = normalizeRegistrationOptions(m === f, options);
1544
+ this.#endDragOn(m, f);
1545
+ return {
1546
+ kind: "registerMultistage",
1547
+ rev,
1548
+ moving: m.id,
1549
+ fixed: f.id,
1550
+ payload,
1551
+ qid
1552
+ };
1553
+ }, (v) => v);
1554
+ }
1555
+ /** Detects the dominant world-space reflection symmetry plane of `mesh`. */
1556
+ detectSymmetryPlane(mesh) {
1557
+ return this.#query("detectSymmetryPlane", () => ({ mesh: this.#live(mesh).id }), (v) => v);
1558
+ }
1559
+ /** Async boolean CSG operation backing {@link WorkerScene.boolean}. */
1560
+ #runBoolean(target, source, op, options) {
1561
+ return this.#ask((rev, qid) => {
1562
+ const ta = this.#live(target);
1563
+ const sb = this.#live(source);
1564
+ const payload = normalizeBooleanArgs(op, options);
1565
+ this.#endDragOn(ta, sb);
1566
+ return {
1567
+ kind: "boolean",
1568
+ rev,
1569
+ target: ta.id,
1570
+ source: sb.id,
1571
+ payload,
1572
+ qid
1573
+ };
1574
+ }, () => target);
1575
+ }
1576
+ booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) {
1577
+ let added;
1578
+ return this.#ask((rev, qid) => {
1579
+ const { meshes, tree, options } = normalizeCsgBatchArgs(meshesOrTree, treeOrOptions, maybeOptions);
1580
+ const states = meshes.map((m) => this.#live(m));
1581
+ added = this.#allocMeshState([
1582
+ 0,
1583
+ 0,
1584
+ 0
1585
+ ], states[0]?.normalsOn ?? true);
1586
+ return {
1587
+ kind: "booleanBatch",
1588
+ rev,
1589
+ meshes: states.map((s) => s.id),
1590
+ tree,
1591
+ options,
1592
+ addedId: added.id,
1593
+ qid
1594
+ };
1595
+ }, () => added.handle).catch((e) => {
1596
+ this.#discardPlaceholder(added);
1597
+ throw e;
1598
+ });
1599
+ }
1600
+ /** Cuts `mesh` by `plane` in the Worker (see `Scene.cutByPlane`). */
1601
+ cutByPlane(mesh, plane, options) {
1602
+ let added;
1603
+ return this.#ask((rev, qid) => {
1604
+ const st = this.#live(mesh);
1605
+ if (plane == null || typeof plane !== "object") throw invalid("plane must be an object");
1606
+ const origin = normalizeVec3(plane.origin, "plane.origin");
1607
+ const normal = normalizeVec3(plane.normal, "plane.normal");
1608
+ const cap = options?.cap ?? true;
1609
+ if (typeof cap !== "boolean") throw invalid("cap must be a boolean");
1610
+ this.#endDragOn(st);
1611
+ added = this.#allocMeshState(st.origin, st.normalsOn);
1612
+ return {
1613
+ kind: "cutByPlane",
1614
+ rev,
1615
+ id: st.id,
1616
+ addedId: added.id,
1617
+ plane: {
1618
+ origin,
1619
+ normal
1620
+ },
1621
+ cap,
1622
+ qid
1623
+ };
1624
+ }, (v) => {
1625
+ const r = v;
1626
+ return {
1627
+ kept: mesh,
1628
+ removed: added.handle,
1629
+ keptTriangles: r.keptTriangles,
1630
+ removedTriangles: r.removedTriangles,
1631
+ capTriangles: r.capTriangles
1632
+ };
1633
+ }).catch((e) => {
1634
+ this.#discardPlaceholder(added);
1635
+ throw e;
1636
+ });
1637
+ }
1638
+ trimByCurve(mesh, optionsOrCurve, maybeOptions) {
1639
+ return this.#ask((rev, qid) => {
1640
+ const st = this.#live(mesh);
1641
+ const payload = normalizeTrimCurveArgs(optionsOrCurve, maybeOptions);
1642
+ this.#endDragOn(st);
1643
+ return {
1644
+ kind: "trimByCurve",
1645
+ rev,
1646
+ id: st.id,
1647
+ payload,
1648
+ qid
1649
+ };
1650
+ }, (v) => {
1651
+ return {
1652
+ kept: mesh,
1653
+ ...v
1654
+ };
1655
+ });
1656
+ }
1657
+ /** Fills a single boundary loop with selectable G0/G1/G2 continuity. */
1658
+ fillHoleContinuity(mesh, loopIndex, options = {}) {
1659
+ return this.#ask((rev, qid) => {
1660
+ const st = this.#live(mesh);
1661
+ const norm = normalizeFillHolesContinuityOptions(options);
1662
+ const loopIdx = checkU32Int(loopIndex, "loopIndex");
1663
+ this.#endDragOn(st);
1664
+ return {
1665
+ kind: "fillHoleContinuity",
1666
+ rev,
1667
+ id: st.id,
1668
+ loopIndex: loopIdx,
1669
+ options: norm,
1670
+ qid
1671
+ };
1672
+ }, (v) => v);
1673
+ }
1674
+ /** Fills all eligible holes with selectable G0/G1/G2 continuity. */
1675
+ fillAllHolesContinuity(mesh, options = {}) {
1676
+ return this.#ask((rev, qid) => {
1677
+ const st = this.#live(mesh);
1678
+ const norm = normalizeFillHolesContinuityOptions(options);
1679
+ this.#endDragOn(st);
1680
+ return {
1681
+ kind: "fillAllHolesContinuity",
1682
+ rev,
1683
+ id: st.id,
1684
+ options: norm,
1685
+ qid
1686
+ };
1687
+ }, (v) => v);
1688
+ }
1689
+ /** Bridges two boundary vertex arcs or index ranges. */
1690
+ bridgePartialArcs(mesh, loopA = [], loopB = [], options = {}) {
1691
+ return this.#ask((rev, qid) => {
1692
+ const st = this.#live(mesh);
1693
+ const vertsA = normalizeU32List(loopA, "loopA");
1694
+ const vertsB = normalizeU32List(loopB, "loopB");
1695
+ const norm = normalizePartialBridgeOptions(options);
1696
+ this.#endDragOn(st);
1697
+ return {
1698
+ kind: "bridgePartialArcs",
1699
+ rev,
1700
+ id: st.id,
1701
+ loopA: vertsA,
1702
+ loopB: vertsB,
1703
+ options: norm,
1704
+ qid
1705
+ };
1706
+ }, (v) => v);
1707
+ }
1708
+ /** Runs localized dynamic topology remeshing inside sphere `(center, radius)`. */
1709
+ applyDyntopo(mesh, center, radius, options = {}, pinned = []) {
1710
+ return this.#ask((rev, qid) => {
1711
+ const st = this.#live(mesh);
1712
+ const cr = normalizeDyntopoCenterRadius(center, radius);
1713
+ const norm = normalizeDyntopoOptions(options);
1714
+ const pinnedList = normalizeU32List(pinned, "pinned");
1715
+ this.#endDragOn(st);
1716
+ return {
1717
+ kind: "applyDyntopo",
1718
+ rev,
1719
+ id: st.id,
1720
+ center: cr.center,
1721
+ radius: cr.radius,
1722
+ options: norm,
1723
+ pinned: pinnedList,
1724
+ qid
1725
+ };
1726
+ }, (v) => v);
1727
+ }
1728
+ /** Applies localized dynamic topology remeshing followed by a brush dab. */
1729
+ dyntopoDab(mesh, dab, options = {}, protection) {
1730
+ return this.#ask((rev, qid) => {
1731
+ const st = this.#live(mesh);
1732
+ if (!isBrushSculptOp(dab)) throw invalid("dyntopoDab requires a brush sculpt operation");
1733
+ const norm = normalizeDyntopoOptions(options);
1734
+ const effective = protection !== void 0 ? {
1735
+ ...dab,
1736
+ protect: protection
1737
+ } : { ...dab };
1738
+ if (effective.protect !== void 0) effective.protect = {
1739
+ vertices: normalizeU32List(effective.protect.vertices, "protect.vertices"),
1740
+ ...effective.protect.weights !== void 0 ? { weights: Array.from(effective.protect.weights) } : {},
1741
+ ...effective.protect.band !== void 0 ? { band: effective.protect.band } : {}
1742
+ };
1743
+ this.#endDragOn(st);
1744
+ return {
1745
+ kind: "dyntopoDab",
1746
+ rev,
1747
+ id: st.id,
1748
+ dab: effective,
1749
+ options: norm,
1750
+ qid
1751
+ };
1752
+ }, (v) => v);
1753
+ }
1754
+ /**
1214
1755
  * Sets a mesh's placement (one undo step), scale included (`[1, 1, 1]`
1215
1756
  * when omitted); `placement()` follows when the result arrives.
1216
1757
  */
@@ -1318,6 +1859,8 @@ var WorkerScene = class WorkerScene {
1318
1859
  drag(mesh) {
1319
1860
  const st = this.#live(mesh);
1320
1861
  if (this.#drag?.active) throw invalid("a drag is already active; end or cancel it first");
1862
+ this.#stepDepth++;
1863
+ const dragDepth = this.#stepDepth;
1321
1864
  const start = st.requested !== void 0 && (st.local === void 0 || st.requestedUntil > st.localUntil) ? st.requested : st.local ?? st.pose;
1322
1865
  const key = `placement:${st.id}`;
1323
1866
  this.#push({
@@ -1333,6 +1876,7 @@ var WorkerScene = class WorkerScene {
1333
1876
  if (!d.active) return false;
1334
1877
  d.active = false;
1335
1878
  this.#drag = void 0;
1879
+ this.#stepDepth = Math.min(this.#stepDepth, dragDepth - 1);
1336
1880
  if (this.#terminated) return true;
1337
1881
  st.localUntil = this.#push({
1338
1882
  kind: "drag",
@@ -1346,8 +1890,19 @@ var WorkerScene = class WorkerScene {
1346
1890
  const d = {
1347
1891
  mesh: st,
1348
1892
  active: true,
1893
+ stepDepth: dragDepth,
1349
1894
  end: () => {
1350
1895
  finish("end");
1896
+ },
1897
+ abandon: (rev, restore = false) => {
1898
+ if (!d.active) return;
1899
+ d.active = false;
1900
+ this.#drag = void 0;
1901
+ st.localUntil = rev;
1902
+ if (restore) {
1903
+ st.local = start;
1904
+ this.#optimistic.add(st);
1905
+ }
1351
1906
  }
1352
1907
  };
1353
1908
  this.#drag = d;
@@ -1464,58 +2019,1080 @@ var WorkerScene = class WorkerScene {
1464
2019
  };
1465
2020
  }, (v) => v);
1466
2021
  }
1467
- /** Undoes the latest step; an active drag is ended first. */
1468
- undo() {
1469
- this.#alive();
1470
- this.#drag?.end();
1471
- this.#forgetRequested();
1472
- this.#push({
1473
- kind: "undo",
1474
- rev: ++this.#rev
1475
- });
2022
+ /** Evaluates world-space printability overhangs against `buildDirection` (see `Scene.overhangs`). */
2023
+ overhangs(mesh, options = {}) {
2024
+ return this.#query("overhangs", () => ({
2025
+ mesh: this.#live(mesh).id,
2026
+ options: normalizeOverhangOptions(options)
2027
+ }), (v) => v);
1476
2028
  }
1477
- /** Redoes the latest undone step; an active drag is ended first. */
1478
- redo() {
1479
- this.#alive();
1480
- this.#drag?.end();
1481
- this.#forgetRequested();
1482
- this.#push({
1483
- kind: "redo",
1484
- rev: ++this.#rev
1485
- });
2029
+ /** Computes per-triangle geometric quality and worst-incident vertex quality (see `Scene.triangleQuality`). */
2030
+ triangleQuality(mesh, metricOrOptions = "radiusRatio", sliverThreshold) {
2031
+ return this.#query("triangleQuality", () => {
2032
+ const id = this.#live(mesh).id;
2033
+ const norm = normalizeQualityArgs(metricOrOptions, sliverThreshold);
2034
+ return {
2035
+ mesh: id,
2036
+ metric: norm.metric,
2037
+ sliverThreshold: norm.sliverThreshold
2038
+ };
2039
+ }, (v) => v);
1486
2040
  }
1487
- /**
1488
- * An undo or redo is queued: requested placements and the poses held for
1489
- * ended drags no longer say where the meshes will be. The engine's pose is
1490
- * shown (and a new drag starts from it) until the results arrive.
1491
- */
1492
- #forgetRequested() {
1493
- for (const st of this.#meshes.values()) {
1494
- st.requested = void 0;
1495
- if (st.local !== void 0 && st.localUntil !== Number.POSITIVE_INFINITY) {
1496
- if (!samePose(st.local, st.pose)) this.#optimistic.add(st);
1497
- st.local = void 0;
1498
- st.localUntil = 0;
1499
- }
1500
- }
2041
+ /** Computes vertex-wise Hausdorff or signed distance deviation from `source` to `target`. */
2042
+ meshDeviation(source, target, options = {}) {
2043
+ return this.#query("meshDeviation", () => ({
2044
+ source: this.#live(source).id,
2045
+ target: this.#live(target).id,
2046
+ options: normalizeDeviationOptions(options)
2047
+ }), (v) => v);
1501
2048
  }
1502
2049
  /**
1503
- * The threads the engine computes with: more than 1 when the threaded
1504
- * engine runs (see {@link WorkerSceneOptions.threads}), 1 when
1505
- * single-threaded. As of the current Worker's start (1 until it is ready).
2050
+ * Computes geodesic surface distances from `sources` on `mesh` (`"dijkstra"`
2051
+ * or `"heatMethod"`), in steps on the Worker: `options.signal` cancels the
2052
+ * query. Other requests wait for it.
1506
2053
  */
1507
- get threads() {
1508
- return this.#threads;
2054
+ geodesicDistances(mesh, sources, options = {}) {
2055
+ return this.#query("geodesicDistances", () => ({
2056
+ mesh: this.#live(mesh).id,
2057
+ sources: Array.from(normalizeSourceVertices(sources)),
2058
+ options: normalizeGeodesicOptions(options)
2059
+ }), (v) => v, options.signal);
1509
2060
  }
1510
- /** Whether there is a step to undo, as of the latest result. */
1511
- get canUndo() {
1512
- return this.#history.canUndo;
2061
+ /** Frees what `"heatMethod"` queries keep in the Worker for the next one of the same mesh. */
2062
+ releaseGeodesics() {
2063
+ return this.#query("releaseGeodesics", () => ({}), () => void 0);
2064
+ }
2065
+ /**
2066
+ * Traces an intrinsic shortest path along the surface of `mesh` to
2067
+ * `targetVertex`. Without `options.distances` it computes them first, like
2068
+ * {@link WorkerScene.geodesicDistances}: `options.signal` cancels that.
2069
+ */
2070
+ shortestSurfacePath(mesh, sources, targetVertex, options = {}) {
2071
+ return this.#query("shortestSurfacePath", () => {
2072
+ const id = this.#live(mesh).id;
2073
+ const src = Array.from(normalizeSourceVertices(sources));
2074
+ const target = normalizeSurfacePathTarget(targetVertex);
2075
+ const checked = checkSurfacePathOptions(options);
2076
+ return {
2077
+ mesh: id,
2078
+ sources: src,
2079
+ targetVertex: target,
2080
+ options: {
2081
+ ...checked.geodesic,
2082
+ ...checked.distances === void 0 ? {} : { distances: checked.distances.slice() }
2083
+ }
2084
+ };
2085
+ }, (v) => v, options.signal);
2086
+ }
2087
+ selectFacesScreen(mesh, shape, options) {
2088
+ return this.#query("selectFacesScreen", () => {
2089
+ const id = this.#live(mesh).id;
2090
+ normalizeScreenSelectArgs(shape, options);
2091
+ return {
2092
+ mesh: id,
2093
+ shape: copyInput(shape, "shape"),
2094
+ options: copyInput(options, "options")
2095
+ };
2096
+ }, (v) => v);
2097
+ }
2098
+ selectFacesInSphere(mesh, center, radius, normalCone) {
2099
+ return this.#query("selectFacesInSphere", () => {
2100
+ const id = this.#live(mesh).id;
2101
+ normalizeSelectInSphereArgs(center, radius, normalCone);
2102
+ return {
2103
+ mesh: id,
2104
+ center: [
2105
+ center[0],
2106
+ center[1],
2107
+ center[2]
2108
+ ],
2109
+ radius,
2110
+ ...normalCone === void 0 ? {} : { normalCone: {
2111
+ normal: [
2112
+ normalCone.normal[0],
2113
+ normalCone.normal[1],
2114
+ normalCone.normal[2]
2115
+ ],
2116
+ angleRad: normalCone.angleRad
2117
+ } }
2118
+ };
2119
+ }, (v) => v);
2120
+ }
2121
+ selectByCreaseAngle(mesh, seedTri, maxDihedralRad) {
2122
+ return this.#query("selectByCreaseAngle", () => ({
2123
+ mesh: this.#live(mesh).id,
2124
+ seedTri: checkU32Arg(seedTri, "seedTri"),
2125
+ maxDihedralRad
2126
+ }), (v) => v);
2127
+ }
2128
+ selectConnectedShell(mesh, seedTri) {
2129
+ return this.#query("selectConnectedShell", () => ({
2130
+ mesh: this.#live(mesh).id,
2131
+ seedTri: checkU32Arg(seedTri, "seedTri")
2132
+ }), (v) => v);
2133
+ }
2134
+ selectSmallFaceIslands(mesh, maxFaceCount, maxArea) {
2135
+ return this.#query("selectSmallFaceIslands", () => {
2136
+ const id = this.#live(mesh).id;
2137
+ const n = normalizeSelectSmallIslandsArgs(maxFaceCount, maxArea);
2138
+ return {
2139
+ mesh: id,
2140
+ maxFaceCount: n.maxFaceCount,
2141
+ ...maxArea === void 0 ? {} : { maxArea: n.maxArea }
2142
+ };
2143
+ }, (v) => v);
2144
+ }
2145
+ growFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
2146
+ return this.#query("growFaceSelection", () => {
2147
+ const id = this.#live(mesh).id;
2148
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
2149
+ return {
2150
+ mesh: id,
2151
+ selectedTris: n.selectedTris,
2152
+ rings: n.rings,
2153
+ adjacency
2154
+ };
2155
+ }, (v) => v);
2156
+ }
2157
+ shrinkFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
2158
+ return this.#query("shrinkFaceSelection", () => {
2159
+ const id = this.#live(mesh).id;
2160
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
2161
+ return {
2162
+ mesh: id,
2163
+ selectedTris: n.selectedTris,
2164
+ rings: n.rings,
2165
+ adjacency
2166
+ };
2167
+ }, (v) => v);
2168
+ }
2169
+ fillSelectionHoles(mesh, selectedTris, maxHoleTris) {
2170
+ return this.#query("fillSelectionHoles", () => ({
2171
+ mesh: this.#live(mesh).id,
2172
+ selectedTris: normalizeU32Selection(selectedTris),
2173
+ maxHoleTris: checkU32Arg(maxHoleTris, "maxHoleTris")
2174
+ }), (v) => v);
2175
+ }
2176
+ smoothSelectionBoundary(mesh, selectedTris, iterations = 1) {
2177
+ return this.#query("smoothSelectionBoundary", () => ({
2178
+ mesh: this.#live(mesh).id,
2179
+ selectedTris: normalizeU32Selection(selectedTris),
2180
+ iterations: checkU32Arg(iterations, "iterations")
2181
+ }), (v) => v);
2182
+ }
2183
+ faceSelectionToVertexMask(mesh, selectedTris) {
2184
+ return this.#query("faceSelectionToVertexMask", () => ({
2185
+ mesh: this.#live(mesh).id,
2186
+ selectedTris: normalizeU32Selection(selectedTris)
2187
+ }), (v) => v);
2188
+ }
2189
+ vertexMaskToFaceSelection(mesh, mask, threshold = .5, requireAllVertices = false) {
2190
+ return this.#query("vertexMaskToFaceSelection", () => {
2191
+ const id = this.#live(mesh).id;
2192
+ const n = normalizeVertexMaskSelectArgs(mask, threshold, requireAllVertices);
2193
+ return {
2194
+ mesh: id,
2195
+ mask: n.mask,
2196
+ threshold: n.threshold,
2197
+ requireAllVertices: n.requireAllVertices
2198
+ };
2199
+ }, (v) => v);
2200
+ }
2201
+ deleteSelectedFaces(mesh, selectedTris) {
2202
+ return this.#ask((rev, qid) => {
2203
+ const st = this.#live(mesh);
2204
+ const tris = normalizeU32Selection(selectedTris);
2205
+ this.#endDragOn(st);
2206
+ return {
2207
+ kind: "deleteSelectedFaces",
2208
+ rev,
2209
+ id: st.id,
2210
+ selectedTris: tris,
2211
+ qid
2212
+ };
2213
+ }, (v) => v);
2214
+ }
2215
+ /** Extrudes a face selection in the Worker, one undo step (see `Scene.extrudeFaces`). */
2216
+ extrudeFaces(mesh, triangles, options) {
2217
+ return this.#ask((rev, qid) => {
2218
+ const st = this.#live(mesh);
2219
+ const tris = normalizeU32Selection(triangles, "triangles");
2220
+ extrudeFacesArgs(options);
2221
+ const cloned = copyInput(options, "options");
2222
+ this.#endDragOn(st);
2223
+ return {
2224
+ kind: "extrudeFaces",
2225
+ rev,
2226
+ id: st.id,
2227
+ triangles: tris,
2228
+ options: cloned,
2229
+ qid
2230
+ };
2231
+ }, (v) => v);
2232
+ }
2233
+ /** Extrudes a mesh's boundary to a flat base in the Worker, one undo step (see `Scene.extrudeBase`). */
2234
+ extrudeBase(mesh, options) {
2235
+ return this.#ask((rev, qid) => {
2236
+ const st = this.#live(mesh);
2237
+ extrudeBaseArgs(options);
2238
+ const cloned = copyInput(options, "options");
2239
+ this.#endDragOn(st);
2240
+ return {
2241
+ kind: "extrudeBase",
2242
+ rev,
2243
+ id: st.id,
2244
+ options: cloned,
2245
+ qid
2246
+ };
2247
+ }, (v) => v);
2248
+ }
2249
+ extractSelectedFaces(mesh, selectedTris, options = {}) {
2250
+ let added;
2251
+ return this.#ask((rev, qid) => {
2252
+ const st = this.#live(mesh);
2253
+ const tris = normalizeU32Selection(selectedTris);
2254
+ const normals = checkBooleanArg(options?.normals, st.normalsOn, "options.normals");
2255
+ this.#endDragOn(st);
2256
+ added = this.#allocMeshState(st.origin, normals);
2257
+ return {
2258
+ kind: "extractSelectedFaces",
2259
+ rev,
2260
+ id: st.id,
2261
+ addedId: added.id,
2262
+ selectedTris: tris,
2263
+ normals,
2264
+ qid
2265
+ };
2266
+ }, () => added.handle).catch((e) => {
2267
+ this.#discardPlaceholder(added);
2268
+ throw e;
2269
+ });
2270
+ }
2271
+ splitSelectedFaces(mesh, selectedTris, options = {}) {
2272
+ let added;
2273
+ return this.#ask((rev, qid) => {
2274
+ const st = this.#live(mesh);
2275
+ const tris = normalizeU32Selection(selectedTris);
2276
+ const normals = checkBooleanArg(options?.normals, st.normalsOn, "options.normals");
2277
+ this.#endDragOn(st);
2278
+ added = this.#allocMeshState(st.origin, normals);
2279
+ return {
2280
+ kind: "splitSelectedFaces",
2281
+ rev,
2282
+ id: st.id,
2283
+ addedId: added.id,
2284
+ selectedTris: tris,
2285
+ normals,
2286
+ qid
2287
+ };
2288
+ }, (v) => {
2289
+ const r = v;
2290
+ return {
2291
+ detached: this.#handleOf(r.detached),
2292
+ removedTriangles: r.removedTriangles,
2293
+ removedVertices: r.removedVertices
2294
+ };
2295
+ }).catch((e) => {
2296
+ this.#discardPlaceholder(added);
2297
+ throw e;
2298
+ });
2299
+ }
2300
+ buildFfdLattice(mesh, dims, basis = "bernstein", padding = 0) {
2301
+ return this.#query("buildFfdLattice", () => {
2302
+ const id = this.#live(mesh).id;
2303
+ normalizeBuildFfdLatticeArgs(dims, basis, padding);
2304
+ return {
2305
+ mesh: id,
2306
+ dims: [
2307
+ dims[0],
2308
+ dims[1],
2309
+ dims[2]
2310
+ ],
2311
+ basis,
2312
+ padding
2313
+ };
2314
+ }, (v) => v);
2315
+ }
2316
+ applyFfd(mesh, options) {
2317
+ return this.#ask((rev, qid) => {
2318
+ const st = this.#live(mesh);
2319
+ normalizeFfdArgs(options);
2320
+ const cloned = copyInput(options, "options");
2321
+ this.#endDragOn(st);
2322
+ return {
2323
+ kind: "applyFfd",
2324
+ rev,
2325
+ id: st.id,
2326
+ options: cloned,
2327
+ qid
2328
+ };
2329
+ }, (v) => v);
2330
+ }
2331
+ applyArap(mesh, options) {
2332
+ return this.#ask((rev, qid) => {
2333
+ const st = this.#live(mesh);
2334
+ normalizeArapArgs(options);
2335
+ const cloned = copyInput(options, "options");
2336
+ this.#endDragOn(st);
2337
+ return {
2338
+ kind: "applyArap",
2339
+ rev,
2340
+ id: st.id,
2341
+ options: cloned,
2342
+ qid
2343
+ };
2344
+ }, (v) => v);
2345
+ }
2346
+ applyKelvinlet(mesh, options) {
2347
+ return this.#ask((rev, qid) => {
2348
+ const st = this.#live(mesh);
2349
+ normalizeKelvinletArgs(options);
2350
+ const cloned = copyInput(options, "options");
2351
+ this.#endDragOn(st);
2352
+ return {
2353
+ kind: "applyKelvinlet",
2354
+ rev,
2355
+ id: st.id,
2356
+ options: cloned,
2357
+ qid
2358
+ };
2359
+ }, (v) => v);
2360
+ }
2361
+ applyXpbd(mesh, options) {
2362
+ return this.#ask((rev, qid) => {
2363
+ const st = this.#live(mesh);
2364
+ normalizeXpbdArgs(options);
2365
+ const cloned = copyInput(options, "options");
2366
+ this.#endDragOn(st);
2367
+ return {
2368
+ kind: "applyXpbd",
2369
+ rev,
2370
+ id: st.id,
2371
+ options: cloned,
2372
+ qid
2373
+ };
2374
+ }, (v) => v);
2375
+ }
2376
+ setDefaultCollisionRule(rule) {
2377
+ this.#alive();
2378
+ const normalized = normalizeCollisionRule(rule);
2379
+ this.#defaultCollisionRule = normalized;
2380
+ this.#push({
2381
+ kind: "setDefaultCollisionRule",
2382
+ rev: ++this.#rev,
2383
+ rule: { ...normalized }
2384
+ });
2385
+ }
2386
+ defaultCollisionRule() {
2387
+ this.#alive();
2388
+ return { ...this.#defaultCollisionRule };
2389
+ }
2390
+ setCollisionRule(a, b, rule) {
2391
+ const sa = this.#live(a);
2392
+ const sb = this.#live(b);
2393
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2394
+ const normalized = normalizeCollisionRule(rule);
2395
+ const rev = ++this.#rev;
2396
+ this.#collisionRules.set(collisionPairKey(sa.id, sb.id), {
2397
+ a: sa,
2398
+ b: sb,
2399
+ rule: normalized,
2400
+ rev
2401
+ });
2402
+ this.#push({
2403
+ kind: "setCollisionRule",
2404
+ rev,
2405
+ a: sa.id,
2406
+ b: sb.id,
2407
+ rule: { ...normalized }
2408
+ });
2409
+ }
2410
+ clearCollisionRule(a, b) {
2411
+ const sa = this.#live(a);
2412
+ const sb = this.#live(b);
2413
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2414
+ const existed = this.#collisionRules.delete(collisionPairKey(sa.id, sb.id));
2415
+ this.#push({
2416
+ kind: "clearCollisionRule",
2417
+ rev: ++this.#rev,
2418
+ a: sa.id,
2419
+ b: sb.id
2420
+ });
2421
+ return existed;
2422
+ }
2423
+ collisionRule(a, b) {
2424
+ const sa = this.#live(a);
2425
+ const sb = this.#live(b);
2426
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2427
+ const entry = this.#collisionRules.get(collisionPairKey(sa.id, sb.id));
2428
+ return entry !== void 0 ? { ...entry.rule } : { ...this.#defaultCollisionRule };
2429
+ }
2430
+ hasActiveCollisionResponse(mesh) {
2431
+ const st = this.#live(mesh);
2432
+ if (this.#defaultCollisionRule.mode !== "passThrough") return true;
2433
+ for (const entry of this.#collisionRules.values()) if ((entry.a === st || entry.b === st) && !entry.a.removed && !entry.b.removed && entry.rule.mode !== "passThrough") return true;
2434
+ return false;
2435
+ }
2436
+ moveWithCollision(mesh, placement, isRelease = false) {
2437
+ return this.#ask((rev, qid) => {
2438
+ const st = this.#live(mesh);
2439
+ const norm = normalizePlacementInputArgs(placement);
2440
+ const release = checkBooleanArg(isRelease, false, "isRelease");
2441
+ this.#endDragOn(st);
2442
+ const wirePlacement = {
2443
+ rotation: Array.from(norm.rotation),
2444
+ translation: [
2445
+ norm.translation[0],
2446
+ norm.translation[1],
2447
+ norm.translation[2]
2448
+ ],
2449
+ ...norm.scale === void 0 ? {} : { scale: [
2450
+ norm.scale[0],
2451
+ norm.scale[1],
2452
+ norm.scale[2]
2453
+ ] }
2454
+ };
2455
+ return {
2456
+ kind: "moveWithCollision",
2457
+ rev,
2458
+ id: st.id,
2459
+ placement: wirePlacement,
2460
+ isRelease: release,
2461
+ qid
2462
+ };
2463
+ }, (v) => this.#mapCollisionReport(v));
2464
+ }
2465
+ commitCollisionInteraction(mesh) {
2466
+ return this.#ask((rev, qid) => {
2467
+ const st = this.#live(mesh);
2468
+ this.#endDragOn(st);
2469
+ return {
2470
+ kind: "commitCollisionInteraction",
2471
+ rev,
2472
+ id: st.id,
2473
+ qid
2474
+ };
2475
+ }, (v) => this.#mapCollisionReport(v));
2476
+ }
2477
+ fitPrimitive(mesh, options = {}) {
2478
+ return this.#query("fitPrimitive", () => {
2479
+ const id = this.#live(mesh).id;
2480
+ normalizeFitPrimitiveArgs(options);
2481
+ return {
2482
+ mesh: id,
2483
+ options: copyInput(options, "options")
2484
+ };
2485
+ }, (v) => v);
2486
+ }
2487
+ alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin) {
2488
+ return this.#ask((rev, qid) => {
2489
+ const st = this.#live(mesh);
2490
+ const n = normalizeAlignToPrimitiveArgs(primitive, targetAxis, targetOrigin);
2491
+ this.#endDragOn(st);
2492
+ return {
2493
+ kind: "alignToFittedPrimitive",
2494
+ rev,
2495
+ id: st.id,
2496
+ primitive: copyInput(primitive, "primitive"),
2497
+ targetAxis: [
2498
+ n.targetAxis[0],
2499
+ n.targetAxis[1],
2500
+ n.targetAxis[2]
2501
+ ],
2502
+ targetOrigin: [
2503
+ n.targetOrigin[0],
2504
+ n.targetOrigin[1],
2505
+ n.targetOrigin[2]
2506
+ ],
2507
+ qid
2508
+ };
2509
+ }, (v) => v);
2510
+ }
2511
+ sliceContours(mesh, origin, normal) {
2512
+ return this.#query("sliceContours", () => {
2513
+ const id = this.#live(mesh).id;
2514
+ const n = normalizeSliceContoursArgs(origin, normal);
2515
+ return {
2516
+ mesh: id,
2517
+ origin: [
2518
+ n.origin[0],
2519
+ n.origin[1],
2520
+ n.origin[2]
2521
+ ],
2522
+ normal: [
2523
+ n.normal[0],
2524
+ n.normal[1],
2525
+ n.normal[2]
2526
+ ]
2527
+ };
2528
+ }, (v) => v);
2529
+ }
2530
+ sliceContourStack(mesh, origin, normal, spacing, count) {
2531
+ return this.#query("sliceContourStack", () => {
2532
+ const id = this.#live(mesh).id;
2533
+ const n = normalizeSliceContourStackArgs(origin, normal, spacing, count);
2534
+ return {
2535
+ mesh: id,
2536
+ origin: [
2537
+ n.origin[0],
2538
+ n.origin[1],
2539
+ n.origin[2]
2540
+ ],
2541
+ normal: [
2542
+ n.normal[0],
2543
+ n.normal[1],
2544
+ n.normal[2]
2545
+ ],
2546
+ spacing: n.spacing,
2547
+ count: n.count
2548
+ };
2549
+ }, (v) => v);
2550
+ }
2551
+ /**
2552
+ * Adds the convex hull of `meshes` (one mesh or several) in the Worker as a
2553
+ * new mesh, one undo step (see `Scene.convexHull`).
2554
+ */
2555
+ convexHull(meshes, options) {
2556
+ let added;
2557
+ return this.#ask((rev, qid) => {
2558
+ const states = hullMeshList(meshes).map((m) => this.#live(m));
2559
+ const normals = hullNormals(options);
2560
+ added = this.#allocMeshState([
2561
+ 0,
2562
+ 0,
2563
+ 0
2564
+ ], normals);
2565
+ return {
2566
+ kind: "convexHull",
2567
+ rev,
2568
+ addedId: added.id,
2569
+ meshes: states.map((st) => st.id),
2570
+ normals,
2571
+ qid
2572
+ };
2573
+ }, (v) => ({
2574
+ mesh: added.handle,
2575
+ ...v
2576
+ })).catch((e) => {
2577
+ this.#discardPlaceholder(added);
2578
+ throw e;
2579
+ });
2580
+ }
2581
+ /**
2582
+ * Adds the convex hull of world `points` in the Worker as a new mesh, one
2583
+ * undo step (see `Scene.convexHullOfPoints`). The points are copied.
2584
+ */
2585
+ convexHullOfPoints(points, options) {
2586
+ let added;
2587
+ return this.#ask((rev, qid) => {
2588
+ this.#alive();
2589
+ const buf = hullPointsBuffer(points);
2590
+ const normals = hullNormals(options);
2591
+ added = this.#allocMeshState([
2592
+ 0,
2593
+ 0,
2594
+ 0
2595
+ ], normals);
2596
+ return {
2597
+ kind: "convexHullPoints",
2598
+ rev,
2599
+ addedId: added.id,
2600
+ points: buf,
2601
+ normals,
2602
+ qid
2603
+ };
2604
+ }, (v) => ({
2605
+ mesh: added.handle,
2606
+ ...v
2607
+ })).catch((e) => {
2608
+ this.#discardPlaceholder(added);
2609
+ throw e;
2610
+ });
2611
+ }
2612
+ /** Fits a height map's frame to `meshes` (one mesh or several) in the Worker (see `Scene.heightMapFrame`). */
2613
+ heightMapFrame(meshes, options) {
2614
+ return this.#query("heightMapFrame", () => ({
2615
+ meshes: heightMapMeshList(meshes).map((m) => this.#live(m).id),
2616
+ options: encodeHeightMapOptions(options)
2617
+ }), (v) => v);
2618
+ }
2619
+ /**
2620
+ * An orthographic depth image of `meshes` (one mesh or several), sampled in
2621
+ * the Worker and transferred (see `Scene.heightMap`). Asking for bands of
2622
+ * `rows` lets other requests run in between them.
2623
+ */
2624
+ heightMap(meshes, frame, rows) {
2625
+ return this.#query("heightMap", () => ({
2626
+ meshes: heightMapMeshList(meshes).map((m) => this.#live(m).id),
2627
+ ...isHeightMapFrame(frame) ? { frame: encodeHeightMapFrame(frame) } : { options: encodeHeightMapOptions(frame) },
2628
+ ...rows === void 0 ? {} : { rows: [rows[0], rows[1]] }
2629
+ }), (v) => v);
2630
+ }
2631
+ /**
2632
+ * Adds the relief of a grid of heights in the Worker as a new mesh, one undo
2633
+ * step (see `Scene.addHeightfield`). The heights are copied here and
2634
+ * transferred; the mesh itself comes back only as the mirror's buffers.
2635
+ */
2636
+ addHeightfield(field, options) {
2637
+ let added;
2638
+ return this.#ask((rev, qid) => {
2639
+ this.#alive();
2640
+ const checked = checkHeightfield(field);
2641
+ const placement = checkHeightfieldPlacement(options);
2642
+ added = this.#allocMeshState([
2643
+ 0,
2644
+ 0,
2645
+ 0
2646
+ ], placement.normals);
2647
+ const copy = {
2648
+ ...checked,
2649
+ heights: checked.heights.slice()
2650
+ };
2651
+ return {
2652
+ kind: "addHeightfield",
2653
+ rev,
2654
+ addedId: added.id,
2655
+ field: copy,
2656
+ placement,
2657
+ qid
2658
+ };
2659
+ }, (v) => ({
2660
+ mesh: added.handle,
2661
+ ...v
2662
+ })).catch((e) => {
2663
+ this.#discardPlaceholder(added);
2664
+ throw e;
2665
+ });
2666
+ }
2667
+ /** Smooths noise out of `mesh` in the Worker, one undo step (see `Scene.denoise`). */
2668
+ denoise(mesh, options) {
2669
+ return this.#ask((rev, qid) => {
2670
+ const st = this.#live(mesh);
2671
+ const checked = checkDenoiseOptions(options);
2672
+ this.#endDragOn(st);
2673
+ return {
2674
+ kind: "denoise",
2675
+ rev,
2676
+ id: st.id,
2677
+ options: checked,
2678
+ qid
2679
+ };
2680
+ }, (v) => v);
2681
+ }
2682
+ /** Flips `mesh`'s edges towards Delaunay in the Worker, one undo step (see `Scene.delaunayFlips`). */
2683
+ delaunayFlips(mesh, options) {
2684
+ return this.#ask((rev, qid) => {
2685
+ const st = this.#live(mesh);
2686
+ const checked = checkDelaunayFlipOptions(options);
2687
+ this.#endDragOn(st);
2688
+ return {
2689
+ kind: "delaunayFlips",
2690
+ rev,
2691
+ id: st.id,
2692
+ options: checked,
2693
+ qid
2694
+ };
2695
+ }, (v) => v);
2696
+ }
2697
+ /**
2698
+ * Plans the voxel grid of {@link WorkerScene.wrap} for the same meshes and
2699
+ * options without running it (see `Scene.wrapPlan`).
2700
+ */
2701
+ wrapPlan(meshes, options) {
2702
+ return this.#query("wrapPlan", () => ({
2703
+ meshes: wrapMeshList(meshes).map((m) => this.#live(m).id),
2704
+ options: checkWrapOptions(options)
2705
+ }), (v) => v);
2706
+ }
2707
+ /**
2708
+ * Wraps `meshes` (one mesh or several) in one closed, manifold envelope in
2709
+ * the Worker, added as a new mesh, one undo step (see `Scene.wrap`). The
2710
+ * page stays live while it runs.
2711
+ */
2712
+ wrap(meshes, options) {
2713
+ let added;
2714
+ return this.#ask((rev, qid) => {
2715
+ const states = wrapMeshList(meshes).map((m) => this.#live(m));
2716
+ const checked = checkWrapOptions(options);
2717
+ added = this.#allocMeshState([
2718
+ 0,
2719
+ 0,
2720
+ 0
2721
+ ], checked.normals);
2722
+ return {
2723
+ kind: "wrap",
2724
+ rev,
2725
+ addedId: added.id,
2726
+ meshes: states.map((st) => st.id),
2727
+ options: checked,
2728
+ qid
2729
+ };
2730
+ }, (v) => ({
2731
+ mesh: added.handle,
2732
+ ...v
2733
+ })).catch((e) => {
2734
+ this.#discardPlaceholder(added);
2735
+ throw e;
2736
+ });
2737
+ }
2738
+ reconstructPointCloud(cloud, options = {}) {
2739
+ let added;
2740
+ return this.#ask((rev, qid) => {
2741
+ this.#alive();
2742
+ const buf = cloudBuffer(cloud).slice();
2743
+ const origin = cloudOrigin(cloud);
2744
+ normalizeReconstructArgs(options);
2745
+ const normals = checkBooleanArg(options?.normals, true, "options.normals");
2746
+ added = this.#allocMeshState(origin ?? [
2747
+ 0,
2748
+ 0,
2749
+ 0
2750
+ ], normals);
2751
+ return {
2752
+ kind: "reconstructPointCloud",
2753
+ rev,
2754
+ addedId: added.id,
2755
+ cloud: buf,
2756
+ ...origin === void 0 ? {} : { origin },
2757
+ options: copyInput(options, "options"),
2758
+ qid
2759
+ };
2760
+ }, () => added.handle).catch((e) => {
2761
+ this.#discardPlaceholder(added);
2762
+ throw e;
2763
+ });
2764
+ }
2765
+ hollowMesh(mesh, options) {
2766
+ return this.#ask((rev, qid) => {
2767
+ const st = this.#live(mesh);
2768
+ normalizeHollowArgs(options);
2769
+ const cloned = copyInput(options, "options");
2770
+ this.#endDragOn(st);
2771
+ return {
2772
+ kind: "hollowMesh",
2773
+ rev,
2774
+ id: st.id,
2775
+ options: cloned,
2776
+ qid
2777
+ };
2778
+ }, (v) => v);
2779
+ }
2780
+ /**
2781
+ * Plans the voxel grid of {@link WorkerScene.latticeFill} for the same mesh
2782
+ * and options without running it (see `Scene.latticePlan`).
2783
+ */
2784
+ latticePlan(mesh, options) {
2785
+ return this.#query("latticePlan", () => ({
2786
+ mesh: this.#live(mesh).id,
2787
+ options: checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS)
2788
+ }), (v) => v);
2789
+ }
2790
+ /**
2791
+ * Fills the inside of a closed mesh, or the cavity of a hollowed one, with a
2792
+ * lattice in the Worker, one undo step (see `Scene.latticeFill`). The page
2793
+ * stays live while it runs.
2794
+ */
2795
+ latticeFill(mesh, options) {
2796
+ return this.#ask((rev, qid) => {
2797
+ const st = this.#live(mesh);
2798
+ const checked = checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS);
2799
+ this.#endDragOn(st);
2800
+ return {
2801
+ kind: "latticeFill",
2802
+ rev,
2803
+ id: st.id,
2804
+ options: checked,
2805
+ qid
2806
+ };
2807
+ }, (v) => v);
2808
+ }
2809
+ /**
2810
+ * The walls of a lattice on a small grid, built in the Worker without
2811
+ * changing the mesh (see `Scene.latticePreview`).
2812
+ */
2813
+ latticePreview(mesh, options) {
2814
+ return this.#query("latticePreview", () => ({
2815
+ mesh: this.#live(mesh).id,
2816
+ options: checkLatticeOptions(options, DEFAULT_LATTICE_PREVIEW_VOXELS)
2817
+ }), (v) => v);
2818
+ }
2819
+ punchDrainHole(mesh, options) {
2820
+ let plug;
2821
+ return this.#ask((rev, qid) => {
2822
+ const st = this.#live(mesh);
2823
+ const n = normalizeDrainHoleArgs(options);
2824
+ const plugNormals = checkBooleanArg(n.plugNormals, st.normalsOn, "options.plugNormals");
2825
+ const cloned = copyInput(options, "options");
2826
+ this.#endDragOn(st);
2827
+ plug = n.generatePlug ? this.#allocMeshState(st.origin, plugNormals) : void 0;
2828
+ return {
2829
+ kind: "punchDrainHole",
2830
+ rev,
2831
+ id: st.id,
2832
+ ...plug === void 0 ? {} : { plugId: plug.id },
2833
+ options: cloned,
2834
+ qid
2835
+ };
2836
+ }, (v) => {
2837
+ const r = v;
2838
+ if (plug !== void 0 && !r.plugs.includes(plug.id)) this.#discardPlaceholder(plug);
2839
+ return {
2840
+ ...r,
2841
+ plugs: r.plugs.map((pid) => this.#handleOf(pid))
2842
+ };
2843
+ }).catch((e) => {
2844
+ this.#discardPlaceholder(plug);
2845
+ throw e;
2846
+ });
2847
+ }
2848
+ placeMesh(target, stamp, options) {
2849
+ let added;
2850
+ return this.#ask((rev, qid) => {
2851
+ const stTarget = this.#live(target);
2852
+ const stStamp = this.#live(stamp);
2853
+ const n = normalizePlaceMeshArgs(options);
2854
+ const normals = checkBooleanArg(n.normals, stStamp.normalsOn, "options.normals");
2855
+ const cloned = copyInput(options, "options");
2856
+ this.#endDragOn(stTarget, stStamp);
2857
+ added = (options.mode ?? "keepSeparate") === "keepSeparate" ? this.#allocMeshState(stTarget.origin, normals) : void 0;
2858
+ return {
2859
+ kind: "placeMesh",
2860
+ rev,
2861
+ target: stTarget.id,
2862
+ stamp: stStamp.id,
2863
+ ...added === void 0 ? {} : { addedId: added.id },
2864
+ options: cloned,
2865
+ qid
2866
+ };
2867
+ }, (v) => {
2868
+ const r = v;
2869
+ if (added !== void 0 && r.added !== added.id) this.#discardPlaceholder(added);
2870
+ return {
2871
+ ...r,
2872
+ added: r.added === null ? null : this.#handleOf(r.added)
2873
+ };
2874
+ }).catch((e) => {
2875
+ this.#discardPlaceholder(added);
2876
+ throw e;
2877
+ });
2878
+ }
2879
+ #mapCollisionReport(r) {
2880
+ return {
2881
+ ...r,
2882
+ activePairs: r.activePairs.map((p) => ({
2883
+ ...p,
2884
+ other: this.#handleOf(p.other)
2885
+ })),
2886
+ modifiedMeshes: r.modifiedMeshes.map((id) => this.#handleOf(id))
2887
+ };
2888
+ }
2889
+ /** Undoes the latest step; an active drag is ended first. */
2890
+ undo() {
2891
+ this.#alive();
2892
+ this.#drag?.end();
2893
+ this.#stepDepth = 0;
2894
+ this.#forgetRequested();
2895
+ this.#push({
2896
+ kind: "undo",
2897
+ rev: ++this.#rev
2898
+ });
2899
+ this.#scheduleFlush();
2900
+ }
2901
+ /** Redoes the latest undone step; an active drag is ended first. */
2902
+ redo() {
2903
+ this.#alive();
2904
+ this.#drag?.end();
2905
+ this.#stepDepth = 0;
2906
+ this.#forgetRequested();
2907
+ this.#push({
2908
+ kind: "redo",
2909
+ rev: ++this.#rev
2910
+ });
2911
+ this.#scheduleFlush();
2912
+ }
2913
+ /** Closes an open step and drops every undo and redo step. */
2914
+ clearHistory() {
2915
+ this.#alive();
2916
+ this.#drag?.end();
2917
+ this.#stepDepth = 0;
2918
+ this.#forgetRequested();
2919
+ this.#push({
2920
+ kind: "clearHistory",
2921
+ rev: ++this.#rev
2922
+ });
2923
+ this.#scheduleFlush();
2924
+ }
2925
+ /**
2926
+ * Records an entry of the application's own in the history, after the
2927
+ * requests before it; see `Scene.recordEntry`. Its functions run here, on
2928
+ * this thread, as the result that undid, redid or dropped it is applied:
2929
+ * after the mirrors and before the promises the result settles and the
2930
+ * change records of the next {@link WorkerScene.commitFrame}.
2931
+ *
2932
+ * The history's order is that of the calls, whatever is in flight: an
2933
+ * `undo()` undoes what was recorded last when it was called, and the engine
2934
+ * says what that was. An entry recorded while an `undo()` or `redo()` is in
2935
+ * flight comes after it, and the undone entries' functions then run around
2936
+ * it (its `undo` before them, its `redo` after), so that every function
2937
+ * finds the application as the history has it. An entry that could not be
2938
+ * recorded is dropped, and so is every entry by a
2939
+ * {@link WorkerScene.restart}, which clears the history.
2940
+ *
2941
+ * @throws `INVALID_ARGUMENT` for an entry without `undo` and `redo`, or with
2942
+ * bytes below 0.
2943
+ */
2944
+ recordEntry(entry) {
2945
+ this.#alive();
2946
+ const { bytes, coalesce } = checkHistoryEntry(entry);
2947
+ const rev = ++this.#rev;
2948
+ const id = this.#entries.add(entry, rev);
2949
+ this.#push({
2950
+ kind: "entry",
2951
+ rev,
2952
+ id,
2953
+ bytes,
2954
+ ...coalesce === void 0 ? {} : { coalesce }
2955
+ });
2956
+ this.#scheduleFlush();
2957
+ }
2958
+ /** The most bytes the history may hold, as last set here. */
2959
+ get historyBudget() {
2960
+ return this.#init.historyBudget ?? 268435456;
2961
+ }
2962
+ /**
2963
+ * Changes the most bytes the history may hold, after the requests before
2964
+ * it; see `Scene.setHistoryBudget`. A {@link WorkerScene.restart} keeps it.
2965
+ *
2966
+ * @throws `INVALID_ARGUMENT` for anything but a number, 0 or more.
2967
+ */
2968
+ setHistoryBudget(bytes) {
2969
+ this.#alive();
2970
+ const budget = checkHistoryBudget(bytes);
2971
+ this.#init = {
2972
+ ...this.#init,
2973
+ historyBudget: budget
2974
+ };
2975
+ this.#push({
2976
+ kind: "historyBudget",
2977
+ rev: ++this.#rev,
2978
+ bytes: budget
2979
+ });
2980
+ this.#scheduleFlush();
2981
+ }
2982
+ /** The bytes the history holds, as of the latest result. */
2983
+ get historyBytes() {
2984
+ return this.#historyBytes;
2985
+ }
2986
+ /**
2987
+ * Registers a listener called with each step the history could not keep
2988
+ * (an action that is permanent, or one that cannot be redone), as its
2989
+ * result is applied, before the promises it settles; see
2990
+ * `Scene.onPermanent`. Returns the function that removes it.
2991
+ */
2992
+ onPermanent(listener) {
2993
+ this.#permanentListeners.add(listener);
2994
+ return () => {
2995
+ this.#permanentListeners.delete(listener);
2996
+ };
2997
+ }
2998
+ /**
2999
+ * Opens a history step, or one more nesting level of the open one. Edits,
3000
+ * repairs, and placement changes until the matching {@link WorkerScene.endStep}
3001
+ * are coalesced into a single undo entry.
3002
+ */
3003
+ beginStep() {
3004
+ this.#alive();
3005
+ this.#stepDepth++;
3006
+ this.#push({
3007
+ kind: "step",
3008
+ rev: ++this.#rev,
3009
+ phase: "begin"
3010
+ });
3011
+ this.#scheduleFlush();
3012
+ }
3013
+ /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
3014
+ endStep() {
3015
+ this.#alive();
3016
+ if (this.#stepDepth === 0) throw new FastMeshError("STEP_NOT_OPEN", "no history step is open");
3017
+ const closingDrag = this.#drag !== void 0 && this.#stepDepth <= this.#drag.stepDepth;
3018
+ const rev = this.#push({
3019
+ kind: "step",
3020
+ rev: ++this.#rev,
3021
+ phase: "end"
3022
+ });
3023
+ this.#stepDepth--;
3024
+ if (closingDrag && this.#drag !== void 0) this.#drag.abandon(rev, false);
3025
+ this.#scheduleFlush();
3026
+ }
3027
+ /** Reverts and discards the open step, however deeply nested. Throws `STEP_NOT_OPEN` when none is open. */
3028
+ cancelStep() {
3029
+ this.#alive();
3030
+ if (this.#stepDepth === 0) throw new FastMeshError("STEP_NOT_OPEN", "no history step is open");
3031
+ const rev = this.#push({
3032
+ kind: "step",
3033
+ rev: ++this.#rev,
3034
+ phase: "cancel"
3035
+ });
3036
+ this.#stepDepth = 0;
3037
+ this.#drag?.abandon(rev, true);
3038
+ this.#forgetRequested();
3039
+ this.#scheduleFlush();
3040
+ }
3041
+ /**
3042
+ * An undo or redo is queued: requested placements and the poses held for
3043
+ * ended drags no longer say where the meshes will be. The engine's pose is
3044
+ * shown (and a new drag starts from it) until the results arrive.
3045
+ */
3046
+ #forgetRequested() {
3047
+ for (const st of this.#meshes.values()) {
3048
+ st.requested = void 0;
3049
+ if (st.local !== void 0 && st.localUntil !== Number.POSITIVE_INFINITY) {
3050
+ if (!samePose(st.local, st.pose)) this.#optimistic.add(st);
3051
+ st.local = void 0;
3052
+ st.localUntil = 0;
3053
+ }
3054
+ }
3055
+ }
3056
+ /**
3057
+ * The threads the engine computes with: more than 1 when the threaded
3058
+ * engine runs (see {@link WorkerSceneOptions.threads}), 1 when
3059
+ * single-threaded. As of the current Worker's start (1 until it is ready).
3060
+ */
3061
+ get threads() {
3062
+ return this.#threads;
3063
+ }
3064
+ /** Whether there is a step to undo, as of the latest result. */
3065
+ get canUndo() {
3066
+ return this.#history.canUndo;
1513
3067
  }
1514
3068
  /** Whether there is a step to redo, as of the latest result. */
1515
3069
  get canRedo() {
1516
3070
  return this.#history.canRedo;
1517
3071
  }
1518
3072
  /**
3073
+ * Generates a primitive shape in the Worker, as the standalone
3074
+ * `generatePrimitive` does on a thread with the module initialised; the
3075
+ * buffers are transferred back, and the scene is not touched. The shape is
3076
+ * checked by type here, its ranges in the Worker.
3077
+ *
3078
+ * @throws (rejects) `INVALID_ARGUMENT` for an unknown kind or a parameter
3079
+ * out of range; `OUT_OF_MEMORY` when the buffers cannot be allocated.
3080
+ */
3081
+ generatePrimitive(shape) {
3082
+ return this.#query("generatePrimitive", () => encodePrimitive(shape), (v) => v);
3083
+ }
3084
+ /**
3085
+ * Generates the relief of a grid of heights in the Worker, as the standalone
3086
+ * `generateHeightfield` does on a thread with the module initialised; the
3087
+ * buffers are transferred back, and the scene is not touched.
3088
+ *
3089
+ * @throws (rejects) `INVALID_ARGUMENT` for a grid out of range;
3090
+ * `OUT_OF_MEMORY` when the buffers cannot be allocated.
3091
+ */
3092
+ generateHeightfield(field) {
3093
+ return this.#query("generateHeightfield", () => checkHeightfield(field), (v) => v);
3094
+ }
3095
+ /**
1519
3096
  * Adds a signed distance field; see `Scene.addDistanceField`.
1520
3097
  *
1521
3098
  * @deprecated Use `workerScene.inspect.addDistanceField()` instead.
@@ -1851,6 +3428,13 @@ var WorkerScene = class WorkerScene {
1851
3428
  }), (v) => v);
1852
3429
  }
1853
3430
  /**
3431
+ * The live triangle slots of `mesh` that intersect or touch another of its
3432
+ * own triangles, ascending; see `Scene.selfIntersectingTriangles`.
3433
+ */
3434
+ selfIntersectingTriangles(mesh) {
3435
+ return this.#query("selfIntersectingTriangles", () => ({ mesh: this.#live(mesh).id }), (v) => v);
3436
+ }
3437
+ /**
1854
3438
  * Every mesh pair (or every pair of `pairs`) within `margin`; see `Scene.findContacts`.
1855
3439
  *
1856
3440
  * @deprecated Use `workerScene.inspect.findContacts()` instead.
@@ -1918,19 +3502,7 @@ var WorkerScene = class WorkerScene {
1918
3502
  const st = this.#byMesh.get(c.mesh);
1919
3503
  if (st === void 0) continue;
1920
3504
  st.gone = true;
1921
- if (st.removed) {
1922
- this.#meshes.delete(st.id);
1923
- this.#byMesh.delete(st.handle);
1924
- this.#tombstones.add(st.handle);
1925
- const id = st.id;
1926
- this.#forgetKeys([
1927
- `mesh:${id}`,
1928
- `placement:${id}`,
1929
- `edit:${id}`,
1930
- `display:${id}`
1931
- ], []);
1932
- this.#statusChanged();
1933
- }
3505
+ if (st.removed && !st.parked) this.#forgetMesh(st);
1934
3506
  }
1935
3507
  let failure;
1936
3508
  for (const listener of [...this.#listeners]) try {
@@ -1993,7 +3565,8 @@ var WorkerScene = class WorkerScene {
1993
3565
  * - fields, colourings and sections as last requested (removed ones are
1994
3566
  * not re-created).
1995
3567
  *
1996
- * History is cleared (`canUndo`/`canRedo` are false). The replay is sent
3568
+ * History is cleared (`canUndo`/`canRedo` are false), and the meshes it
3569
+ * could have brought back are gone for good. The replay is sent
1997
3570
  * at once, not with the next frame. Every replayed key is `"computing"`
1998
3571
  * until the replay's results arrive, and so is the key of every pending
1999
3572
  * declarative request (placement, drag, colouring, field, section), also
@@ -2123,6 +3696,7 @@ var WorkerScene = class WorkerScene {
2123
3696
  this.#drag.active = false;
2124
3697
  this.#drag = void 0;
2125
3698
  }
3699
+ this.#stepDepth = 0;
2126
3700
  for (const st of this.#meshes.values()) {
2127
3701
  if (!samePose(this.#shown(st), poses.get(st))) this.#optimistic.add(st);
2128
3702
  st.local = void 0;
@@ -2163,6 +3737,8 @@ var WorkerScene = class WorkerScene {
2163
3737
  canUndo: false,
2164
3738
  canRedo: false
2165
3739
  };
3740
+ this.#historyBytes = 0;
3741
+ this.#entries.dropAll();
2166
3742
  this.#statusChanged();
2167
3743
  const first = this.#rev + 1;
2168
3744
  if (this.#values) this.#push({
@@ -2170,6 +3746,11 @@ var WorkerScene = class WorkerScene {
2170
3746
  rev: ++this.#rev
2171
3747
  });
2172
3748
  const replayed = /* @__PURE__ */ new Set();
3749
+ for (const st of [...this.#meshes.values()].filter((m) => m.parked)) {
3750
+ st.parked = false;
3751
+ this.#dropFieldsOf(st, this.#rev);
3752
+ if (st.gone) this.#forgetMesh(st);
3753
+ }
2173
3754
  for (const st of this.#meshes.values()) {
2174
3755
  if (st.removed) {
2175
3756
  if (!st.gone) {
@@ -2292,6 +3873,19 @@ var WorkerScene = class WorkerScene {
2292
3873
  desc
2293
3874
  });
2294
3875
  }
3876
+ this.#push({
3877
+ kind: "setDefaultCollisionRule",
3878
+ rev: ++this.#rev,
3879
+ rule: { ...this.#defaultCollisionRule }
3880
+ });
3881
+ for (const [key, entry] of [...this.#collisionRules.entries()]) if (!entry.a.removed && !entry.b.removed && replayed.has(entry.a.id) && replayed.has(entry.b.id)) this.#push({
3882
+ kind: "setCollisionRule",
3883
+ rev: ++this.#rev,
3884
+ a: entry.a.id,
3885
+ b: entry.b.id,
3886
+ rule: { ...entry.rule }
3887
+ });
3888
+ else if (!replayed.has(entry.a.id) || !replayed.has(entry.b.id)) this.#collisionRules.delete(key);
2295
3889
  const rev = this.#push({
2296
3890
  kind: "clearHistory",
2297
3891
  rev: ++this.#rev
@@ -2325,6 +3919,7 @@ var WorkerScene = class WorkerScene {
2325
3919
  mesh: st.handle,
2326
3920
  added: false,
2327
3921
  removed: true,
3922
+ ...st.parked ? { restorable: true } : {},
2328
3923
  placementChanged: false,
2329
3924
  capacityChanged: false,
2330
3925
  positions: [],
@@ -2352,6 +3947,7 @@ var WorkerScene = class WorkerScene {
2352
3947
  this.#drag.active = false;
2353
3948
  this.#drag = void 0;
2354
3949
  }
3950
+ this.#stepDepth = 0;
2355
3951
  this.#worker.terminate();
2356
3952
  this.#unwatch();
2357
3953
  this.#dropHandoff();
@@ -2365,6 +3961,7 @@ var WorkerScene = class WorkerScene {
2365
3961
  this.#batchDone.clear();
2366
3962
  this.#queue = [];
2367
3963
  this.#inflight.length = 0;
3964
+ this.#entries.dropAll();
2368
3965
  }
2369
3966
  static {
2370
3967
  createScene = (make, options) => {
@@ -2378,6 +3975,13 @@ var WorkerScene = class WorkerScene {
2378
3975
  scene.#statusSinks.delete(sink);
2379
3976
  };
2380
3977
  };
3978
+ fieldTargetsOf = (scene, field) => {
3979
+ const st = scene.#byField.get(field);
3980
+ if (st === void 0 || st.removed) return null;
3981
+ return st.desc.to.flatMap((id) => scene.#meshes.get(id)?.handle ?? []);
3982
+ };
3983
+ sectionMeshesOf = (scene, section) => scene.#bySection.get(section)?.meshes.map((m) => m.handle) ?? [];
3984
+ presenceVersionOf = (scene) => scene.#presenceVersion;
2381
3985
  }
2382
3986
  };
2383
3987
  /**
@@ -2400,6 +4004,25 @@ function watchStatusKeys(scene, sink) {
2400
4004
  return watchStatusKeysOf(scene, sink);
2401
4005
  }
2402
4006
  /**
4007
+ * Internal, not exported from `fast-mesh-wasm/worker`: the targets a field is
4008
+ * left with as of the latest result, or `null` for one that is gone.
4009
+ */
4010
+ function fieldTargets(scene, field) {
4011
+ return fieldTargetsOf(scene, field);
4012
+ }
4013
+ /** Internal, not exported from `fast-mesh-wasm/worker`: the meshes a section cuts, as of the latest result. */
4014
+ function sectionMeshes(scene, section) {
4015
+ return sectionMeshesOf(scene, section);
4016
+ }
4017
+ /**
4018
+ * Internal, not exported from `fast-mesh-wasm/worker`: goes up with every
4019
+ * result that says where undoable adds and removals moved meshes. `onStatus`
4020
+ * listeners are called for it.
4021
+ */
4022
+ function presenceVersion(scene) {
4023
+ return presenceVersionOf(scene);
4024
+ }
4025
+ /**
2403
4026
  * A deep copy of a caller's request input (edit ops, repair ops), taken at
2404
4027
  * call time so later changes to it do not leak into the request.
2405
4028
  */
@@ -2506,6 +4129,10 @@ function merge(a, b) {
2506
4129
  };
2507
4130
  if (b.added) return {
2508
4131
  ...b,
4132
+ ...a.removed ? {
4133
+ placementChanged: true,
4134
+ capacityChanged: true
4135
+ } : {},
2509
4136
  fieldsChanged: union(a.fieldsChanged, b.fieldsChanged),
2510
4137
  sectionsChanged: union(a.sectionsChanged, b.sectionsChanged)
2511
4138
  };
@@ -2549,6 +4176,9 @@ function checkPlane(plane) {
2549
4176
  normal
2550
4177
  };
2551
4178
  }
4179
+ function collisionPairKey(a, b) {
4180
+ return a < b ? `${a}:${b}` : `${b}:${a}`;
4181
+ }
2552
4182
  /**
2553
4183
  * A checked plane with its normal normalised. Scaled by its largest
2554
4184
  * component first, so a huge finite normal (whose length overflows) or a
@@ -2571,4 +4201,4 @@ function normalised(plane) {
2571
4201
  ]
2572
4202
  };
2573
4203
  }
2574
- export { watchStatusKeys as a, createWorkerScene as i, WorkerScene as n, addFieldKeyed as r, MAX_THREADS as t };
4204
+ export { fieldTargets as a, watchStatusKeys as c, createWorkerScene as i, WorkerScene as n, presenceVersion as o, addFieldKeyed as r, sectionMeshes as s, MAX_THREADS as t };