From 0fdea96d690e8356a7de018ff75ce1a00a1fa190 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:09:01 -0800 Subject: [PATCH 01/40] (docs) Propose browser sculpting with automatic detail --- .../2026-11-23-browser-sculpting-design.md | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-23-browser-sculpting-design.md diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md new file mode 100644 index 0000000..dcb26f3 --- /dev/null +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -0,0 +1,105 @@ +# Browser sculpting v1 + +Status: proposed for review. + +## Intent + +Add freehand sculpting to Kitbasher's browser workbench, with ZBrush and Blender as workflow +references. The user chose automatic detail under the brush for the first release and asked +for full Wacom tablet support. The brush set, controls, and implementation below are proposed. + +## Approaches + +- **Local edge subdivision (recommended).** Split long edges as the brush passes over a coarse + area. Each split preserves the original triangle surfaces until the brush moves them. This + needs a growth limit and a picking index that can keep up with changing topology. +- **Local subdivision and edge collapse.** Also remove short edges to control density. This + adds geometric simplification, attribute transfer, and checks around boundaries and creases. +- **Voxel remeshing.** Kitbasher's current worker reconstructs a closed mesh and drops vertex + colors. Running it on a brush patch would require stitching the patch back into the source, + and can change thin features and open surfaces. + +## Workbench behavior + +Select one visible, unlocked part and choose **Sculpt** in the workbench toolbar. Keep the part +in its assembly so nearby parts remain visible. The panel shows the brush, radius, strength, +detail, and local X symmetry. Show a surface-aligned cursor at the hit under the tip and preview +the mirrored hit when symmetry is enabled. Start each direct dab on the nearest visible surface +under the tip, and act only when it belongs to the selected part. Resolve the mirror against a +nearby surface on that same part, including the far side when symmetry explicitly calls for it. +If the mirrored and direct footprints overlap, apply at most one dab's effect per vertex. + +Proposed brushes are Draw, Grab, Smooth, and Flatten. Draw raises the surface or digs into it +when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local surface and +follow the existing Refine behavior where it suits freehand strokes. Holding Shift temporarily +switches to Smooth. Keep pressure settings in a collapsible section of the same panel. + +Strokes preview in the viewport and commit on release. One undo or redo covers deformation and +all topology changes from that stroke. Escape, pointer cancellation, lost capture, blur, or an +external change to the target discards the active stroke. Leaving Sculpt keeps completed strokes. +Commit against the target part's identity, source mesh, and pose. Follow Refine's behavior of +keeping existing pins, anchors, pivot, joints, and constraint frames during a geometry edit. +Committed geometry saves, exports, and shares through the existing part geometry paths. Start +with imported meshes. Later releases can address starter meshes, masks, alphas, sculpt layers, +and XR. + +## Automatic detail + +- Use the visible hit triangle to seed a connected surface patch. Test triangle overlap with the + brush footprint so a small dab inside a single coarse triangle can still create useful detail. + Stop at disconnected shells and avoid catching the opposite face of a thin wall. +- Refine long edges in the patch to a target derived from radius and detail, with a minimum edge + length in scene units. Split all incident faces of each chosen edge for conformity, including + neighbors just outside the brush. Retain their surface shape, open boundaries, winding, and + seams. Interpolate normals and supported attributes along each render edge. Use a shared + geometric midpoint with separate render vertices where attributes differ. +- Bound per-frame subdivision work and total growth. At the growth limit, show a brief status and + keep brushing at the available density. Roll back subdivision when the stroke makes no surface + change. Treat invalid triangles and ambiguous edges as patch boundaries so usable areas of a + damaged scan remain sculptable. +- Keep mutable stroke data separate from saved geometry. Update picking against current triangles + and refresh changed positions and normals locally. Batch splits so a pen sample never triggers + a whole-part topology or GPU rebuild in the input handler. Refine's seam handling and vertex + updates are precedents. Its fast preview currently requires unchanged topology. + +## Wacom behavior + +- Use browser Pointer Events for pen tip, hover, pressure, buttons, and orientation. Consume + coalesced samples where available and resample by brush-relative spacing. Use individual events + as the fallback. Mouse input has steady strength. Touch stays available for navigation outside + the active stroke and secondary contact cannot paint or move the camera during pen contact. +- Enable pressure-sensitive strength by default. Offer pressure-sensitive radius and a pressure + curve. Give a pen barrel button viewport navigation and map the physical eraser to inverted Draw + when the browser exposes those buttons. Use reported tilt to orient an optional angled Draw + footprint and use twist to rotate it when available. Round brush settings work with default or + unavailable orientation data. Keep keyboard and mouse equivalents for brush actions. +- Verify on a physical Wacom Intuos and Cintiq. Start with Windows and macOS in Chromium, then + record the browser, OS, tablet, pen, driver, and features actually delivered for every supported + combination. The proposed launch matrix covers the capabilities exposed by those combinations. + Automated synthetic pen tests establish application behavior. Physical testing establishes tablet + support. [Wacom browser API](https://developer-docs.wacom.com/docs/icbt/web/web-api-overview/) + +## Verification + +- Unit tests cover coarse-triangle dabs, shared splits, open edges, indexed and unindexed inputs, + hard normals and vertex colors, thin and disconnected shells, isolated non-manifold regions, + transformed parts, growth limits, and exact stroke undo and redo. Existing positions beyond the + brush footprint must stay bit-identical. +- Browser tests cover tool entry, live preview, picking after a split, pressure ramps, modifiers, + navigation, cancellation, undo, save/reopen, and shared-scene commit and rejection. A discarded + stroke must leave the committed geometry and history untouched. +- Profile input-to-preview latency and retained history memory on a coarse mesh and an approximately + one-million-triangle scan. Use a recorded reference browser and machine. Aim for updates by + the next frame on a 60 Hz display during sustained strokes. Record p95 and worst-case latency, + and set supported mesh sizes and byte limits from the measured budgets before launch. Cap + retained sculpt history by bytes to avoid retaining an unbounded series of dense meshes. +- Run `npm test`, `npm run test:e2e -- tests/e2e/sculpt.spec.ts`, and `npm run build`. Run a physical + tablet pass for hover, slow pressure ramps, fast strokes, barrel navigation, eraser, tilt, twist, + incidental touch, and cancellation where the hardware provides those inputs. + +## Build order + +Mesh subdivision and transactional stroke editing first, followed by viewport picking and input, +then the complete brush panel and tablet controls. Measure the coarse and dense fixtures as soon +as the first Draw stroke works end to end. Keep the file format and dependencies unchanged unless +the implementation demonstrates a need to revisit them. From e68611d850f1646c0965851bdd88f754f03d409a Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:11:08 -0800 Subject: [PATCH 02/40] (docs) Include masking and advanced sculpt controls --- .../2026-11-23-browser-sculpting-design.md | 59 +++++++++++++++---- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md index dcb26f3..686cf7d 100644 --- a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -6,7 +6,8 @@ Status: proposed for review. Add freehand sculpting to Kitbasher's browser workbench, with ZBrush and Blender as workflow references. The user chose automatic detail under the brush for the first release and asked -for full Wacom tablet support. The brush set, controls, and implementation below are proposed. +for full Wacom tablet support, masking, and advanced brush parameters. The brush set, controls, +and implementation below are proposed. ## Approaches @@ -29,10 +30,10 @@ under the tip, and act only when it belongs to the selected part. Resolve the mi nearby surface on that same part, including the far side when symmetry explicitly calls for it. If the mirrored and direct footprints overlap, apply at most one dab's effect per vertex. -Proposed brushes are Draw, Grab, Smooth, and Flatten. Draw raises the surface or digs into it +Proposed brushes are Draw, Grab, Smooth, Flatten, and Mask. Draw raises the surface or digs into it when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local surface and follow the existing Refine behavior where it suits freehand strokes. Holding Shift temporarily -switches to Smooth. Keep pressure settings in a collapsible section of the same panel. +switches to Smooth on the sculpting brushes. In Mask mode it temporarily softens the mask. Strokes preview in the viewport and commit on release. One undo or redo covers deformation and all topology changes from that stroke. Escape, pointer cancellation, lost capture, blur, or an @@ -40,8 +41,40 @@ external change to the target discards the active stroke. Leaving Sculpt keeps c Commit against the target part's identity, source mesh, and pose. Follow Refine's behavior of keeping existing pins, anchors, pivot, joints, and constraint frames during a geometry edit. Committed geometry saves, exports, and shares through the existing part geometry paths. Start -with imported meshes. Later releases can address starter meshes, masks, alphas, sculpt layers, -and XR. +with imported meshes. Later releases can address starter meshes, alphas, sculpt layers, and XR. + +## Advanced brush parameters + +Keep everyday controls visible and group advanced parameters in a collapsible section. Offer a +reset to the defaults for the active brush. Preserve each brush's settings when switching brushes. + +| Group | Proposed controls | +| --- | --- | +| Falloff | Soft, linear, and hard profiles control how strength falls toward the edge. | +| Stroke | Dab spacing as a fraction of brush size and optional stroke stabilization. | +| Pressure | Separate strength and radius toggles and a pressure response curve. | +| Draw footprint | Round or elliptical, with roundness, rotation, and optional tilt or twist input. | +| Detail limits | Minimum edge size bounds local refinement at the selected detail level. | + +Show controls only where the active brush uses them. Update the cursor when radius, footprint, +or symmetry changes. Apply parameter changes to subsequent strokes so the current stroke uses a +consistent configuration. + +## Masking + +- Paint protection with Mask. Use the inverse gesture to erase, Shift to soften the mask, and + offer Invert and Clear for the whole part. Show protection as an overlay with a visibility toggle. +- Mask weights range from zero to one. Partial protection scales down brush displacement and full + protection keeps a point fixed. Use the same connected-surface and symmetry rules as sculpt dabs. + Pressure-sensitive mask strength follows the pen settings. +- Use automatic subdivision for fine mask strokes on coarse faces. Preserve the surface during + those splits and interpolate existing mask weights onto the new vertices, including at seams. + Commit any new triangles alongside the mask stroke, and skip geometry commits when the mesh + stays identical. Fully masked sculpt dabs leave the mesh untouched. +- Keep masks as temporary state for the selected part while Sculpt is open. Within Sculpt, + undo and redo cover mask edits and geometry strokes in order. Roll back both on cancellation + or a refused stroke. Leaving Sculpt clears the overlay and temporary weights. Saved and exported + parts include committed mesh detail. ## Automatic detail @@ -54,9 +87,9 @@ and XR. seams. Interpolate normals and supported attributes along each render edge. Use a shared geometric midpoint with separate render vertices where attributes differ. - Bound per-frame subdivision work and total growth. At the growth limit, show a brief status and - keep brushing at the available density. Roll back subdivision when the stroke makes no surface - change. Treat invalid triangles and ambiguous edges as patch boundaries so usable areas of a - damaged scan remain sculptable. + keep brushing at the available density. Roll back subdivision when the stroke changes neither + surface shape nor mask weights. Treat invalid triangles and ambiguous edges as patch boundaries + so usable areas of a damaged scan remain sculptable. - Keep mutable stroke data separate from saved geometry. Update picking against current triangles and refresh changed positions and normals locally. Batch splits so a pen sample never triggers a whole-part topology or GPU rebuild in the input handler. Refine's seam handling and vertex @@ -88,6 +121,10 @@ and XR. - Browser tests cover tool entry, live preview, picking after a split, pressure ramps, modifiers, navigation, cancellation, undo, save/reopen, and shared-scene commit and rejection. A discarded stroke must leave the committed geometry and history untouched. +- Verify mask painting, erasing, softening, inverting, clearing, and undo across subdivision. Test + that fully protected points keep their positions, partial protection scales the displacement, + and new vertices inherit interpolated weights. Verify that advanced settings affect subsequent + strokes, persist across brush switches, and reset to the active brush's defaults. - Profile input-to-preview latency and retained history memory on a coarse mesh and an approximately one-million-triangle scan. Use a recorded reference browser and machine. Aim for updates by the next frame on a 60 Hz display during sustained strokes. Record p95 and worst-case latency, @@ -100,6 +137,6 @@ and XR. ## Build order Mesh subdivision and transactional stroke editing first, followed by viewport picking and input, -then the complete brush panel and tablet controls. Measure the coarse and dense fixtures as soon -as the first Draw stroke works end to end. Keep the file format and dependencies unchanged unless -the implementation demonstrates a need to revisit them. +then masking, advanced brush parameters, and tablet controls. Measure the coarse and dense +fixtures as soon as the first Draw stroke works end to end. Keep the file format and dependencies +unchanged unless the implementation demonstrates a need to revisit them. From 7e2bf9c29dd31e776a1ea1fe11739267b972556f Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:15:11 -0800 Subject: [PATCH 03/40] (docs) Add the Crease sculpt brush to v1 --- .../specs/2026-11-23-browser-sculpting-design.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md index 686cf7d..a143563 100644 --- a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -30,10 +30,12 @@ under the tip, and act only when it belongs to the selected part. Resolve the mi nearby surface on that same part, including the far side when symmetry explicitly calls for it. If the mirrored and direct footprints overlap, apply at most one dab's effect per vertex. -Proposed brushes are Draw, Grab, Smooth, Flatten, and Mask. Draw raises the surface or digs into it -when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local surface and -follow the existing Refine behavior where it suits freehand strokes. Holding Shift temporarily -switches to Smooth on the sculpting brushes. In Mask mode it temporarily softens the mask. +The brush set includes Draw, Grab, Smooth, Flatten, Crease, and Mask. Draw raises the surface or +digs into it when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local +surface and follow the existing Refine behavior where it suits freehand strokes. Crease pulls the +surface toward the stroke path while cutting a groove. Invert the depth to form a sharp ridge. +Holding Shift temporarily switches to Smooth on the sculpting brushes. In Mask mode it temporarily +softens the mask. Strokes preview in the viewport and commit on release. One undo or redo covers deformation and all topology changes from that stroke. Escape, pointer cancellation, lost capture, blur, or an @@ -54,6 +56,7 @@ reset to the defaults for the active brush. Preserve each brush's settings when | Stroke | Dab spacing as a fraction of brush size and optional stroke stabilization. | | Pressure | Separate strength and radius toggles and a pressure response curve. | | Draw footprint | Round or elliptical, with roundness, rotation, and optional tilt or twist input. | +| Crease | Pinch controls how tightly the brush draws the surface toward the stroke path. | | Detail limits | Minimum edge size bounds local refinement at the selected detail level. | Show controls only where the active brush uses them. Update the cursor when radius, footprint, @@ -125,6 +128,8 @@ consistent configuration. that fully protected points keep their positions, partial protection scales the displacement, and new vertices inherit interpolated weights. Verify that advanced settings affect subsequent strokes, persist across brush switches, and reset to the active brush's defaults. +- Verify that Crease forms a groove or an inverted ridge on coarse and dense meshes, respects + masking, and undoes its deformation and added topology together. - Profile input-to-preview latency and retained history memory on a coarse mesh and an approximately one-million-triangle scan. Use a recorded reference browser and machine. Aim for updates by the next frame on a 60 Hz display during sustained strokes. Record p95 and worst-case latency, From d2602d0cebf13caf28631029eef69ad8c3da1783 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:16:08 -0800 Subject: [PATCH 04/40] (docs) Plan browser sculpting implementation and volume brushes --- .../plans/2026-11-23-browser-sculpting.md | 18 ++++++++++++++++++ .../2026-11-23-browser-sculpting-design.md | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-23-browser-sculpting.md diff --git a/docs/superpowers/plans/2026-11-23-browser-sculpting.md b/docs/superpowers/plans/2026-11-23-browser-sculpting.md new file mode 100644 index 0000000..35d92bc --- /dev/null +++ b/docs/superpowers/plans/2026-11-23-browser-sculpting.md @@ -0,0 +1,18 @@ +# Browser sculpting implementation plan + +Implement the [Sculpt v1 design](../specs/2026-11-23-browser-sculpting-design.md) +in the existing Three.js workbench. Keep working geometry separate from committed parts. + +- [ ] Build and unit-test the editable mesh and brush kernel in `src/core/sculpt-mesh.ts`. + Verify local conforming subdivision of a coarse triangle, connected footprints, masks, + seam interpolation, bounded growth, and brush-specific displacement. +- [ ] Add the Sculpt tool, settings and history in `src/core/store.ts`, + `src/components/SculptControls.tsx` and the existing workbench tool entry points. + Verify target identity, visibility and lock eligibility before accepting geometry. +- [ ] Connect native pointer input and the editable preview in `src/components/SculptPointer.tsx` + and `src/components/Viewport.tsx`. Verify pressure and orientation, capture and cancellation, + occlusion, mask preview, symmetry and a single checkpoint per accepted stroke. +- [ ] Exercise the workflow through the viewport, including undo/redo, automatic detail, + masking and save/reopen. Run the unit suite and production build. +- [ ] Measure dense-mesh stroke latency and memory. Record physical Wacom results by OS, + browser, tablet and driver before claiming compatibility. diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md index a143563..118a9ec 100644 --- a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -1,6 +1,6 @@ # Browser sculpting v1 -Status: proposed for review. +Status: approved for implementation. ## Intent @@ -30,10 +30,11 @@ under the tip, and act only when it belongs to the selected part. Resolve the mi nearby surface on that same part, including the far side when symmetry explicitly calls for it. If the mirrored and direct footprints overlap, apply at most one dab's effect per vertex. -The brush set includes Draw, Grab, Smooth, Flatten, Crease, and Mask. Draw raises the surface or +The brush set includes Draw, Grab, Smooth, Flatten, Crease, Clay Buildup, Inflate/Deflate, and Mask. Draw raises the surface or digs into it when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local surface and follow the existing Refine behavior where it suits freehand strokes. Crease pulls the surface toward the stroke path while cutting a groove. Invert the depth to form a sharp ridge. +Clay Buildup adds broad layers against the local surface plane. Inflate/Deflate moves vertices along their individual surface normals. Holding Shift temporarily switches to Smooth on the sculpting brushes. In Mask mode it temporarily softens the mask. From 446356120798618a34b1d32d729994197645651e Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:29:26 -0800 Subject: [PATCH 05/40] (feat) Wire sculpt strokes into the browser viewport --- README.md | 17 + .../plans/2026-11-23-browser-sculpting.md | 16 +- .../2026-11-23-browser-sculpting-design.md | 14 +- src/components/CameraNavigation.tsx | 1 + src/components/SculptPointer.tsx | 678 ++++++++++++++++++ src/components/Viewport.tsx | 11 +- tests/unit/sculpt-benchmark.test.ts | 86 +++ 7 files changed, 805 insertions(+), 18 deletions(-) create mode 100644 src/components/SculptPointer.tsx create mode 100644 tests/unit/sculpt-benchmark.test.ts diff --git a/README.md b/README.md index 53a9cee..b9454b8 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,23 @@ shared the mesh keep the original. Warp works on parts of up to 10 million triangles. On a large region the grid lines follow your drag, and the surface updates when you release. +## Sculpt a part + +Select a visible, unlocked part and choose **Sculpt**. Draw builds or removes material, Clay +Buildup layers broad strokes, and Inflate/Deflate changes the volume of rounded details. Grab +moves a patch, Crease sharpens a groove or ridge, and Smooth and Flatten clean up the surface. +The brush adds mesh detail locally as needed. Adjust **Detail** to change the density. + +- Hold **Alt** to invert an applicable brush and **Shift** for temporary smoothing. +- Use **Mask** to protect areas. Hold **Alt** to erase protection or **Shift** to soften it. + Masks stay with the active Sculpt session. Saved scenes contain the sculpted mesh. +- Open **Advanced** for falloff, stroke spacing, stabilization, pen pressure, and brush-specific + controls. When a Wacom tablet reports pen data through the browser, Sculpt can use pressure, + tilt, twist, the eraser, and the barrel button. Available signals depend on the tablet, driver, + and browser. +- Each completed stroke is one undo step, including any triangles it added. Press **Escape** + during a stroke to discard it. + ## Part colors and lighting Editor colors and lighting change only how the scene looks here. Both are undoable, are saved diff --git a/docs/superpowers/plans/2026-11-23-browser-sculpting.md b/docs/superpowers/plans/2026-11-23-browser-sculpting.md index 35d92bc..6e876c6 100644 --- a/docs/superpowers/plans/2026-11-23-browser-sculpting.md +++ b/docs/superpowers/plans/2026-11-23-browser-sculpting.md @@ -4,15 +4,15 @@ Implement the [Sculpt v1 design](../specs/2026-11-23-browser-sculpting-design.md in the existing Three.js workbench. Keep working geometry separate from committed parts. - [ ] Build and unit-test the editable mesh and brush kernel in `src/core/sculpt-mesh.ts`. - Verify local conforming subdivision of a coarse triangle, connected footprints, masks, - seam interpolation, bounded growth, and brush-specific displacement. + Verify local conforming subdivision of a coarse triangle, connected footprints, masks, + seam interpolation, bounded growth, and brush-specific displacement. - [ ] Add the Sculpt tool, settings and history in `src/core/store.ts`, - `src/components/SculptControls.tsx` and the existing workbench tool entry points. - Verify target identity, visibility and lock eligibility before accepting geometry. + `src/components/SculptControls.tsx` and the existing workbench tool entry points. + Verify target identity, visibility and lock eligibility before accepting geometry. - [ ] Connect native pointer input and the editable preview in `src/components/SculptPointer.tsx` - and `src/components/Viewport.tsx`. Verify pressure and orientation, capture and cancellation, - occlusion, mask preview, symmetry and a single checkpoint per accepted stroke. + and `src/components/Viewport.tsx`. Verify pressure and orientation, capture and cancellation, + occlusion, mask preview, symmetry and a single checkpoint per accepted stroke. - [ ] Exercise the workflow through the viewport, including undo/redo, automatic detail, - masking and save/reopen. Run the unit suite and production build. + masking and save/reopen. Run the unit suite and production build. - [ ] Measure dense-mesh stroke latency and memory. Record physical Wacom results by OS, - browser, tablet and driver before claiming compatibility. + browser, tablet and driver before claiming compatibility. diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md index 118a9ec..0fc9433 100644 --- a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -51,14 +51,14 @@ with imported meshes. Later releases can address starter meshes, alphas, sculpt Keep everyday controls visible and group advanced parameters in a collapsible section. Offer a reset to the defaults for the active brush. Preserve each brush's settings when switching brushes. -| Group | Proposed controls | -| --- | --- | -| Falloff | Soft, linear, and hard profiles control how strength falls toward the edge. | -| Stroke | Dab spacing as a fraction of brush size and optional stroke stabilization. | -| Pressure | Separate strength and radius toggles and a pressure response curve. | +| Group | Proposed controls | +| -------------- | -------------------------------------------------------------------------------- | +| Falloff | Soft, linear, and hard profiles control how strength falls toward the edge. | +| Stroke | Dab spacing as a fraction of brush size and optional stroke stabilization. | +| Pressure | Separate strength and radius toggles and a pressure response curve. | | Draw footprint | Round or elliptical, with roundness, rotation, and optional tilt or twist input. | -| Crease | Pinch controls how tightly the brush draws the surface toward the stroke path. | -| Detail limits | Minimum edge size bounds local refinement at the selected detail level. | +| Crease | Pinch controls how tightly the brush draws the surface toward the stroke path. | +| Detail limits | Minimum edge size bounds local refinement at the selected detail level. | Show controls only where the active brush uses them. Update the cursor when radius, footprint, or symmetry changes. Apply parameter changes to subsequent strokes so the current stroke uses a diff --git a/src/components/CameraNavigation.tsx b/src/components/CameraNavigation.tsx index 1d913e1..2cbf36b 100644 --- a/src/components/CameraNavigation.tsx +++ b/src/components/CameraNavigation.tsx @@ -31,6 +31,7 @@ const initialOrbitTarget: [number, number, number] = [0, 54, 0]; /** Whether a left drag paints with a surface brush rather than moving the camera. */ const brushOwnsLeftDrag = (state: Editor) => ((state.tool === 'align' && state.operation.mode === 'surface') || + state.tool === 'sculpt' || paintingWarpRegion(state) || paintingRefine(state) || brushingRefine(state)) && diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx new file mode 100644 index 0000000..c345efb --- /dev/null +++ b/src/components/SculptPointer.tsx @@ -0,0 +1,678 @@ +import { useEffect } from 'react'; +import { useThree } from '@react-three/fiber'; +import { + BufferAttribute, + BufferGeometry, + DoubleSide, + Matrix3, + Matrix4, + Mesh, + MeshBasicMaterial, + Raycaster, + RingGeometry, + ShaderMaterial, + Vector2, + Vector3, + type Intersection, +} from 'three'; +import { acceleratedRaycast } from 'three-mesh-bvh'; +import { SculptMesh, type SculptDab } from '../core/sculpt-mesh'; +import { useEditor } from '../core/store'; +import type { Part, SculptureSettings } from '../core/types'; +import { partMeshes } from '../xr/part-meshes'; + +type Sample = Pick< + PointerEvent, + 'clientX' | 'clientY' | 'pressure' | 'pointerType' | 'tiltX' | 'tiltY' | 'twist' +>; +type Hit = Pick; + +const lerp = (a: number, b: number, t: number) => a + (b - a) * t; + +function interpolate(a: Sample, b: Sample, t: number): Sample { + return { + pointerType: b.pointerType, + clientX: lerp(a.clientX, b.clientX, t), + clientY: lerp(a.clientY, b.clientY, t), + pressure: lerp(a.pressure, b.pressure, t), + tiltX: lerp(a.tiltX, b.tiltX, t), + tiltY: lerp(a.tiltY, b.tiltY, t), + twist: (a.twist + (((b.twist - a.twist + 540) % 360) - 180) * t + 360) % 360, + }; +} + +const visible = (mesh: Mesh) => { + for (let object = mesh.parent; object; object = object.parent) if (!object.visible) return false; + return mesh.visible; +}; + +function pressure(sample: Sample, settings: SculptureSettings) { + return sample.pointerType === 'pen' ? sample.pressure ** settings.pressureCurve : 1; +} + +function footprint(s: SculptureSettings, sample: Sample) { + const pen = sample.pointerType === 'pen'; + const tilt = s.tilt && pen && (sample.tiltX || sample.tiltY); + const angle = + (s.rotation + (s.twist && pen ? sample.twist : 0)) * (Math.PI / 180) + + (tilt ? Math.atan2(-sample.tiltY, sample.tiltX) : 0); + return angle; +} + +function hitFrom(intersection: Intersection, mesh: Mesh): Hit | null { + if (!intersection.face || intersection.faceIndex == null) return null; + return { + point: intersection.point, + normal: intersection.face.normal + .clone() + .applyNormalMatrix(new Matrix3().getNormalMatrix(mesh.matrixWorld)), + face: intersection.faceIndex, + }; +} + +interface Stroke { + id: number; + target: Part; + epoch: number; + revision: number; + own: Mesh; + before: BufferGeometry; + draft: SculptMesh; + settings: SculptureSettings; + controls: { enabled: boolean } | null; + controlsEnabled: boolean; + brush: SculptDab['brush']; + inverted: boolean; + softenMask: boolean; + last: Sample; + pending: Sample[]; + changed: boolean; + end: boolean; + spacing: number; + first: Hit; + grabPoint: Vector3; + grabMirror: Hit | null; + applied: Sample | null; +} + +export function SculptPointer() { + const get = useThree((s) => s.get); + const invalidate = useThree((s) => s.invalidate); + useEffect(() => { + const { events, gl, scene } = get(); + const canvas = events.connected instanceof HTMLElement ? events.connected : gl.domElement; + const ray = new Raycaster(); + ray.firstHitOnly = true; + const ndc = new Vector2(); + const direction = new Vector3(); + const right = new Vector3(); + const cursorShape = new RingGeometry(0.975, 1, 56); + const cursorPaint = new MeshBasicMaterial({ + color: '#ffd195', + side: DoubleSide, + polygonOffset: true, + polygonOffsetFactor: -2, + polygonOffsetUnits: -2, + depthWrite: false, + }); + const cursors = [new Mesh(cursorShape, cursorPaint), new Mesh(cursorShape, cursorPaint)]; + const maskPaint = new ShaderMaterial({ + transparent: true, + depthWrite: false, + polygonOffset: true, + polygonOffsetFactor: -1, + polygonOffsetUnits: -1, + vertexShader: ` + attribute float sculptMask; + varying float protection; + void main() { + protection = sculptMask; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: ` + varying float protection; + void main() { gl_FragColor = vec4(0.02, 0.05, 0.09, protection * 0.75); } + `, + }); + const overlay = new Mesh(undefined, maskPaint); + const emptyOverlay = overlay.geometry; + overlay.matrixAutoUpdate = false; + overlay.frustumCulled = false; + overlay.renderOrder = 1; + overlay.visible = false; + const mirrorMaterial = new MeshBasicMaterial({ side: DoubleSide }); + const mirrorMesh = new Mesh(undefined, mirrorMaterial); + const emptyMirror = mirrorMesh.geometry; + mirrorMesh.matrixAutoUpdate = false; + let idleOverlay: BufferGeometry | null = null; + let idleSource: BufferGeometry | null = null; + let idleWeights: Float32Array | null = null; + let stroke: Stroke | null = null; + let warm: { + source: BufferGeometry; + mask: Float32Array | null; + matrix: Matrix4; + draft: SculptMesh; + } | null = null; + let warmTimer = 0; + const discardWarm = () => { + warm?.draft.geometry.dispose(); + warm = null; + }; + const preparationTarget = () => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + if (!sculpt || state.view.explode || stroke) return null; + const own = partMeshes.get(sculpt.partId); + const part = state.scene.parts.find((p) => p.id === sculpt.partId); + if (!own || !part || part.locked || !visible(own)) return null; + own.updateWorldMatrix(true, false); + return { source: part.geometry, mask: sculpt.mask, matrix: own.matrixWorld }; + }; + const prepare = () => { + if (warmTimer || stroke) return; + warmTimer = window.setTimeout(() => { + warmTimer = 0; + const target = preparationTarget(); + if (!target) return discardWarm(); + const { source, mask, matrix } = target; + if (warm?.source === source && warm.mask === mask && warm.matrix.equals(matrix)) return; + discardWarm(); + const draft = new SculptMesh(source, matrix, mask ?? undefined); + draft.prepare(); + warm = { source, mask, matrix: matrix.clone(), draft }; + }, 60); + }; + let frame = 0; + let hover: Sample | null = null; + let suppressClick = false; + let clickTimer = 0; + const hideCursor = () => cursors.forEach((cursor) => (cursor.visible = false)); + hideCursor(); + scene.add(...cursors, overlay); + + const setRay = (sample: Sample) => { + const rect = canvas.getBoundingClientRect(); + ndc.set( + ((sample.clientX - rect.left) / rect.width) * 2 - 1, + 1 - ((sample.clientY - rect.top) / rect.height) * 2, + ); + ray.setFromCamera(ndc, get().camera); + }; + const intersect = (mesh: Mesh): Intersection[] => { + if (stroke?.own !== mesh) return ray.intersectObject(mesh, false); + const hits: Intersection[] = []; + stroke.draft.raycast(ray, mesh, hits); + return hits; + }; + const pick = (sample: Sample, own: Mesh): Hit | null => { + setRay(sample); + let closest: Intersection | undefined; + for (const mesh of partMeshes.values()) { + if (!visible(mesh)) continue; + const hit = intersect(mesh)[0]; + if (hit && (!closest || hit.distance < closest.distance)) closest = hit; + } + return closest?.object === own ? hitFrom(closest, own) : null; + }; + const mirror = (hit: Hit, own: Mesh, radius: number): Hit | null => { + const inverse = new Matrix4().copy(own.matrixWorld).invert(); + const local = hit.point.clone().applyMatrix4(inverse); + if (Math.abs(local.x) < 1e-7) return null; + local.x = -local.x; + const point = local.applyMatrix4(own.matrixWorld); + const direction = hit.normal + .clone() + .applyNormalMatrix(new Matrix3().getNormalMatrix(inverse)); + direction.x = -direction.x; + direction.applyNormalMatrix(new Matrix3().getNormalMatrix(own.matrixWorld)); + const range = radius * 0.2; + mirrorMesh.geometry = own.geometry; + if (!stroke) { + const part = useEditor.getState().scene.parts.find((p) => partMeshes.get(p.id) === own); + if (part) mirrorMesh.geometry = part.geometry; + } + mirrorMesh.matrixWorld.copy(own.matrixWorld); + ray.set(point.clone().addScaledVector(direction, range), direction.clone().negate()); + ray.far = range * 2; + const hits: Intersection[] = []; + ray.firstHitOnly = false; + if (stroke) stroke.draft.raycast(ray, mirrorMesh, hits); + else if ( + mirrorMesh.geometry.boundsTree || + (mirrorMesh.geometry.index?.count ?? mirrorMesh.geometry.getAttribute('position').count) < + 150_000 + ) + acceleratedRaycast.call(mirrorMesh, ray, hits); + ray.firstHitOnly = true; + ray.far = Infinity; + const closest = hits.reduce( + (best, entry) => + !best || entry.point.distanceToSquared(point) < best.point.distanceToSquared(point) + ? entry + : best, + undefined, + ); + return closest ? hitFrom(closest, own) : null; + }; + const tangentAt = (hit: Hit, angle: number) => { + get().camera.matrixWorld.extractBasis(right, new Vector3(), new Vector3()); + const tangent = right.clone().addScaledVector(hit.normal, -right.dot(hit.normal)); + if (tangent.lengthSq() < 1e-8) + tangent.crossVectors( + hit.normal, + Math.abs(hit.normal.y) < 0.9 ? new Vector3(0, 1, 0) : new Vector3(1, 0, 0), + ); + return tangent.normalize().applyAxisAngle(hit.normal, angle); + }; + const show = (i: number, hit: Hit | null, radius: number, aspect: number, angle: number) => { + const cursor = cursors[i]; + cursor.visible = !!hit && radius > 0; + if (!hit) return; + const tangent = tangentAt(hit, angle); + cursor.position.copy(hit.point).addScaledVector(hit.normal, radius * 0.006); + cursor.quaternion.setFromRotationMatrix( + new Matrix4().makeBasis( + tangent, + new Vector3().crossVectors(hit.normal, tangent), + hit.normal, + ), + ); + cursor.scale.set(radius, radius * aspect, radius); + }; + const displayMask = () => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + const own = sculpt && partMeshes.get(sculpt.partId); + overlay.visible = false; + if ( + !sculpt || + !own || + !sculpt.settings.maskVisible || + (!sculpt.mask && stroke?.brush !== 'mask') || + !visible(own) + ) + return; + const source = state.scene.parts.find((part) => part.id === sculpt.partId)?.geometry; + if (!source) return; + if (stroke?.draft.geometry.hasAttribute('sculptMask')) + overlay.geometry = stroke.draft.geometry; + else if (sculpt.mask) { + if (idleSource !== source || idleWeights !== sculpt.mask || !idleOverlay) { + idleOverlay?.dispose(); + idleSource = source; + idleWeights = sculpt.mask; + idleOverlay = new BufferGeometry(); + idleOverlay.setAttribute('position', source.getAttribute('position')); + idleOverlay.setIndex(source.index); + idleOverlay.setAttribute('sculptMask', new BufferAttribute(sculpt.mask, 1)); + } + overlay.geometry = idleOverlay; + } else return; + overlay.matrix.copy(own.matrixWorld); + overlay.matrixWorldNeedsUpdate = true; + overlay.visible = true; + }; + const refresh = () => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + const own = sculpt && partMeshes.get(sculpt.partId); + if ( + !hover || + !sculpt || + !own || + state.navigationMode || + state.temporaryOrbit || + state.view.explode + ) { + hideCursor(); + } else { + const settings = stroke?.settings ?? sculpt.settings; + const radius = + settings.radius * + (settings.pressureRadius && stroke ? Math.max(0.08, pressure(hover, settings)) : 1); + const hit = pick(hover, own); + const aspect = settings.brush === 'draw' ? settings.aspect : 1; + const angle = footprint(settings, hover); + show(0, hit, radius, aspect, angle); + show(1, hit && settings.symmetry ? mirror(hit, own, radius) : null, radius, aspect, -angle); + } + displayMask(); + invalidate(); + }; + const detach = (accept: boolean) => { + const active = stroke; + if (!active) return; + stroke = null; + if (active.controls) active.controls.enabled = active.controlsEnabled; + if (canvas.hasPointerCapture(active.id)) canvas.releasePointerCapture(active.id); + if (active.own.geometry === active.draft.geometry) active.own.geometry = active.before; + overlay.visible = false; + if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; + if (accept && active.changed) { + const geometry = active.draft.finish(); + const mask = active.draft.getMask(); + const { id: partId, geometry: source, position, quaternion, scale } = active.target; + if ( + !useEditor.getState().commitSculpt({ + partId, + source, + epoch: active.epoch, + revision: active.revision, + position, + quaternion, + scale, + geometry, + mask: mask.some((value) => value > 0) ? mask : null, + }) + ) + geometry?.dispose(); + } + if (accept && active.draft.detailLimited) + useEditor + .getState() + .notify( + 'Sculpt detail reached its limit. You can keep brushing at this density.', + 'info', + ); + active.draft.geometry.dispose(); + prepare(); + refresh(); + }; + const apply = (active: Stroke, sample: Sample) => { + const s = active.settings; + const hit = active.brush === 'grab' ? active.first : pick(sample, active.own); + if (!hit) return; + const p = pressure(sample, s); + const strength = s.strength * (s.pressureStrength ? p : 1); + if (!(strength > 0)) return; + const radius = s.radius * (s.pressureRadius ? Math.max(0.08, p) : 1); + let angle = footprint(s, sample); + if (active.brush === 'crease' && active.applied) { + const dx = sample.clientX - active.applied.clientX; + const dy = active.applied.clientY - sample.clientY; + if (dx || dy) angle = Math.atan2(dy, dx); + } + active.applied = sample; + const tangent = tangentAt(hit, angle); + const twin = + active.brush === 'grab' + ? active.grabMirror + : s.symmetry + ? mirror(hit, active.own, radius) + : null; + let grab: Vector3 | undefined; + let mirroredGrab: Vector3 | undefined; + if (active.brush === 'grab') { + setRay(sample); + get().camera.getWorldDirection(direction); + const projection = active.first.point.clone().sub(ray.ray.origin).dot(direction); + const point = ray.ray.at(projection / ray.ray.direction.dot(direction), new Vector3()); + grab = point.clone().sub(active.grabPoint); + active.grabPoint.copy(point); + if (twin) { + const local = grab + .clone() + .applyMatrix3(new Matrix3().setFromMatrix4(active.own.matrixWorld.clone().invert())); + local.x = -local.x; + mirroredGrab = local.applyMatrix3(new Matrix3().setFromMatrix4(active.own.matrixWorld)); + } + } + active.changed = + active.draft.dab({ + ...hit, + radius, + strength, + detail: s.detail, + minEdge: s.minEdge, + brush: active.brush, + falloff: s.falloff, + inverted: active.inverted, + pinch: s.pinch, + softenMask: active.softenMask, + grab, + tangent, + aspect: active.brush === 'draw' ? s.aspect : 1, + mirror: twin + ? { ...twin, tangent: tangentAt(twin, -angle), grab: mirroredGrab } + : undefined, + }) || active.changed; + }; + const schedule = () => { + if (frame) return; + frame = requestAnimationFrame(() => { + frame = 0; + const active = stroke; + if (active) { + const until = performance.now() + 6; + do { + const sample = active.pending.shift(); + if (sample) apply(active, sample); + } while (active.pending.length && performance.now() < until); + if (!active.pending.length && active.end) detach(true); + else if (active.pending.length) schedule(); + } + refresh(); + }); + }; + const enqueue = (active: Stroke, incoming: Sample, final = false) => { + const sample = final + ? incoming + : interpolate(active.last, incoming, 1 - active.settings.stabilization * 0.85); + const distance = Math.hypot( + sample.clientX - active.last.clientX, + sample.clientY - active.last.clientY, + ); + const steps = Math.min(32, Math.floor(distance / active.spacing)); + if (steps) { + for (let i = 1; i <= steps; i++) + active.pending.push(interpolate(active.last, sample, i / steps)); + } else if ( + final + ? distance > 0.1 + : distance < 0.1 && Math.abs(sample.pressure - active.last.pressure) > 0.015 + ) { + active.pending.push(sample); + } else return; + active.last = sample; + }; + const down = (event: PointerEvent) => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + if (stroke) { + event.stopImmediatePropagation(); + return; + } + if ( + !sculpt || + sculpt.pending || + !event.isPrimary || + (event.button !== 0 && !(event.pointerType === 'pen' && event.button === 5)) || + event.pointerType === 'touch' || + state.navigationMode || + state.temporaryOrbit || + state.pivotPicking || + state.view.explode || + state.freeTransform || + event.ctrlKey || + event.metaKey + ) + return; + const target = state.scene.parts.find((part) => part.id === sculpt.partId); + const own = target && partMeshes.get(target.id); + if (!target || !own || target.locked || !visible(own)) return; + const hit = pick(event, own); + if (!hit) return; + event.preventDefault(); + event.stopImmediatePropagation(); + try { + canvas.setPointerCapture(event.pointerId); + } catch { + /* Synthetic pointer events lack native capture. */ + } + const controls = get().controls as { enabled: boolean } | null; + const settings = sculpt.settings; + const camera = get().camera; + const projected = hit.point.clone().project(camera); + const radial = tangentAt(hit, 0) + .multiplyScalar(settings.radius) + .add(hit.point) + .project(camera); + const rect = canvas.getBoundingClientRect(); + const radiusPixels = + Math.hypot((radial.x - projected.x) * rect.width, (radial.y - projected.y) * rect.height) / + 2; + const cached = + warm?.source === target.geometry && + warm.mask === sculpt.mask && + warm.matrix.equals(own.matrixWorld) + ? warm.draft + : null; + if (cached) warm = null; + else discardWarm(); + const draft = + cached ?? new SculptMesh(target.geometry, own.matrixWorld, sculpt.mask ?? undefined); + const eraser = event.button === 5; + const brush = + settings.brush === 'mask' + ? 'mask' + : eraser + ? 'draw' + : event.shiftKey + ? 'smooth' + : settings.brush; + stroke = { + id: event.pointerId, + target, + epoch: state.sceneEpoch, + revision: sculpt.revision, + own, + before: own.geometry, + draft, + controls, + controlsEnabled: controls?.enabled ?? false, + settings, + brush, + inverted: eraser || event.altKey, + softenMask: brush === 'mask' && event.shiftKey, + first: hit, + grabPoint: hit.point.clone(), + grabMirror: + brush === 'grab' && settings.symmetry ? mirror(hit, own, settings.radius) : null, + applied: null, + last: event, + pending: [event], + changed: false, + end: false, + spacing: Math.max(0.75, radiusPixels * settings.spacing), + }; + if (controls) controls.enabled = false; + own.geometry = draft.geometry; + hover = event; + schedule(); + }; + const move = (event: PointerEvent) => { + if (stroke) { + if (event.pointerId !== stroke.id) return; + event.stopImmediatePropagation(); + if (stroke.end) return; + const events = event.getCoalescedEvents?.() ?? []; + for (const sample of events.length ? events : [event]) enqueue(stroke, sample); + } else if (!canvas.contains(event.target as Node) || event.pointerType === 'touch') return; + hover = event; + schedule(); + }; + const release = (event: PointerEvent) => { + if (!stroke || event.pointerId !== stroke.id) return; + event.stopImmediatePropagation(); + enqueue( + stroke, + { ...interpolate(stroke.last, event, 1), pressure: stroke.last.pressure }, + true, + ); + stroke.end = true; + suppressClick = true; + window.clearTimeout(clickTimer); + clickTimer = window.setTimeout(() => (suppressClick = false), 300); + schedule(); + }; + const cancel = (event: PointerEvent) => { + if (stroke?.id === event.pointerId && !stroke.end) detach(false); + }; + const escape = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || !stroke) return; + event.preventDefault(); + event.stopImmediatePropagation(); + detach(false); + }; + const blur = () => { + hover = null; + detach(false); + refresh(); + }; + const leave = () => { + if (!stroke) { + hover = null; + schedule(); + } + }; + const click = (event: MouseEvent) => { + if (!suppressClick) return; + suppressClick = false; + event.stopImmediatePropagation(); + }; + const unsubscribe = useEditor.subscribe((state) => { + if ( + stroke && + (state.sculpt?.partId !== stroke.target.id || + state.sculpt.revision !== stroke.revision || + state.sceneEpoch !== stroke.epoch || + state.navigationMode || + state.temporaryOrbit || + state.view.explode || + state.scene.parts.find((part) => part.id === stroke?.target.id) !== stroke.target) + ) + detach(false); + prepare(); + schedule(); + }); + prepare(); + canvas.addEventListener('pointerdown', down, true); + canvas.addEventListener('lostpointercapture', cancel); + canvas.addEventListener('pointerleave', leave); + canvas.addEventListener('click', click, true); + window.addEventListener('pointermove', move, true); + window.addEventListener('pointerup', release, true); + window.addEventListener('pointercancel', cancel, true); + window.addEventListener('keydown', escape, true); + window.addEventListener('blur', blur); + return () => { + unsubscribe(); + canvas.removeEventListener('pointerdown', down, true); + canvas.removeEventListener('lostpointercapture', cancel); + canvas.removeEventListener('pointerleave', leave); + canvas.removeEventListener('click', click, true); + window.removeEventListener('pointermove', move, true); + window.removeEventListener('pointerup', release, true); + window.removeEventListener('pointercancel', cancel, true); + window.removeEventListener('keydown', escape, true); + window.removeEventListener('blur', blur); + cancelAnimationFrame(frame); + window.clearTimeout(clickTimer); + hover = null; + detach(false); + window.clearTimeout(warmTimer); + discardWarm(); + scene.remove(...cursors, overlay); + cursorShape.dispose(); + cursorPaint.dispose(); + idleOverlay?.dispose(); + emptyOverlay.dispose(); + emptyMirror.dispose(); + maskPaint.dispose(); + mirrorMaterial.dispose(); + }; + }, [get, invalidate]); + return null; +} diff --git a/src/components/Viewport.tsx b/src/components/Viewport.tsx index 81d67a2..ea6909d 100644 --- a/src/components/Viewport.tsx +++ b/src/components/Viewport.tsx @@ -71,6 +71,7 @@ import { FreeTransformController, FreeTransformPrompt } from './FreeTransform'; import { CombinedTransform } from './CombinedTransform'; import { ManagedTransformControls } from './ManagedTransformControls'; import { WarpOverlay, shownWarpPreview } from './WarpOverlay'; +import { SculptPointer } from './SculptPointer'; import { beginWarpStroke, endingWarpStroke, WarpStrokeController } from './WarpStroke'; import { beginRefinePaint, @@ -137,7 +138,7 @@ const noRaycast = () => {}; const RefineOverlay = lazy(() => import('./RefineOverlay').then(({ RefineOverlay }) => ({ default: RefineOverlay })), ); -const toolsPicking = ['align', 'joint', 'measure', 'anchors', 'pins', 'warp', 'refine']; +const toolsPicking = ['align', 'joint', 'measure', 'anchors', 'pins', 'warp', 'refine', 'sculpt']; // A press on a gizmo handle also reaches whatever lies under it, but it is not a selection click. let gizmoPressed = false; const gizmoWasPressed = () => gizmoPressed; @@ -250,7 +251,7 @@ const PartMesh = memo(function PartMesh({ event.stopPropagation(); if (gizmoPressed) return; const state = useEditor.getState(); - if (state.navigationMode || state.temporaryOrbit) return; + if (state.navigationMode || state.temporaryOrbit || state.tool === 'sculpt') return; if (state.pivotPicking) { state.setPartPivot(toSurface(event)); return; @@ -343,6 +344,7 @@ const PartMesh = memo(function PartMesh({ receiveShadow={!ghost} onContextMenu={(event) => { event.nativeEvent.preventDefault(); + if (useEditor.getState().tool === 'sculpt') return; event.stopPropagation(); useEditor.getState().openContextMenu({ x: event.nativeEvent.clientX, @@ -449,6 +451,7 @@ const PartMesh = memo(function PartMesh({ !nearby && !warpPreview && !refinePreview && + tool !== 'sculpt' && triangleCount(part.geometry) < proxyThreshold ? ( ) : null} @@ -1233,6 +1236,7 @@ function Scene({ ) : null} + {tool === 'sculpt' ? : null} @@ -1356,7 +1360,8 @@ export function Viewport() { state.pivotPicking || tool === 'align' || tool === 'joint' || - tool === 'measure' + tool === 'measure' || + tool === 'sculpt' ) return; // While warping or refining, an empty click clears that tool's selection and keeps diff --git a/tests/unit/sculpt-benchmark.test.ts b/tests/unit/sculpt-benchmark.test.ts new file mode 100644 index 0000000..82cdc5f --- /dev/null +++ b/tests/unit/sculpt-benchmark.test.ts @@ -0,0 +1,86 @@ +import { it, expect } from 'vitest'; +import { writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + DoubleSide, + Matrix4, + Mesh, + MeshBasicMaterial, + PlaneGeometry, + Raycaster, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import { SculptMesh } from '../../src/core/sculpt-mesh'; + +const enabled = process.env.KITBASHER_SCULPT_BENCH; +const timed = (work: () => T) => { + const start = performance.now(); + const result = work(); + return { result, ms: performance.now() - start }; +}; + +it.skipIf(!enabled)('profiles coarse and dense sculpt strokes', () => { + const metrics = []; + for (const segments of [1, 707]) { + const source = new PlaneGeometry(100, 100, segments, segments); + source.boundsTree = new MeshBVH(source, { indirect: true }); + const initial = timed(() => new SculptMesh(source, new Matrix4())); + const { result: draft } = initial; + const prepare = timed(() => draft.prepare()); + const mesh = new Mesh(draft.geometry, new MeshBasicMaterial({ side: DoubleSide })); + const raycast = new Raycaster(); + raycast.firstHitOnly = true; + const durations: number[] = []; + for (let dab = 0; dab < 30; dab++) { + const result = timed(() => { + raycast.ray.origin.set(-5 + dab / 3, 0, 30); + raycast.ray.direction.set(0, 0, -1); + const hits: import('three').Intersection[] = []; + draft.raycast(raycast, mesh, hits); + const hit = hits[0]; + if (!hit?.face || hit.faceIndex == null) return false; + return draft.dab({ + brush: 'draw', + point: hit.point, + normal: hit.face.normal, + face: hit.faceIndex, + radius: 3, + strength: 0.2, + detail: 0.5, + minEdge: 0.05, + falloff: 'soft', + }); + }); + expect(result.result).toBe(true); + durations.push(result.ms); + } + const finish = timed(() => draft.finish()); + const geometry = finish.result!; + const bytes = + geometry.index!.array.byteLength + + Object.values(geometry.attributes).reduce( + (sum, attribute) => sum + attribute.array.byteLength, + 0, + ); + const warm = durations.slice(1).sort((a, b) => a - b); + metrics.push({ + triangles: source.index!.count / 3, + setupMs: initial.ms, + prepareMs: prepare.ms, + firstDabMs: durations[0], + warmP95Ms: warm[Math.floor(warm.length * 0.95)], + warmWorstMs: warm.at(-1), + finishMs: finish.ms, + committedMeshBytes: bytes, + }); + geometry.dispose(); + draft.geometry.dispose(); + mesh.material.dispose(); + source.dispose(); + } + writeFileSync( + join(tmpdir(), 'kitbasher-sculpt-benchmark.json'), + JSON.stringify(metrics, null, 2), + ); +}); From 2c11a0e1670987d628259c650b6d1d3212e0df06 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:29:42 -0800 Subject: [PATCH 06/40] (test) Exercise browser sculpting with pen and mask input --- tests/e2e/sculpt.spec.ts | 196 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 tests/e2e/sculpt.spec.ts diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts new file mode 100644 index 0000000..69e9d40 --- /dev/null +++ b/tests/e2e/sculpt.spec.ts @@ -0,0 +1,196 @@ +import { expect, test, type Page } from '@playwright/test'; +import { BoxGeometry } from 'three'; +import { serializeGeometry } from '../../src/core/geometry'; +import { fixture, inStore, openScene, screen } from './helpers/refine'; +import { failOnBrowserErrors } from './helpers/warp-grid'; +import { readSavedScene } from './saved-scene'; + +failOnBrowserErrors(); + +const block = { + ...fixture, + parts: [ + { + ...fixture.parts[0], + name: 'Coarse block', + source: 'block.stl', + geometry: serializeGeometry(new BoxGeometry(8, 6, 4)), + }, + ], +}; + +async function openSculpt(page: Page) { + await openScene(page, block); + await page.locator('.part-select[title="Coarse block"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page + .getByRole('toolbar', { name: 'Assembly tools' }) + .getByRole('button', { name: /^Sculpt\b/ }) + .click(); +} + +const mesh = (page: Page) => + inStore(page, (state) => { + const geometry = state.scene.parts[0].geometry; + const positions = geometry.getAttribute('position'); + let peak = -Infinity; + for (let i = 0; i < positions.count; i++) peak = Math.max(peak, positions.getZ(i)); + return { + positions: Array.from(positions.array), + indices: geometry.index ? Array.from(geometry.index.array) : null, + triangles: (geometry.index?.count ?? positions.count) / 3, + peak, + }; + }); + +async function penTap(page: Page, pressure: number) { + const point = await screen(page, [1, 0, 2]); + const session = await page.context().newCDPSession(page); + try { + const sample = { ...point, pointerType: 'pen' as const, button: 'left' as const }; + await session.send('Input.dispatchMouseEvent', { + ...sample, + type: 'mousePressed', + buttons: 1, + force: pressure, + }); + await page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => resolve())), + ); + await session.send('Input.dispatchMouseEvent', { + ...sample, + type: 'mouseReleased', + buttons: 0, + }); + } finally { + await session.detach(); + } +} + +test('draws into a coarse face with pen pressure and undoes topology with displacement', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + await penTap(page, 0.25); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + const light = await mesh(page); + expect(light.triangles).toBeGreaterThan(before.triangles); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(light.peak); + const heavy = await mesh(page); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await page.keyboard.press('ControlOrMeta+Shift+z'); + await expect.poll(() => mesh(page)).toEqual(heavy); +}); + +test('cancels an active stroke and reopens the completed stroke from disk', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.mouse.move(point.x, point.y); + await page.mouse.down(); + await page.mouse.move(point.x + 12, point.y, { steps: 3 }); + await expect + .poll(() => + page.evaluate(async () => { + const url = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/xr\/part-meshes\.ts(?:\?.*)?$/.test(url))!; + const { partMeshes } = await import(url); + const geometry = partMeshes.get('block').geometry; + return Math.min( + geometry.drawRange.count, + geometry.index?.count ?? geometry.getAttribute('position').count, + ); + }), + ) + .toBeGreaterThan(before.triangles * 3); + expect(await mesh(page)).toEqual(before); + await page.keyboard.press('Escape'); + await page.mouse.up(); + expect(await mesh(page)).toEqual(before); + expect(await inStore(page, (state) => state.sculpt?.past.length)).toBe(0); + await penTap(page, 0.8); + await expect.poll(async () => (await mesh(page)).triangles).toBeGreaterThan(before.triangles); + const completed = await mesh(page); + const downloading = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Save scene', exact: true }).click(); + const file = await readSavedScene((await (await downloading).path())!); + const oldGeometry = await inStore(page, (state) => state.scene.parts[0].geometry.uuid); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'sculpt.kitbash', + mimeType: 'application/octet-stream', + buffer: file.bytes, + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await expect + .poll(() => inStore(page, (state) => state.scene.parts[0].geometry.uuid)) + .not.toBe(oldGeometry); + await expect.poll(() => mesh(page)).toEqual(completed); +}); + +test('a fully inverted mask protects the coarse surface until cleared', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await page.getByRole('button', { name: /invert mask/i }).click(); + await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('draw'); + await penTap(page, 0.9); + expect(await mesh(page)).toEqual(before); + await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await page.getByRole('button', { name: /clear mask/i }).click(); + await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('draw'); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + +test('mask paint subdivides without displacement and restores weights with undo and redo', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + const weights = () => inStore(page, (state) => Array.from(state.sculpt?.mask ?? [])); + await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await penTap(page, 0.8); + await expect.poll(async () => (await weights()).some((weight) => weight > 0)).toBe(true); + const painted = await mesh(page); + expect(painted.triangles).toBeGreaterThan(before.triangles); + expect(painted.peak).toEqual(before.peak); + const protection = await weights(); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + expect(await weights()).toEqual([]); + await page.keyboard.press('ControlOrMeta+Shift+z'); + await expect.poll(() => mesh(page)).toEqual(painted); + expect(await weights()).toEqual(protection); +}); + +test('applies Clay Buildup and Inflate and keeps their falloff settings independent', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + const brush = page.getByRole('combobox', { name: 'Brush', exact: true }); + const falloff = page.getByRole('combobox', { name: 'Falloff' }); + await page.getByText('Advanced brush settings', { exact: true }).click(); + await brush.selectOption({ label: 'Clay Buildup' }); + await falloff.selectOption('hard'); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await brush.selectOption({ label: 'Inflate/Deflate' }); + await expect(falloff).toHaveValue('soft'); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + await brush.selectOption({ label: 'Clay Buildup' }); + await expect(falloff).toHaveValue('hard'); + await page.getByRole('button', { name: 'Reset brush settings' }).click(); + await expect(falloff).toHaveValue('soft'); +}); From 6265881db71a5fceb178c853de4640ef34768537 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:30:51 -0800 Subject: [PATCH 07/40] (feat) Add adaptive sculpt mesh editing --- src/core/sculpt-mesh.ts | 1049 ++++++++++++++++++++++++++++++++ tests/unit/sculpt-mesh.test.ts | 240 ++++++++ 2 files changed, 1289 insertions(+) create mode 100644 src/core/sculpt-mesh.ts create mode 100644 tests/unit/sculpt-mesh.test.ts diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts new file mode 100644 index 0000000..6f6ee85 --- /dev/null +++ b/src/core/sculpt-mesh.ts @@ -0,0 +1,1049 @@ +import { + BackSide, + Box3, + BufferAttribute, + BufferGeometry, + DynamicDrawUsage, + FrontSide, + MathUtils, + Matrix4, + Mesh, + Quaternion, + Sphere, + Triangle, + Vector3, + type Intersection, + type Raycaster, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import type { SculptBrush } from './types'; + +export type { SculptBrush } from './types'; + +interface SculptHit { + point: Vector3; + normal: Vector3; + face: number; + tangent?: Vector3; + grab?: Vector3; +} + +export interface SculptDab extends SculptHit { + radius: number; + strength: number; + detail: number; + minEdge: number; + brush: SculptBrush; + falloff: 'soft' | 'linear' | 'hard'; + inverted?: boolean; + pinch?: number; + softenMask?: boolean; + aspect?: number; + mirror?: SculptHit; +} + +type Face = [number, number, number]; +type Attribute = ReturnType; +type AttributeArray = BufferAttribute['array']; +interface Split { + vertexCount: number; + weld: number; + faces: { id: number; previous: Face; child: number }[]; +} +interface SculptSample { + footprint: Footprint; + weight: number; + mirrored: boolean; +} +interface Incidence { + weldOf: Uint32Array; + representative: Uint32Array; + faceStart: Uint32Array; + incidentFaces: Uint32Array; + edits: ReadonlyMap>; +} + +let latestIncidence: + | { + source: WeakRef; + position: Attribute; + index: BufferAttribute | null; + incidence: Incidence; + } + | undefined; + +function rememberIncidence(source: BufferGeometry, incidence: Incidence) { + latestIncidence = { + source: new WeakRef(source), + position: source.getAttribute('position'), + index: source.index, + incidence, + }; +} + +const maxSplitsPerDab = 192; +const maxFacesPerPatch = 8192; +const maskName = 'sculptMask'; + +/** Exact coincident vertices share connectivity without welding a nearby thin shell. */ +function weldVertices(position: Attribute) { + const capacity = 2 ** Math.ceil(Math.log2(Math.max(16, position.count * 1.5))); + const table = new Uint32Array(capacity); + const weldOf = new Uint32Array(position.count); + const representative = new Uint32Array(position.count); + const coordinate = new Float64Array(1); + const bits = new Uint32Array(coordinate.buffer); + function hash(value: number) { + coordinate[0] = value || 0; + return Math.imul(bits[0], 0x45d9f3b) ^ bits[1]; + } + let count = 0; + for (let vertex = 0; vertex < position.count; vertex++) { + const x = position.getX(vertex); + const y = position.getY(vertex); + const z = position.getZ(vertex); + let slot = (hash(x) ^ Math.imul(hash(y), 31) ^ Math.imul(hash(z), 961)) & (capacity - 1); + while (table[slot]) { + const candidate = representative[table[slot] - 1]; + if ( + position.getX(candidate) === x && + position.getY(candidate) === y && + position.getZ(candidate) === z + ) + break; + slot = (slot + 1) & (capacity - 1); + } + if (!table[slot]) { + representative[count] = vertex; + table[slot] = ++count; + } + weldOf[vertex] = table[slot] - 1; + } + return { weldOf, representative: representative.slice(0, count) }; +} + +function resize(array: T, length: number): T { + const ArrayType = array.constructor as new (length: number) => T; + const result = new ArrayType(length); + result.set(array.subarray(0, length)); + return result; +} + +function renderAttribute(source: Attribute) { + const attribute = source.clone(); + return attribute.setUsage(DynamicDrawUsage); +} + +class Footprint { + readonly normal: Vector3; + readonly tangent: Vector3; + readonly cross: Vector3; + private readonly aspect: number; + private readonly triangle = new Triangle(); + private readonly offset = new Vector3(); + + constructor( + readonly hit: SculptHit, + readonly radius: number, + aspect: number, + ) { + this.aspect = MathUtils.clamp(aspect, 0.1, 1); + this.normal = hit.normal.clone().normalize(); + this.tangent = hit.tangent?.clone() ?? new Vector3(); + this.tangent.addScaledVector(this.normal, -this.tangent.dot(this.normal)); + if (this.tangent.lengthSq() < 1e-8) { + const axis = Math.abs(this.normal.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0); + this.tangent.crossVectors(axis, this.normal); + } + this.tangent.normalize(); + this.cross = new Vector3().crossVectors(this.normal, this.tangent); + } + + private project(point: Vector3, target: Vector3) { + const offset = this.offset.subVectors(point, this.hit.point); + return target.set( + offset.dot(this.tangent), + offset.dot(this.cross) / this.aspect, + offset.dot(this.normal), + ); + } + + overlaps(a: Vector3, b: Vector3, c: Vector3) { + const triangle = this.triangle; + this.project(a, triangle.a); + this.project(b, triangle.b); + this.project(c, triangle.c); + return triangle.closestPointToPoint(origin, this.offset).lengthSq() < this.radius ** 2; + } + + distance(point: Vector3) { + return this.project(point, this.offset).length() / this.radius; + } +} + +const origin = new Vector3(); + +export class SculptMesh { + readonly geometry = new BufferGeometry(); + detailLimited = false; + + private readonly world: Matrix4; + private readonly inverse: Matrix4; + private readonly orientation: number; + private readonly source: BufferGeometry; + private readonly initialVertices: number; + private readonly initialFaces: number; + private readonly growthLimit: number; + private vertexCount: number; + private faceCount: number; + private weldCount = 0; + private weldOf = new Uint32Array(0); + private representative = new Uint32Array(0); + private faceStart = new Uint32Array(0); + private incidentFaces = new Uint32Array(0); + private baseEdits: ReadonlyMap> = new Map(); + private incidentEdits = new Map>(); + private readonly editedFaces = new Set(); + private grabSamples: Map | undefined; + private changed = false; + + constructor(source: BufferGeometry, matrixWorld: Matrix4, mask?: Float32Array) { + this.source = source; + this.world = matrixWorld.clone(); + this.inverse = matrixWorld.clone().invert(); + this.orientation = Math.sign(matrixWorld.determinant()); + this.initialVertices = this.vertexCount = source.getAttribute('position').count; + this.initialFaces = this.faceCount = Math.floor((source.index?.count ?? this.vertexCount) / 3); + this.growthLimit = Math.min(65_536, Math.max(4096, Math.ceil(this.initialFaces * 0.2))); + this.geometry.name = source.name; + this.geometry.userData = { ...source.userData }; + for (const [name, attribute] of Object.entries(source.attributes)) + this.geometry.setAttribute(name, renderAttribute(attribute)); + const indices = new Uint32Array(this.faceCount * 3); + for (let corner = 0; corner < indices.length; corner++) + indices[corner] = source.index?.getX(corner) ?? corner; + this.geometry.setIndex(new BufferAttribute(indices, 1).setUsage(DynamicDrawUsage)); + this.geometry.groups = source.groups.map((group) => ({ ...group })); + this.geometry.setDrawRange(0, indices.length); + const weights = new Float32Array(this.vertexCount); + if (mask) weights.set(mask.subarray(0, this.vertexCount)); + this.geometry.setAttribute( + maskName, + new BufferAttribute(weights, 1).setUsage(DynamicDrawUsage), + ); + this.geometry.boundingBox = source.boundingBox?.clone() ?? null; + this.geometry.boundingSphere = source.boundingSphere?.clone() ?? null; + if (!this.geometry.boundingBox) this.geometry.computeBoundingBox(); + if (!this.geometry.boundingSphere) this.geometry.computeBoundingSphere(); + } + + getMask() { + return (this.geometry.getAttribute(maskName).array as Float32Array).slice(0, this.vertexCount); + } + + /** Build or reuse incidence before pen-down when the controller has an idle opportunity. */ + prepare() { + if (this.faceStart.length) return; + const cached = latestIncidence; + if ( + cached?.source.deref() === this.source && + cached.position === this.source.getAttribute('position') && + cached.index === this.source.index + ) { + const { weldOf, representative, faceStart, incidentFaces, edits } = cached.incidence; + this.weldOf = weldOf; + this.representative = representative; + this.weldCount = representative.length; + this.faceStart = faceStart; + this.incidentFaces = incidentFaces; + this.baseEdits = edits; + return; + } + this.buildIncidence(); + rememberIncidence(this.source, { + weldOf: this.weldOf, + representative: this.representative, + faceStart: this.faceStart, + incidentFaces: this.incidentFaces, + edits: this.baseEdits, + }); + } + + /** Unedited faces remain in the source index. Test edited faces at their live positions. */ + raycast(raycaster: Raycaster, mesh: Mesh, hits: Intersection[]) { + const tree = this.source.boundsTree; + if (!(tree instanceof MeshBVH) || Array.isArray(mesh.material)) { + const found: Intersection[] = []; + Mesh.prototype.raycast.call(mesh, raycaster, found); + found.sort((a, b) => a.distance - b.distance); + hits.push(...(raycaster.firstHitOnly ? found.slice(0, 1) : found)); + return; + } + const world = mesh.matrixWorld; + const ray = raycaster.ray.clone().applyMatrix4(this.inverse); + if (this.geometry.boundingBox && !ray.intersectsBox(this.geometry.boundingBox)) return; + const worldStep = ray.at(1, new Vector3()).applyMatrix4(world).distanceTo(raycaster.ray.origin); + const near = raycaster.near / worldStep; + const far = raycaster.far / worldStep; + const side = mesh.material.side; + let sourceHits: Intersection[] = []; + if (raycaster.firstHitOnly) { + const first = tree.raycastFirst(ray, side, near, far); + if (first) + sourceHits = this.editedFaces.has(first.faceIndex!) + ? tree.raycast(ray, side, near, far) + : [first]; + } else sourceHits = tree.raycast(ray, side, near, far); + const found: Intersection[] = []; + for (const hit of sourceHits) { + if (this.editedFaces.has(hit.faceIndex!)) continue; + hit.point.applyMatrix4(world); + hit.distance = hit.point.distanceTo(raycaster.ray.origin); + hit.object = mesh; + found.push(hit); + } + + const position = this.attribute('position'); + const a = new Vector3(), + b = new Vector3(), + c = new Vector3(), + point = new Vector3(); + for (const faceIndex of this.editedFaces) { + const [ia, ib, ic] = this.face(faceIndex); + a.fromBufferAttribute(position, ia); + b.fromBufferAttribute(position, ib); + c.fromBufferAttribute(position, ic); + const contact = + side === BackSide + ? ray.intersectTriangle(c, b, a, true, point) + : ray.intersectTriangle(a, b, c, side === FrontSide, point); + if (!contact) continue; + point.applyMatrix4(world); + const distance = point.distanceTo(raycaster.ray.origin); + if (distance < raycaster.near || distance > raycaster.far) continue; + found.push({ + distance, + point: point.clone(), + object: mesh, + faceIndex, + face: { + a: ia, + b: ib, + c: ic, + normal: Triangle.getNormal(a, b, c, new Vector3()), + materialIndex: 0, + }, + }); + } + found.sort((a, b) => a.distance - b.distance); + hits.push(...(raycaster.firstHitOnly ? found.slice(0, 1) : found)); + } + + invertMask() { + return this.replaceMask((value) => 1 - value); + } + + clearMask() { + return this.replaceMask(() => 0); + } + + private replaceMask(replace: (value: number) => number) { + const attribute = this.attribute(maskName); + let changed = false; + for (let vertex = 0; vertex < this.vertexCount; vertex++) { + const value = attribute.getX(vertex); + const next = Math.fround(replace(value)); + if (value === next) continue; + attribute.setX(vertex, next); + changed = true; + } + if (changed) { + attribute.addUpdateRange(0, this.vertexCount); + attribute.needsUpdate = true; + } + return changed; + } + + private attribute(name: string) { + return this.geometry.getAttribute(name) as BufferAttribute; + } + + private face(id: number): Face { + const index = this.geometry.index!.array; + const start = id * 3; + return [index[start], index[start + 1], index[start + 2]]; + } + + private buildIncidence() { + const { weldOf, representative } = weldVertices(this.attribute('position')); + this.weldOf = weldOf; + this.representative = representative; + this.weldCount = representative.length; + const faces = this.geometry.index!.array.subarray(0, this.faceCount * 3); + const starts = new Uint32Array(this.weldCount + 1); + for (const vertex of faces) { + const weld = weldOf[vertex]; + starts[weld + 1]++; + // Use a referenced copy when a source contains an unused vertex at the same position. + representative[weld] = vertex; + } + for (let weld = 0; weld < this.weldCount; weld++) starts[weld + 1] += starts[weld]; + const next = starts.slice(0, -1); + this.incidentFaces = new Uint32Array(faces.length); + for (let corner = 0; corner < faces.length; corner++) + this.incidentFaces[next[weldOf[faces[corner]]]++] = Math.floor(corner / 3); + this.faceStart = starts; + } + + private incidence(weld: number): Iterable { + const edited = this.incidentEdits.get(weld) ?? this.baseEdits.get(weld); + if (edited) return edited; + if (weld + 1 >= this.faceStart.length) return []; + return this.incidentFaces.subarray(this.faceStart[weld], this.faceStart[weld + 1]); + } + + private editIncidence(id: number, vertices: Face, add: boolean) { + for (const vertex of vertices) { + const weld = this.weldOf[vertex]; + let faces = this.incidentEdits.get(weld); + if (!faces) this.incidentEdits.set(weld, (faces = new Set(this.incidence(weld)))); + if (add) faces.add(id); + else faces.delete(id); + } + } + + private worldAt(vertex: number, target = new Vector3()) { + return target.fromBufferAttribute(this.attribute('position'), vertex).applyMatrix4(this.world); + } + + private maskAt(weld: number) { + let protection = 0; + const attribute = this.attribute(maskName); + for (const face of this.incidence(weld)) { + for (const vertex of this.face(face)) + if (this.weldOf[vertex] === weld) protection = Math.max(protection, attribute.getX(vertex)); + } + return protection; + } + + private neighbors(a: number, b: number) { + const faces: number[] = []; + const index = this.geometry.index!.array; + const weldOf = this.weldOf; + let previous = -1; + for (const id of this.incidence(a)) { + if (previous === id) continue; + previous = id; + const corner = id * 3; + if ( + weldOf[index[corner]] === b || + weldOf[index[corner + 1]] === b || + weldOf[index[corner + 2]] === b + ) + faces.push(id); + if (faces.length > 2) break; + } + return faces; + } + + private edgeSlot(vertices: Face, a: number, b: number) { + return vertices.findIndex((vertex, i) => { + const u = this.weldOf[vertex]; + const v = this.weldOf[vertices[(i + 1) % 3]]; + return (u === a && v === b) || (u === b && v === a); + }); + } + + private validFace(vertices: Face) { + const a = this.worldAt(vertices[0]); + const ab = this.worldAt(vertices[1]).sub(a); + const ac = this.worldAt(vertices[2]).sub(a); + const area = ab.cross(ac).lengthSq(); + return Number.isFinite(area) && area > 0; + } + + /** An edge with a third incident face, reversed adjacency, or a degenerate face is a boundary. */ + private splittableFaces(a: number, b: number) { + const faces = this.neighbors(a, b); + if (!faces.length || faces.length > 2) return []; + const first = this.face(faces[0]); + const start = this.edgeSlot(first, a, b); + if (start === -1 || !this.validFace(first)) return []; + if (faces.length === 2) { + const second = this.face(faces[1]); + const end = this.edgeSlot(second, a, b); + if ( + end === -1 || + this.weldOf[first[start]] === this.weldOf[second[end]] || + !this.validFace(second) + ) + return []; + } + return faces; + } + + private overlaps(id: number, footprint: Footprint) { + const vertices = this.face(id); + const a = this.worldAt(vertices[0]); + const b = this.worldAt(vertices[1]); + const c = this.worldAt(vertices[2]); + const normal = new Vector3().subVectors(b, a).cross(new Vector3().subVectors(c, a)); + const facing = normal.dot(footprint.normal) * this.orientation; + return Number.isFinite(facing) && facing > 0 && footprint.overlaps(a, b, c); + } + + private patch(footprint: Footprint) { + const faces = new Set(); + const seed = footprint.hit.face; + if (seed < 0 || seed >= this.faceCount || !Number.isInteger(seed)) return faces; + const visited = new Set([seed]); + const queue = [seed]; + for (let i = 0; i < queue.length && i < maxFacesPerPatch; i++) { + const face = queue[i]; + if (!this.overlaps(face, footprint)) continue; + faces.add(face); + const vertices = this.face(face); + for (let edge = 0; edge < 3; edge++) { + const a = this.weldOf[vertices[edge]]; + const b = this.weldOf[vertices[(edge + 1) % 3]]; + const incidents = this.splittableFaces(a, b); + if (incidents.length !== 2) continue; + for (const neighbor of incidents) { + if (visited.has(neighbor)) continue; + visited.add(neighbor); + queue.push(neighbor); + } + } + } + return faces; + } + + private setFace(id: number, vertices: Face) { + const index = this.geometry.index!; + index.array.set(vertices, id * 3); + index.addUpdateRange(id * 3, 3); + } + + private ensureCapacity(vertices: number, faces: number) { + const position = this.attribute('position'); + const index = this.geometry.index!; + if (vertices <= position.array.length / 3 && faces <= index.array.length / 3) return; + // Three's GPU buffers cannot be resized. Release them only when the reserved capacity grows. + this.geometry.dispose(); + const vertexCapacity = Math.max( + vertices, + Math.ceil((position.array.length / 3) * 1.25), + this.initialVertices + 512, + ); + const faceCapacity = Math.max( + faces, + Math.ceil((index.array.length / 3) * 1.25), + this.initialFaces + 512, + ); + for (const [name, attribute] of Object.entries(this.geometry.attributes)) { + const old = attribute as BufferAttribute; + const next = new BufferAttribute( + resize(old.array, vertexCapacity * old.itemSize), + old.itemSize, + old.normalized, + ); + next.name = old.name; + this.geometry.setAttribute(name, next.setUsage(DynamicDrawUsage)); + } + this.geometry.setIndex( + new BufferAttribute(resize(index.array, faceCapacity * 3), 1).setUsage(DynamicDrawUsage), + ); + this.weldOf = resize(this.weldOf, vertexCapacity); + this.representative = resize(this.representative, vertexCapacity); + } + + private syncCounts() { + for (const attribute of Object.values(this.geometry.attributes)) + Object.assign(attribute, { count: this.vertexCount }); + const index = this.geometry.index!; + Object.assign(index, { count: this.faceCount * 3 }); + this.geometry.setDrawRange(0, this.faceCount * 3); + } + + private splitEdge(a: number, b: number, faces: number[]) { + const edit: Split = { vertexCount: this.vertexCount, weld: this.weldCount, faces: [] }; + this.ensureCapacity(this.vertexCount + faces.length, this.faceCount + faces.length); + const weld = this.weldCount++; + const edges: { a: number; b: number; vertex: number }[] = []; + const protection = (this.maskAt(a) + this.maskAt(b)) * 0.5; + for (const id of faces) { + const previous = this.face(id); + const start = this.edgeSlot(previous, a, b); + const u = previous[start]; + const v = previous[(start + 1) % 3]; + const w = previous[(start + 2) % 3]; + const repeated = edges.find((edge) => edge.a === v && edge.b === u); + const midpoint = repeated?.vertex ?? this.vertexCount++; + if (!repeated) { + for (const attr of Object.values(this.geometry.attributes) as BufferAttribute[]) { + for (let axis = 0; axis < attr.itemSize; axis++) + attr.setComponent( + midpoint, + axis, + (attr.getComponent(u, axis) + attr.getComponent(v, axis)) * 0.5, + ); + attr.addUpdateRange(midpoint * attr.itemSize, attr.itemSize); + } + const normals = this.geometry.getAttribute('normal'); + if (normals) { + const normal = new Vector3().fromBufferAttribute(normals, midpoint).normalize(); + normals.setXYZ(midpoint, normal.x, normal.y, normal.z); + } + this.attribute(maskName).setX(midpoint, protection); + this.weldOf[midpoint] = weld; + this.representative[weld] = midpoint; + edges.push({ a: u, b: v, vertex: midpoint }); + } + const left: Face = [u, midpoint, w]; + const right: Face = [midpoint, v, w]; + this.editIncidence(id, previous, false); + const child = this.faceCount++; + this.setFace(id, left); + this.setFace(child, right); + this.editIncidence(id, left, true); + this.editIncidence(child, right, true); + this.appendGroups(id, child); + edit.faces.push({ id, previous, child }); + } + return edit; + } + + private appendGroups(id: number, child: number) { + const groups = this.geometry.groups; + const matching = groups.filter(({ start, count }) => id * 3 >= start && id * 3 < start + count); + for (const group of matching) this.geometry.addGroup(child * 3, 3, group.materialIndex); + } + + private rollback(splits: Split[], groupCount: number) { + for (let i = splits.length - 1; i >= 0; i--) { + const { vertexCount, weld, faces } = splits[i]; + for (const { id, previous, child } of faces) { + this.editIncidence(id, this.face(id), false); + this.editIncidence(child, this.face(child), false); + this.setFace(id, previous); + this.editIncidence(id, previous, true); + } + this.incidentEdits.delete(weld); + this.vertexCount = vertexCount; + this.weldCount = weld; + this.faceCount -= faces.length; + } + this.geometry.groups.length = groupCount; + this.syncCounts(); + } + + private refine(settings: SculptDab, brushes: { footprint: Footprint; faces: Set }[]) { + const splits: Split[] = []; + const target = Math.max( + settings.minEdge * 2, + settings.radius * MathUtils.lerp(0.95, 0.22, settings.detail), + ); + const minEdgeSquared = (settings.minEdge ?? 0) ** 2; + const queue = [...new Set(brushes.flatMap(({ faces }) => [...faces]))]; + for (let i = 0; i < queue.length; i++) { + const id = queue[i]; + const active = brushes.filter( + ({ faces, footprint }) => faces.has(id) && this.overlaps(id, footprint), + ); + if (!active.length) continue; + const vertices = this.face(id); + const points = vertices.map((vertex) => this.worldAt(vertex)); + const protectedFace = + settings.brush !== 'mask' && + vertices.every((vertex) => this.maskAt(this.weldOf[vertex]) === 1); + if (protectedFace) continue; + let longest = target ** 2; + let choice: { a: number; b: number; faces: number[] } | undefined; + for (let edge = 0; edge < 3; edge++) { + const next = (edge + 1) % 3; + const length = points[edge].distanceToSquared(points[next]); + if (length <= longest) continue; + const a = this.weldOf[vertices[edge]]; + const b = this.weldOf[vertices[next]]; + const faces = this.splittableFaces(a, b); + if (!faces.length) continue; + const middle = points[edge].clone().lerp(points[next], 0.5); + if ( + faces.some((incident) => + this.face(incident).some((vertex) => { + const weld = this.weldOf[vertex]; + return ( + weld !== a && + weld !== b && + this.worldAt(vertex).distanceToSquared(middle) < minEdgeSquared + ); + }), + ) + ) + continue; + longest = length; + choice = { a, b, faces }; + } + if (!choice) continue; + if (this.faceCount + choice.faces.length > this.initialFaces + this.growthLimit) { + this.detailLimited = true; + break; + } + if (splits.length >= maxSplitsPerDab) break; + const split = this.splitEdge(choice.a, choice.b, choice.faces); + splits.push(split); + for (const { id: parent, child } of split.faces) { + for (const { faces } of brushes) if (faces.has(parent)) faces.add(child); + queue.push(parent, child); + } + } + for (const { faces, footprint } of brushes) + for (const id of faces) if (!this.overlaps(id, footprint)) faces.delete(id); + return splits; + } + + private weight(footprint: Footprint, point: Vector3, settings: SculptDab) { + const distance = footprint.distance(point); + if (!(distance < 1)) return 0; + const weight = 1 - distance; + switch (settings.falloff) { + case 'linear': + return weight; + case 'hard': + return 1; + case 'soft': + return weight * weight * (3 - 2 * weight); + } + } + + private neighborsOf(weld: number, footprint: Footprint) { + const neighbors = new Set(); + for (const id of this.incidence(weld)) { + const face = this.face(id); + const a = this.worldAt(face[0]); + const b = this.worldAt(face[1]).sub(a); + const c = this.worldAt(face[2]).sub(a); + if (!(b.cross(c).dot(footprint.normal) * this.orientation > 0)) continue; + for (const vertex of face) { + const neighbor = this.weldOf[vertex]; + if (neighbor !== weld && this.splittableFaces(weld, neighbor).length) + neighbors.add(neighbor); + } + } + return neighbors; + } + + private surfaceNormal(weld: number) { + const normal = new Vector3(); + const seen = new Set(); + for (const id of this.incidence(weld)) { + if (seen.has(id)) continue; + seen.add(id); + const face = this.face(id); + const a = this.worldAt(face[0]); + const b = this.worldAt(face[1]).sub(a); + const c = this.worldAt(face[2]).sub(a); + normal.add(b.cross(c)); + } + return normal.multiplyScalar(this.orientation).normalize(); + } + + private displacement( + weld: number, + point: Vector3, + footprint: Footprint, + settings: SculptDab, + strength: number, + mirrored: boolean, + ) { + const { hit, normal } = footprint; + const sign = settings.inverted ? -1 : 1; + const height = new Vector3().subVectors(point, hit.point).dot(normal); + const depth = settings.radius * strength; + switch (settings.brush) { + case 'draw': + return normal.clone().multiplyScalar(sign * depth * 0.2); + case 'inflate': + return this.surfaceNormal(weld).multiplyScalar(sign * depth * 0.2); + case 'grab': + return ( + (mirrored ? settings.mirror?.grab : settings.grab)?.clone().multiplyScalar(strength) ?? + new Vector3() + ); + case 'flatten': + return normal.clone().multiplyScalar(-height * strength); + case 'clay': { + const layer = Math.max(0, settings.radius * 0.16 - sign * height); + return normal + .clone() + .multiplyScalar(sign * Math.min(layer, settings.radius * 0.22) * strength); + } + case 'crease': { + const toward = new Vector3().subVectors(hit.point, point); + toward.addScaledVector(normal, -toward.dot(normal)); + if (hit.tangent) toward.addScaledVector(footprint.tangent, -toward.dot(footprint.tangent)); + return toward + .multiplyScalar(MathUtils.clamp(settings.pinch ?? 0.5, 0, 1) * strength * 0.4) + .addScaledVector(normal, -sign * depth * 0.22); + } + case 'smooth': { + const neighbors = this.neighborsOf(weld, footprint); + if (neighbors.size < 2) return new Vector3(); + const center = new Vector3(); + for (const neighbor of neighbors) center.add(this.worldAt(this.representative[neighbor])); + center.divideScalar(neighbors.size).sub(point); + const surface = this.surfaceNormal(weld); + return surface.multiplyScalar(center.dot(surface) * strength * 0.65); + } + case 'mask': + return new Vector3(); + } + } + + private renderVertices(weld: number) { + const vertices = new Set(); + for (const id of this.incidence(weld)) + for (const vertex of this.face(id)) if (this.weldOf[vertex] === weld) vertices.add(vertex); + return vertices; + } + + private localFaceCross(id: number) { + const [ia, ib, ic] = this.face(id); + const position = this.attribute('position'); + const a = new Vector3().fromBufferAttribute(position, ia); + const cross = new Vector3() + .fromBufferAttribute(position, ib) + .sub(a) + .cross(new Vector3().fromBufferAttribute(position, ic).sub(a)); + return Number.isFinite(cross.lengthSq()) ? cross : cross.set(0, 0, 0); + } + + private deform(moves: Map) { + const position = this.attribute('position'); + const outputNormals = this.geometry.getAttribute('normal') as BufferAttribute | undefined; + const changedFaces = new Set(); + for (const weld of moves.keys()) + for (const face of this.incidence(weld)) changedFaces.add(face); + for (const face of changedFaces) this.editedFaces.add(face); + const normals = new Map(); + const renderFaces = new Map>(); + const faceBefore = new Map(); + if (outputNormals) { + for (const face of changedFaces) { + for (const vertex of this.face(face)) { + if (renderFaces.has(vertex)) continue; + const fan = new Set(); + for (const incident of this.incidence(this.weldOf[vertex])) { + if (!this.face(incident).includes(vertex)) continue; + fan.add(incident); + if (!faceBefore.has(incident)) faceBefore.set(incident, this.localFaceCross(incident)); + } + renderFaces.set(vertex, fan); + const normal = new Vector3(); + for (const incident of fan) normal.add(faceBefore.get(incident)!); + normals.set(vertex, normal.normalize()); + } + } + } + const bounds = this.geometry.boundingBox; + const sphere = this.geometry.boundingSphere; + for (const [weld, local] of moves) { + for (const vertex of this.renderVertices(weld)) { + position.setXYZ(vertex, local.x, local.y, local.z); + position.addUpdateRange(vertex * 3, 3); + } + bounds?.expandByPoint(local); + if (sphere) sphere.radius = Math.max(sphere.radius, local.distanceTo(sphere.center)); + } + position.needsUpdate = true; + if (outputNormals) { + const after = new Map(); + const rotate = new Quaternion(); + const normal = new Vector3(); + for (const [vertex, fan] of renderFaces) { + const current = new Vector3(); + for (const face of fan) { + if (!after.has(face)) after.set(face, this.localFaceCross(face)); + current.add(after.get(face)!); + } + const previous = normals.get(vertex)!; + if (!previous.lengthSq() || !current.lengthSq()) continue; + rotate.setFromUnitVectors(previous, current.normalize()); + normal.fromBufferAttribute(outputNormals, vertex).applyQuaternion(rotate).normalize(); + outputNormals.setXYZ(vertex, normal.x, normal.y, normal.z); + outputNormals.addUpdateRange(vertex * 3, 3); + } + outputNormals.needsUpdate = true; + } + } + + dab(settings: SculptDab) { + if (!(settings.radius > 0 && settings.strength > 0) || !this.orientation) return false; + if (settings.brush !== 'grab') this.grabSamples = undefined; + else if (!settings.grab?.lengthSq() && !settings.mirror?.grab?.lengthSq()) return false; + this.prepare(); + const groupCount = this.geometry.groups.length; + let samples = this.grabSamples; + let splits: Split[] = []; + if (!samples) { + const hits: SculptHit[] = [settings]; + if (settings.mirror) hits.push(settings.mirror); + const brushes = hits.map((hit, index) => { + const footprint = new Footprint(hit, settings.radius, settings.aspect ?? 1); + return { footprint, faces: this.patch(footprint), mirrored: index === 1 }; + }); + splits = this.refine(settings, brushes); + samples = new Map(); + for (const { footprint, faces, mirrored } of brushes) { + for (const face of faces) { + for (const vertex of this.face(face)) { + const weld = this.weldOf[vertex]; + const weight = this.weight(footprint, this.worldAt(vertex), settings); + if (weight > (samples.get(weld)?.weight ?? 0)) + samples.set(weld, { footprint, weight, mirrored }); + } + } + } + } + const moves = new Map(); + const masks = new Map(); + for (const [weld, { footprint, weight, mirrored }] of samples) { + const protection = this.maskAt(weld); + const strength = Math.min(1, settings.strength) * weight; + if (settings.brush === 'mask') { + let next = protection + (settings.inverted ? -strength : strength); + if (settings.softenMask) { + const neighbors = this.neighborsOf(weld, footprint); + if (!neighbors.size) continue; + let mean = 0; + for (const neighbor of neighbors) mean += this.maskAt(neighbor); + next = MathUtils.lerp(protection, mean / neighbors.size, strength); + } + next = Math.fround(MathUtils.clamp(next, 0, 1)); + if (next !== protection) masks.set(weld, next); + } else if (protection < 1) { + const vertex = this.representative[weld]; + const point = this.worldAt(vertex); + const displacement = this.displacement( + weld, + point, + footprint, + settings, + strength * (1 - protection), + mirrored, + ); + if (!(displacement.lengthSq() > 1e-24)) continue; + const local = point.add(displacement).applyMatrix4(this.inverse); + const before = new Vector3().fromBufferAttribute(this.attribute('position'), vertex); + if (![local.x, local.y, local.z].every(Number.isFinite)) continue; + if (this.attribute('position').array instanceof Float32Array) + local.set(Math.fround(local.x), Math.fround(local.y), Math.fround(local.z)); + if (!local.equals(before)) moves.set(weld, local); + } + } + if (!moves.size && !masks.size) { + if (splits.length) this.rollback(splits, groupCount); + return false; + } + if (settings.brush === 'grab') this.grabSamples = samples; + if (splits.length) { + this.syncCounts(); + for (const attribute of Object.values(this.geometry.attributes) as BufferAttribute[]) + attribute.needsUpdate = true; + this.geometry.index!.needsUpdate = true; + for (const split of splits) + for (const { id, child } of split.faces) { + this.editedFaces.add(id); + this.editedFaces.add(child); + } + } + if (moves.size) this.deform(moves); + if (masks.size) { + const mask = this.attribute(maskName); + for (const [weld, value] of masks) { + for (const vertex of this.renderVertices(weld)) { + mask.setX(vertex, value); + mask.addUpdateRange(vertex, 1); + } + } + mask.needsUpdate = true; + } + this.changed ||= moves.size > 0 || splits.length > 0; + return true; + } + + private refitPicking(geometry: BufferGeometry) { + const sourceTree = this.source.boundsTree; + if ( + !(sourceTree instanceof MeshBVH) || + this.faceCount !== this.initialFaces || + !this.editedFaces.size + ) + return; + const dirtyBounds = new Box3(); + const sourcePosition = this.source.getAttribute('position'); + const point = new Vector3(); + for (const face of this.editedFaces) + for (const vertex of this.face(face)) + dirtyBounds.expandByPoint(point.fromBufferAttribute(sourcePosition, vertex)); + const nodes = new Set(); + sourceTree.shapecast({ + intersectsBounds: (bounds, _leaf, _score, _depth, node) => { + if (!bounds.intersectsBox(dirtyBounds)) return false; + nodes.add(node); + return true; + }, + }); + const data = MeshBVH.serialize(sourceTree, { cloneBuffers: false }); + const roots = data.roots.map((root) => root.slice(0)); + const tree = MeshBVH.deserialize({ ...data, roots }, geometry, { setIndex: false }); + tree.refit(nodes); + geometry.boundsTree = tree; + } + + finish() { + if (!this.changed) return null; + const geometry = new BufferGeometry(); + geometry.name = this.geometry.name; + geometry.userData = { ...this.geometry.userData }; + for (const [name, attribute] of Object.entries(this.geometry.attributes)) { + if (name === maskName) continue; + const { array, itemSize, normalized } = attribute; + geometry.setAttribute( + name, + new BufferAttribute(array.slice(0, this.vertexCount * itemSize), itemSize, normalized), + ); + } + if (this.source.index || this.faceCount !== this.initialFaces) { + const index = this.geometry.index!.array.slice(0, this.faceCount * 3) as Uint32Array; + geometry.setIndex( + new BufferAttribute(this.vertexCount <= 65_536 ? Uint16Array.from(index) : index, 1), + ); + } + geometry.groups = this.geometry.groups.map((group) => ({ ...group })); + geometry.computeBoundingBox(); + if (geometry.boundingBox && this.geometry.boundingSphere) { + const bounds = this.geometry.boundingSphere; + geometry.boundingSphere = new Sphere(bounds.center.clone(), bounds.radius); + } + this.refitPicking(geometry); + if (this.faceStart.length) + rememberIncidence(geometry, { + weldOf: + this.weldOf.length === this.vertexCount + ? this.weldOf + : this.weldOf.slice(0, this.vertexCount), + representative: + this.representative.length === this.weldCount + ? this.representative + : this.representative.slice(0, this.weldCount), + faceStart: this.faceStart, + incidentFaces: this.incidentFaces, + edits: new Map([ + ...this.baseEdits, + ...Array.from(this.incidentEdits, ([vertex, faces]) => [vertex, new Set(faces)] as const), + ]), + }); + return geometry; + } +} diff --git a/tests/unit/sculpt-mesh.test.ts b/tests/unit/sculpt-mesh.test.ts new file mode 100644 index 0000000..d03f749 --- /dev/null +++ b/tests/unit/sculpt-mesh.test.ts @@ -0,0 +1,240 @@ +import { + BufferAttribute, + BufferGeometry, + Matrix4, + Mesh, + MeshBasicMaterial, + Raycaster, + Vector3, + type Intersection, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import { describe, expect, it } from 'vitest'; +import { SculptMesh, type SculptDab } from '../../src/core/sculpt-mesh'; + +const identity = new Matrix4(); +const dab = (point: Vector3, settings: Partial = {}): SculptDab => ({ + point, + normal: new Vector3(0, 0, 1), + face: 0, + radius: 0.8, + strength: 1, + detail: 0.6, + minEdge: 0.04, + brush: 'draw', + falloff: 'soft', + ...settings, +}); + +function mesh(positions: number[], corners?: number[]) { + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3)); + if (corners) geometry.setIndex(corners); + geometry.computeVertexNormals(); + return geometry; +} + +describe('sculpt mesh', () => { + it('adds detail under a small dab in a coarse face, keeping original positions and winding', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0.3, 0.4, 0)))).toBe(true); + const output = draft.finish()!; + const positions = output.getAttribute('position'); + expect(positions.count).toBeGreaterThan(3); + expect(Array.from(positions.array.slice(0, 9))).toEqual( + Array.from(source.getAttribute('position').array), + ); + expect( + Array.from({ length: positions.count }, (_, vertex) => positions.getZ(vertex)).some( + (z) => z > 0, + ), + ).toBe(true); + const meshObject = new Mesh(draft.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(new Vector3(0.3, 0.4, 3), new Vector3(0, 0, -1)); + expect(caster.intersectObject(meshObject)[0]?.point.z).toBeGreaterThan(0); + expect(source.index?.count).toBe(3); + }); + + it('splits both sides of an unindexed color and normal seam at matching positions', () => { + const source = mesh([-4, 0, 0, 4, 0, 0, 0, 4, 0, 4, 0, 0, -4, 0, 0, 0, -4, 2]); + source.setAttribute( + 'color', + new BufferAttribute( + Float32Array.from([1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1]), + 3, + ), + ); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0, 0, 0), { brush: 'mask' }))).toBe(true); + const output = draft.finish()!; + const pos = output.getAttribute('position'); + const color = output.getAttribute('color'); + const normal = output.getAttribute('normal'); + const midpoint = [...Array(pos.count).keys()].filter( + (v) => pos.getX(v) === 0 && pos.getY(v) === 0, + ); + expect(midpoint).toHaveLength(2); + expect(color.getX(midpoint[0])).not.toBe(color.getX(midpoint[1])); + expect(normal.getY(midpoint[0])).not.toBe(normal.getY(midpoint[1])); + expect(draft.getMask()[midpoint[0]]).toBe(draft.getMask()[midpoint[1]]); + expect(output.getAttribute('sculptMask')).toBeUndefined(); + }); + + it('keeps protection and pending topology unchanged when a sculpt dab has no effect', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0]); + const draft = new SculptMesh(source, identity, new Float32Array([1, 1, 1])); + expect(draft.dab(dab(new Vector3(0, 0, 0)))).toBe(false); + expect(draft.finish()).toBeNull(); + expect(draft.getMask()).toEqual(new Float32Array([1, 1, 1])); + expect(draft.geometry.drawRange.count).toBe(3); + }); + + it('protects points proportionally and applies overlapping symmetry once in world units', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 2]); + const transform = new Matrix4().makeScale(2, 3, 5).setPosition(4, 8, 1); + const point = new Vector3(4, 8, 1); + const settings = { minEdge: 100, mirror: { point, normal: new Vector3(0, 0, 1), face: 0 } }; + const direct = new SculptMesh(source, transform); + const masked = new SculptMesh(source, transform, new Float32Array([0.5, 0, 0])); + direct.dab(dab(point, { minEdge: 100 })); + masked.dab(dab(point, settings)); + expect(masked.finish()!.getAttribute('position').getZ(0)).toBeCloseTo( + direct.finish()!.getAttribute('position').getZ(0) / 2, + ); + }); + + it('ignores a nearby disconnected shell', () => { + const source = mesh([ + -2, -2, 0, 2, -2, 0, 0, 2, 0, -2, -2, -0.000001, 2, -2, -0.000001, 0, 2, -0.000001, + ]); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0, 0, 0)))).toBe(true); + const output = draft.finish()!; + const corners = output.getIndex()!; + expect([corners.getX(3), corners.getX(4), corners.getX(5)]).toEqual([3, 4, 5]); + }); + + it('reuses source ray acceleration and picks live triangle positions after splits', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); + const draft = new SculptMesh(source, identity); + const point = new Vector3(0.3, 0.4, 0); + draft.dab(dab(point)); + const object = new Mesh(draft.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(point.clone().setZ(3), new Vector3(0, 0, -1)); + caster.firstHitOnly = true; + const hits: Intersection[] = []; + draft.raycast(caster, object, hits); + expect(hits).toHaveLength(1); + expect(hits[0].point.z).toBeGreaterThan(0); + expect(hits[0].faceIndex).toBeLessThan(object.geometry.drawRange.count / 3); + expect(hits[0].point.z).toBeCloseTo(caster.intersectObject(object)[0].point.z); + }); + + it('refits an immutable committed picking tree after deformation without subdivision', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0, 5, 5, 0, 6, 5, 0, 5, 6, 0], [0, 1, 2, 3, 4, 5]); + source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); + const point = new Vector3(0, 0, 0); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(point, { minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const ray = new Raycaster(new Vector3(0.05, 0.05, 1), new Vector3(0, 0, -1)).ray; + expect((output.boundsTree as MeshBVH).raycastFirst(ray)?.point.z).toBeGreaterThan(0); + expect((source.boundsTree as MeshBVH).raycastFirst(ray)?.point.z).toBe(0); + expect(output.index?.count).toBe(6); + }); + + it('keeps the original grab weights across a long drag and after refinement', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + const point = new Vector3(0.3, 0.4, 0); + const grab = dab(point, { brush: 'grab', grab: new Vector3(1.5, 0, 0) }); + expect(draft.dab(grab)).toBe(true); + const first = draft.finish()!.getAttribute('position'); + expect(draft.dab(grab)).toBe(true); + const second = draft.finish()!.getAttribute('position'); + expect(second.count).toBe(first.count); + expect(second.array).not.toEqual(first.array); + }); + + it('softens, erases, inverts, and clears mask values without committing dense geometry', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity, new Float32Array([1, 0, 0])); + const settings = dab(new Vector3(), { brush: 'mask', minEdge: 100, strength: 0.25 }); + expect(draft.dab({ ...settings, softenMask: true })).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.75, 0, 0])); + expect(draft.dab({ ...settings, inverted: true })).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.5, 0, 0])); + expect(draft.invertMask()).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.5, 1, 1])); + expect(draft.clearMask()).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array(3)); + expect(draft.finish()).toBeNull(); + }); + + it('can refine and sculpt a previously subdivided mask commit', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const paint = new SculptMesh(source, identity); + expect(paint.dab(dab(new Vector3(0.3, 0.4, 0), { brush: 'mask', strength: 0.4 }))).toBe(true); + const painted = paint.finish()!; + const next = new SculptMesh(painted, identity, paint.getMask()); + const point = new Vector3(0.3, 0.4, 0); + const object = new Mesh(next.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(point.clone().setZ(3), new Vector3(0, 0, -1)); + const hit = caster.intersectObject(object)[0]; + expect(next.dab(dab(point, { face: hit.faceIndex!, detail: 1 }))).toBe(true); + expect(next.finish()!.index!.count).toBeGreaterThanOrEqual(painted.index!.count); + expect(paint.getMask()).toHaveLength(painted.getAttribute('position').count); + }); + + it('cuts a pinched groove and uses inverted depth for a pinched ridge', () => { + const source = mesh([0, 0, 0, 0.5, 0, 0, 0, 0.5, 0], [0, 1, 2]); + const settings = dab(new Vector3(), { + brush: 'crease', + pinch: 1, + tangent: new Vector3(0, 1, 0), + minEdge: 100, + }); + const groove = new SculptMesh(source, identity); + const ridge = new SculptMesh(source, identity); + expect(groove.dab(settings)).toBe(true); + expect(ridge.dab({ ...settings, inverted: true })).toBe(true); + const cut = groove.finish()!.getAttribute('position'); + const raised = ridge.finish()!.getAttribute('position'); + expect(cut.getX(1)).toBeLessThan(0.5); + expect(raised.getX(1)).toBe(cut.getX(1)); + expect(cut.getZ(0)).toBeLessThan(0); + expect(raised.getZ(0)).toBe(-cut.getZ(0)); + }); + + it('builds clay toward a surface plane and inflates using an individual vertex normal', () => { + const source = mesh([0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5, 0, 0.5], [0, 1, 2, 0, 2, 3]); + const clay = new SculptMesh(source, identity); + const inflate = new SculptMesh(source, identity); + const settings = dab(new Vector3(), { minEdge: 100 }); + expect(clay.dab({ ...settings, brush: 'clay' })).toBe(true); + expect(inflate.dab({ ...settings, brush: 'inflate' })).toBe(true); + const buildup = clay.finish()!.getAttribute('position'); + const inflated = inflate.finish()!.getAttribute('position'); + expect(buildup.getZ(0)).toBeGreaterThan(0); + expect(buildup.getX(0)).toBe(0); + expect(inflated.getX(0)).toBeGreaterThan(0); + expect(inflated.getZ(0)).toBeGreaterThan(0); + }); + + it('limits refinement work per dab', () => { + const source = mesh([-20, -20, 0, 20, -20, 0, 0, 20, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + const changed = draft.dab( + dab(new Vector3(), { + brush: 'mask', + radius: 5, + detail: 1, + minEdge: 0.01, + }), + ); + expect(changed).toBe(true); + expect(draft.geometry.index!.count / 3).toBeLessThanOrEqual(1 + 2 * 192); + }); +}); From db39cf1a266f93296078f32b745209df8fb5d418 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:33:01 -0800 Subject: [PATCH 08/40] (feat) Add sculpt controls and transactional history --- mcp/document.ts | 21 ++ mcp/live.ts | 1 + src/App.tsx | 14 +- src/components/Inspector.tsx | 15 +- src/components/SculptControls.tsx | 283 ++++++++++++++++++++ src/core/live.ts | 135 ++++++++-- src/core/sculpt-session.ts | 120 +++++++++ src/core/store.ts | 411 +++++++++++++++++++++++++----- src/core/types.ts | 28 +- src/hooks/useWorkbench.ts | 4 + src/styles.css | 68 ++++- src/xr/runtime.ts | 2 +- tests/unit/sculpt-session.test.ts | 179 +++++++++++++ 13 files changed, 1192 insertions(+), 89 deletions(-) create mode 100644 src/components/SculptControls.tsx create mode 100644 src/core/sculpt-session.ts create mode 100644 tests/unit/sculpt-session.test.ts diff --git a/mcp/document.ts b/mcp/document.ts index e94353e..a0639f2 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -1,5 +1,6 @@ import type { BufferGeometry } from 'three'; import { useEditor } from '../src/core/store'; +import { matchesSculptTarget, type SculptTarget } from '../src/core/sculpt-session'; import { applyPatch, composePatches, @@ -26,6 +27,7 @@ export interface Edit { checkpoint: boolean; /** Starts the scene over, as opening a file does. */ replace?: boolean; + sculpt?: SculptTarget; } interface Logged { @@ -104,6 +106,25 @@ export class SharedDocument { if (!base) throw new EditConflict('This change was made on a version of the scene that is too old.'); const current = this.scene; + if (edit.sculpt) { + const target = edit.sculpt; + const part = current.parts.find((part) => part.id === target.partId); + const carved = edit.scene.parts.find((part) => part.id === target.partId); + if (!part || !carved || !matchesSculptTarget(part, target)) + throw new EditConflict( + 'The sculpt target changed before the stroke reached the shared scene.', + ); + if (carved.geometry === part.geometry) return this.version; + const next = { + ...current, + parts: current.parts.map((candidate) => + candidate === part ? { ...part, geometry: carved.geometry } : candidate, + ), + }; + useEditor.setState((state) => ({ scene: next, revision: state.revision + 1 })); + this.commit(author, current); + return this.version; + } let next = mergeScenes(base, edit.scene, current, 'ours'); if (base !== current) try { diff --git a/mcp/live.ts b/mcp/live.ts index 2c09f78..9efe9ef 100644 --- a/mcp/live.ts +++ b/mcp/live.ts @@ -426,6 +426,7 @@ export class LiveView { scene, checkpoint: body.checkpoint !== false, replace: body.replace === true, + sculpt: body.sculpt, }); this.reply(response, 200, { version }); } catch (error) { diff --git a/src/App.tsx b/src/App.tsx index f8ce70b..2943b67 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,7 @@ import { BoxSelect, Crosshair, Paintbrush, + Brush, Pin, FilePlus2, FolderOpen, @@ -503,6 +504,16 @@ function Toolbar({ Refine {keys.refine ? {keys.refine} : null} + + ))} + + patch('radius', value)} + /> + patch('strength', value)} + /> + patch('detail', value)} + /> + +

+ {brush === 'mask' + ? 'Drag to paint protection. Hold Alt to erase or Shift to soften.' + : 'Drag on the part to sculpt. Hold Shift to smooth.'} + {['draw', 'crease', 'clay', 'inflate'].includes(brush) ? ' Hold Alt to invert.' : ''} +

+
+ +
+ + +
+
+
+ + Advanced brush settings + +
+ + patch('minEdge', value)} + /> + patch('spacing', value)} + /> + patch('stabilization', value)} + /> + + + {(settings.pressureStrength || settings.pressureRadius) && ( + patch('pressureCurve', value)} + /> + )} + {brush === 'draw' && ( + <> + + {settings.aspect < 1 && ( + <> + patch('aspect', value)} + /> + patch('rotation', value)} + /> + + + + )} + + )} + {brush === 'crease' && ( + patch('pinch', value)} + /> + )} + +
+
+ + ); +} diff --git a/src/core/live.ts b/src/core/live.ts index cf54362..0ea7ce1 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -1,11 +1,27 @@ import type { BufferGeometry } from 'three'; import { uid } from './geometry'; import { appendGeometry, parseSceneDocument, readGeometry, validateLayout } from './scene-file'; -import { committedScene, liveHost, useEditor, useSharedHistory } from './store'; +import { + committedScene, + liveHost, + restoreSculptAfterRefusal, + stopSharedSculptHistory, + useEditor, + useSharedHistory, +} from './store'; import { useXR } from './xr-session'; +import { matchesSculptTarget, type SculptTarget } from './sculpt-session'; import { keepUnchanged, mergeScenes, sharedScene } from './sync'; import type { GeometryLayout, SceneDocument } from './types'; +interface QueuedEdit { + before: SceneDocument; + scene: SceneDocument; + checkpoint: boolean; + replace: boolean; + sculpt?: SculptTarget; +} + interface Message { version: number; epoch: number; @@ -57,6 +73,7 @@ export function joinLiveSession() { const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); + const edits: QueuedEdit[] = []; const requests: ('undo' | 'redo')[] = []; /** The last scene the server sent. Unsent changes here are relative to it. */ let confirmed: { version: number; epoch: number; scene: SceneDocument } | null = null; @@ -73,6 +90,7 @@ export function joinLiveSession() { let replace = false; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; + let awaitedSculptHistory = 0; const notify = (message: string, kind: 'error' | 'info' = 'error') => useEditor.getState().notify(message, kind); @@ -87,11 +105,48 @@ export function joinLiveSession() { }; const unsubscribe = useEditor.subscribe((state, previous) => { - if (applyingRemote || committedScene(state) === committedScene(previous) || !confirmed) return; - dirty = true; - if (state.sceneEpoch !== previous.sceneEpoch) replace = true; - // An action that adds an undo step here starts a new one on the server; a drag extends it. - if (replace || state.past !== previous.past) checkpoint = true; + const before = committedScene(previous); + const scene = committedScene(state); + if (applyingRemote || scene === before || !confirmed) return; + const sculpt = state.sculpt; + const step = sculpt?.past.at(-1); + const target = sculpt && before.parts.find((part) => part.id === sculpt.partId); + const changed = sculpt && scene.parts.find((part) => part.id === sculpt.partId); + if ( + sculpt && + sculpt.revision !== previous.sculpt?.revision && + step && + target && + changed && + target.geometry !== changed.geometry && + step.before.geometry === target.geometry.uuid && + step.after.geometry === changed.geometry.uuid + ) { + // Keep each geometry stroke as a separate shared undo step, even during an upload. + if (dirty) edits.push({ before: confirmed.scene, scene: before, checkpoint, replace }); + edits.push({ + before, + scene, + checkpoint: true, + replace: false, + sculpt: { + partId: target.id, + source: target.geometry.uuid, + position: target.position, + quaternion: target.quaternion, + scale: target.scale, + }, + }); + dirty = checkpoint = replace = false; + } else { + dirty = true; + if (state.sceneEpoch !== previous.sceneEpoch) { + edits.length = 0; + replace = true; + } + // An action that adds an undo step here starts a new one on the server; a drag extends it. + if (replace || state.past !== previous.past) checkpoint = true; + } void pump(); }); @@ -125,13 +180,21 @@ export function joinLiveSession() { // This tab is about to replace the scene, so it keeps its own. if (replace) next = local; // Changes made on a scene that has since been replaced no longer apply. - else if (first || replaced) dirty = false; - else if (dirty || sending) next = mergeScenes(confirmed!.scene, local, scene, 'ours'); + else if (first || replaced) { + dirty = false; + edits.length = 0; + if (replaced && useEditor.getState().sculpt) useEditor.getState().setTool('select'); + } else if (dirty || sending || edits.length) + next = mergeScenes(confirmed!.scene, local, scene, 'ours'); confirmed = { version: message.version, epoch: message.epoch, scene }; const [undo, redo] = message.history[client] ?? [0, 0]; useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); const before = new Set(local.parts.map((part) => part.id)); show(next); + if (awaitedSculptHistory && message.version >= awaitedSculptHistory) { + awaitedSculptHistory = 0; + stopSharedSculptHistory(); + } if (!replace && (first || replaced)) useEditor.getState().settleWarp(true); const shown = useEditor.getState().scene; if (first) useEditor.getState().markSaved(useEditor.getState().revision); @@ -176,10 +239,15 @@ export function joinLiveSession() { /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ const refused = (reason?: string) => { + edits.length = 0; dirty = false; replace = false; checkpoint = true; - if (confirmed) show(confirmed.scene); + if (confirmed) { + const { sculpt } = useEditor.getState(); + show(confirmed.scene); + restoreSculptAfterRefusal(confirmed.scene, sculpt); + } notify( `Your last change was undone because it could not be combined with ${other}'s.${reason ? ` ${reason}` : ''}`, ); @@ -190,19 +258,37 @@ export function joinLiveSession() { if (closed) return; connected = false; useSharedHistory(null); + stopSharedSculptHistory(); // While the agent is away, undo here covers only changes made in the meantime. useEditor.setState({ liveStatus: 'disconnected', sharedHistory: null, past: [], future: [] }); }; - const sendEdit = async () => { - const scene = committedScene(useEditor.getState()); + const sendEdit = async (queued?: QueuedEdit) => { // Keep the submitted draft separate from any warp applied while this edit is in flight. const base = confirmed!; - const flags = { checkpoint, replace }; - dirty = checkpoint = replace = false; + const flags = queued + ? { checkpoint: queued.checkpoint, replace: queued.replace } + : { checkpoint, replace }; + const sculpt = queued?.sculpt; + if (!queued) dirty = checkpoint = replace = false; sending = true; - useEditor.getState().submitWarp(); + if (!sculpt) useEditor.getState().submitWarp(); try { + if (sculpt) { + const target = base.scene.parts.find((part) => part.id === sculpt.partId); + const result = queued.scene.parts.find((part) => part.id === sculpt.partId); + // A request can succeed even when the connection drops before its response arrives. + if (target && target.geometry.uuid === result?.geometry.uuid) return; + if (!matchesSculptTarget(target, sculpt)) + throw new Refusal( + 'The sculpt target changed before the stroke reached the shared scene.', + ); + } + const scene = !queued + ? committedScene(useEditor.getState()) + : flags.replace + ? queued.scene + : mergeScenes(queued.before, queued.scene, base.scene); for (const { geometry } of scene.parts) { const key = geometry.uuid; if (known.has(key)) continue; @@ -215,20 +301,24 @@ export function joinLiveSession() { base: base.version, epoch: base.epoch, ...flags, + sculpt, scene: sharedScene(scene), }); if (response.ok) { awaited = ((await response.json()) as { version: number }).version; - useEditor.getState().settleWarp(true, true); + if (!sculpt) useEditor.getState().settleWarp(true, true); } else refused(await errorOf(response)); } catch (error) { if (error instanceof Refusal) refused(error.message); else { // Kept for when the agent can be reached again. - dirty = true; - checkpoint ||= flags.checkpoint; - replace ||= flags.replace; - useEditor.getState().retryWarp(); + if (queued) edits.unshift(queued); + else { + dirty = true; + checkpoint ||= flags.checkpoint; + replace ||= flags.replace; + } + if (!sculpt) useEditor.getState().retryWarp(); lost(); } } finally { @@ -241,6 +331,7 @@ export function joinLiveSession() { try { const response = await post(`live/${direction}`, { client }); if (!response.ok) { + stopSharedSculptHistory(); notify((await errorOf(response)) ?? `This could not be ${direction}ne.`); return; } @@ -250,6 +341,8 @@ export function joinLiveSession() { empty?: boolean; }; awaited = result.version; + if (result.changed && awaited > confirmed!.version) awaitedSculptHistory = awaited; + else stopSharedSculptHistory(); if (!result.changed && !result.empty) notify( `Nothing to ${direction}: ${other} has since changed everything that step touched.`, @@ -267,7 +360,8 @@ export function joinLiveSession() { pumping = true; try { while (!closed && connected && confirmed && awaited <= confirmed.version) { - if (dirty) await sendEdit(); + if (edits.length) await sendEdit(edits.shift()); + else if (dirty) await sendEdit(); else if (requests.length) await sendHistory(requests.shift()!); else break; } @@ -314,6 +408,7 @@ export function joinLiveSession() { source.close(); unsubscribe(); useSharedHistory(null); + stopSharedSculptHistory(); useEditor.setState({ liveStatus: null }); window.removeEventListener('pointerdown', markViewMoved, { capture: true }); window.removeEventListener('wheel', markViewMoved, { capture: true }); diff --git a/src/core/sculpt-session.ts b/src/core/sculpt-session.ts new file mode 100644 index 0000000..f5afc59 --- /dev/null +++ b/src/core/sculpt-session.ts @@ -0,0 +1,120 @@ +import type { BufferGeometry } from 'three'; +import { same } from './sync'; +import type { Part, Quat, SculptBrush, SculptureSettings, Vec3 } from './types'; + +export interface SculptTarget { + partId: string; + source: string; + position: Vec3; + quaternion: Quat; + scale: Vec3; +} + +export function matchesSculptTarget(part: Part | undefined, target: SculptTarget) { + return ( + part?.visible && + !part.locked && + part.id === target.partId && + part.geometry.uuid === target.source && + same(part.position, target.position) && + same(part.quaternion, target.quaternion) && + same(part.scale, target.scale) + ); +} + +export interface SculptStrokeCommit { + partId: string; + source: BufferGeometry; + epoch: number; + revision?: number; + position: Vec3; + quaternion: Quat; + scale: Vec3; + geometry: BufferGeometry | null; + mask: Float32Array | null; +} + +interface SculptSnapshot { + geometry: string; + mask: Float32Array | null; +} + +export interface SculptStep { + before: SculptSnapshot; + after: SculptSnapshot; +} + +export interface SculptSession { + partId: string; + settings: SculptureSettings; + byBrush: Partial>; + defaultRadius: number; + mask: Float32Array | null; + revision: number; + past: SculptStep[]; + future: SculptStep[]; + pending: { direction: 'undo' | 'redo'; step: SculptStep } | null; +} + +export function sculptDefaults( + brush: SculptBrush, + radius: number, + maskVisible = true, +): SculptureSettings { + return { + brush, + radius, + strength: 0.35, + detail: 0.5, + minEdge: 0.05, + falloff: 'soft', + symmetry: false, + spacing: 0.2, + stabilization: 0, + pressureStrength: true, + pressureRadius: false, + pressureCurve: 1, + aspect: 1, + rotation: 0, + tilt: false, + twist: false, + pinch: 0.5, + maskVisible, + }; +} + +export const maskHistoryBytes = 64 * 1024 * 1024; +export const sculptHistoryBytes = 256 * 1024 * 1024; + +/** Count unique allocations because consecutive strokes can share unchanged weights. */ +export function appendSculptStep(past: SculptStep[], step: SculptStep) { + const kept = [...past, step].slice(-40); + const seen = new Set([step.after.mask?.buffer]); + let bytes = 0; + for (let i = kept.length - 1; i >= 0; i--) { + for (const { mask } of [kept[i].before, kept[i].after]) { + if (mask && !seen.has(mask.buffer)) { + seen.add(mask.buffer); + bytes += mask.buffer.byteLength; + } + } + if (bytes > maskHistoryBytes) return kept.slice(i + 1); + } + return kept; +} + +export function stepSculptSession( + session: SculptSession, + direction: 'undo' | 'redo', + step: SculptStep, +): SculptSession { + const undo = direction === 'undo'; + return { + ...session, + revision: session.revision + 1, + mask: (undo ? step.before : step.after).mask, + pending: null, + past: undo ? session.past.slice(0, -1) : [...session.past, step], + future: undo ? [step, ...session.future] : session.future.slice(1), + }; +} diff --git a/src/core/store.ts b/src/core/store.ts index 423c3d6..c8169ff 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -99,7 +99,16 @@ import type { RegionInput, RegionSolve } from './refine-region'; import type { NavigationMode } from './navigation'; import { createSample } from './sample'; import { useXR } from './xr-session'; -import { trimHistory } from './history-budget'; +import { geometryBytes, historyBudgetBytes, trimHistory } from './history-budget'; +import { + appendSculptStep, + maskHistoryBytes, + sculptDefaults, + sculptHistoryBytes, + stepSculptSession, + type SculptSession, + type SculptStrokeCommit, +} from './sculpt-session'; import { captureComponents, instantiateComponents } from './clipboard'; import type { ComponentClipboard } from './clipboard'; import { referencePlanes, resolvePart } from './references'; @@ -185,6 +194,8 @@ import type { SurfacePair, SurfaceSide, Tool, + SculptBrush, + SculptureSettings, ViewSettings, Vec3, } from './types'; @@ -482,6 +493,7 @@ interface EditorState { warpPending: WarpRecovery | null; warpInFlight: WarpRecovery | null; refine: RefineSession | null; + sculpt: SculptSession | null; view: ViewSettings; /** Lighting for scenes that have none of their own. Kept in this browser. */ defaultLighting: SceneLighting; @@ -609,6 +621,13 @@ interface EditorState { retryWarp: () => void; settleWarp: (accepted: boolean, submittedOnly?: boolean) => void; /** Starts a session on the one selected part, or says why it cannot. */ + startSculpt: () => boolean; + setSculptBrush: (brush: SculptBrush) => void; + setSculptSettings: (patch: Partial>) => void; + resetSculptBrush: () => void; + cancelSculptStroke: () => void; + commitSculpt: (stroke: SculptStrokeCommit) => boolean; + changeSculptMask: (operation: 'invert' | 'clear') => void; startRefine: () => boolean; /** Ends the session without changing the part. It leaves the tool as it is. */ cancelRefine: (notice?: string) => void; @@ -763,6 +782,7 @@ const toolChange = (state: EditorState, tool: Tool): Partial => { const pair = mode === 'surface' ? emptySurfacePair() : null; return { tool, + sculpt: tool === 'sculpt' ? state.sculpt : null, pinPicking: tool === 'pins' && !state.scene.parts.find((p) => p.id === state.selected[0])?.pins?.length ? 'hard' @@ -1865,7 +1885,12 @@ function appliedWarpGeometry(source: BufferGeometry, output: WarpOutput) { return geometry; } -const changed = (state: EditorState, scene: SceneDocument, checkpoint = true) => { +const changed = ( + state: EditorState, + scene: SceneDocument, + checkpoint = true, + budget = historyBudgetBytes, +) => { const base = committedScene(state); let past = checkpoint ? [...state.past.slice(-(historyLimit - 1)), base] : state.past; let notice = {}; @@ -1874,6 +1899,7 @@ const changed = (state: EditorState, scene: SceneDocument, checkpoint = true) => past, [], [scene, ...(state.clipboard ? [{ name: '', parts: state.clipboard.parts, joints: [] }] : [])], + budget, ); if (kept.trimmed) { past = kept.past; @@ -1953,6 +1979,84 @@ const restoredIsolated = (state: EditorState, scene: SceneDocument) => scene.parts.filter((part) => !state.scene.parts.some((p) => p.id === part.id)), ); +let sculptRevision = 0; +const nextSculptRevision = () => ++sculptRevision; + +type HistoryDirection = 'undo' | 'redo'; + +function historyScene(state: EditorState, direction: HistoryDirection) { + return direction === 'undo' ? state.past.at(-1) : state.future[0]; +} + +function restoreHistoryScene( + state: EditorState, + direction: HistoryDirection, + scene: SceneDocument, + sculpt: SculptSession | null = null, +): Partial { + const undo = direction === 'undo'; + return { + scene, + past: undo ? state.past.slice(0, -1) : [...state.past, state.scene], + future: undo ? [state.scene, ...state.future] : state.future.slice(1), + revision: state.revision + 1, + selected: state.selected.filter((id) => scene.parts.some((part) => part.id === id)), + ...restoredIsolated(state, scene), + operation: blankOperation(), + // Keep placement tools ready for another adjustment after undo. + tool: + sculpt || ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) + ? state.tool + : 'select', + sculpt, + navigationMode: null, + pivotPicking: false, + painting: false, + paintHistory: [], + measurement: [], + }; +} + +function sculptHistoryStep(state: EditorState, direction: HistoryDirection) { + const { sculpt } = state; + if (!sculpt || sculpt.pending) return; + const undo = direction === 'undo'; + const step = undo ? sculpt.past.at(-1) : sculpt.future[0]; + if (!step || step.before.geometry === step.after.geometry || state.sharedHistory) return step; + const destination = (undo ? step.before : step.after).geometry; + const scene = historyScene(state, direction); + if (scene?.parts.some((part) => part.id === sculpt.partId && part.geometry.uuid === destination)) + return step; +} + +function moveHistory(direction: HistoryDirection) { + const state = useEditor.getState(); + const { sculpt } = state; + const step = sculptHistoryStep(state, direction); + if (sculpt?.pending) return; + if (sculpt && step) { + const next = stepSculptSession(sculpt, direction, step); + next.revision = nextSculptRevision(); + if (step.before.geometry === step.after.geometry) useEditor.setState({ sculpt: next }); + else if (sharedHandlers) { + useEditor.setState({ + sculpt: { ...sculpt, pending: { direction, step }, revision: next.revision }, + }); + sharedHandlers[direction](); + } else { + useEditor.setState( + restoreHistoryScene(state, direction, historyScene(state, direction)!, next), + ); + } + return; + } + const scene = historyScene(state, direction); + if (sharedHandlers) { + if (sculpt) state.setTool('select'); + sharedHandlers[direction](); + } else if (scene) useEditor.setState(restoreHistoryScene(state, direction, scene)); +} + export const useEditor = create((set, get) => ({ scene: initialScene, selected: liveSession ? [] : ['torso'], @@ -1985,6 +2089,7 @@ export const useEditor = create((set, get) => ({ warpPending: null, warpInFlight: null, refine: null, + sculpt: null, view: { inspection: { enabled: false, @@ -2149,6 +2254,7 @@ export const useEditor = create((set, get) => ({ else if (tool === 'refine' && state.tool === 'refine' && state.refine) set({ navigationMode: null, pivotPicking: false }); else if (tool === 'refine') state.startRefine(); + else if (tool === 'sculpt' && !state.sculpt) state.startSculpt(); else set((state) => toolChange(state, tool)); }, addFitAnchor: (point) => { @@ -3284,6 +3390,166 @@ export const useEditor = create((set, get) => ({ 'info', ); }, + startSculpt: () => { + const state = get(); + if (useXR.getState().session) return false; + const part = + state.selected.length === 1 + ? state.scene.parts.find((candidate) => candidate.id === state.selected[0]) + : undefined; + if (!part?.visible || part.locked) { + state.notify('Select one visible, unlocked part to sculpt.', 'info'); + return false; + } + if ( + geometryBytes([part.geometry]) > sculptHistoryBytes || + part.geometry.getAttribute('position').count * Float32Array.BYTES_PER_ELEMENT > + maskHistoryBytes + ) { + state.notify(`${part.name} is too large to sculpt with undo history.`, 'info'); + return false; + } + const defaultRadius = fittedWarpBrushRadius(part); + set({ + ...toolChange(state, 'sculpt'), + sculpt: { + partId: part.id, + settings: sculptDefaults('draw', defaultRadius), + byBrush: {}, + defaultRadius, + mask: null, + revision: nextSculptRevision(), + past: [], + future: [], + pending: null, + }, + }); + return true; + }, + setSculptBrush: (brush) => + set(({ sculpt }) => { + if (!sculpt || brush === sculpt.settings.brush) return {}; + const { maskVisible } = sculpt.settings; + const settings = sculpt.byBrush[brush] ?? sculptDefaults(brush, sculpt.defaultRadius); + return { + sculpt: { + ...sculpt, + settings: { ...settings, maskVisible }, + byBrush: { ...sculpt.byBrush, [sculpt.settings.brush]: sculpt.settings }, + }, + }; + }), + setSculptSettings: (patch) => + set(({ sculpt }) => + sculpt ? { sculpt: { ...sculpt, settings: { ...sculpt.settings, ...patch } } } : {}, + ), + resetSculptBrush: () => + set(({ sculpt }) => + sculpt + ? { + sculpt: { + ...sculpt, + settings: sculptDefaults( + sculpt.settings.brush, + sculpt.defaultRadius, + sculpt.settings.maskVisible, + ), + }, + } + : {}, + ), + cancelSculptStroke: () => + set(({ sculpt }) => (sculpt ? { sculpt: { ...sculpt, revision: nextSculptRevision() } } : {})), + commitSculpt: (stroke) => { + const state = get(); + const { sculpt } = state; + const part = state.scene.parts.find((candidate) => candidate.id === stroke.partId); + if ( + state.tool !== 'sculpt' || + !sculpt || + sculpt.pending || + sculpt.partId !== stroke.partId || + (stroke.revision !== undefined && stroke.revision !== sculpt.revision) || + !part?.visible || + part.locked || + state.selected.length !== 1 || + state.selected[0] !== part.id || + part.geometry !== stroke.source || + state.sceneEpoch !== stroke.epoch || + !same(part.position, stroke.position) || + !same(part.quaternion, stroke.quaternion) || + !same(part.scale, stroke.scale) + ) + return false; + const geometry = stroke.geometry ?? part.geometry; + if (stroke.mask && stroke.mask.length !== geometry.getAttribute('position').count) return false; + const mask = stroke.mask; + if (geometry === part.geometry && mask === sculpt.mask) return false; + if ( + geometry !== part.geometry && + (geometryBytes([geometry]) > sculptHistoryBytes || + geometry.getAttribute('position').count * Float32Array.BYTES_PER_ELEMENT > maskHistoryBytes) + ) { + state.notify('This stroke exceeded the mesh size limit for Sculpt.', 'info'); + return false; + } + const step = { + before: { geometry: part.geometry.uuid, mask: sculpt.mask }, + after: { geometry: geometry.uuid, mask }, + }; + set({ + ...(geometry === part.geometry + ? state.future.length + ? { future: [] } + : {} + : changed( + state, + { + ...state.scene, + parts: state.scene.parts.map((candidate) => + candidate.id === part.id ? { ...part, geometry } : candidate, + ), + }, + true, + sculptHistoryBytes, + )), + sculpt: { + ...sculpt, + revision: nextSculptRevision(), + mask, + past: appendSculptStep(sculpt.past, step), + future: [], + }, + }); + return true; + }, + changeSculptMask: (operation) => { + const state = get(); + const { sculpt } = state; + const part = sculpt && state.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!sculpt || !part || (operation === 'clear' && !sculpt.mask)) return; + const mask = + operation === 'invert' + ? new Float32Array(part.geometry.getAttribute('position').count) + : null; + if (mask) { + const previous = sculpt.mask; + if (previous) { + for (let i = 0; i < mask.length; i++) mask[i] = 1 - previous[i]; + } else mask.fill(1); + } + state.commitSculpt({ + partId: part.id, + source: part.geometry, + epoch: state.sceneEpoch, + revision: sculpt.revision, + position: part.position, + quaternion: part.quaternion, + scale: part.scale, + geometry: null, + mask, + }); + }, startRefine: () => { const state = get(); if (useXR.getState().session) return false; @@ -4645,6 +4911,7 @@ export const useEditor = create((set, get) => ({ revision: state.revision + 1, savedRevision: recovered ? state.revision : state.revision + 1, tool: 'select', + sculpt: null, activeAnchor: null, activeLight: null, anchorPicking: false, @@ -4686,59 +4953,8 @@ export const useEditor = create((set, get) => ({ const next = name.trim() || 'Untitled assembly'; return next === state.scene.name ? {} : changed(state, { ...state.scene, name: next }); }), - undo: () => - sharedHandlers - ? sharedHandlers.undo() - : set((state) => - state.past.length - ? { - scene: state.past.at(-1)!, - past: state.past.slice(0, -1), - future: [state.scene, ...state.future], - revision: state.revision + 1, - selected: state.selected.filter((id) => - state.past.at(-1)!.parts.some((p) => p.id === id), - ), - ...restoredIsolated(state, state.past.at(-1)!), - operation: blankOperation(), - // Keep placement tools ready for another adjustment after undo. - tool: ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) - ? state.tool - : 'select', - navigationMode: null, - pivotPicking: false, - painting: false, - paintHistory: [], - measurement: [], - } - : {}, - ), - redo: () => - sharedHandlers - ? sharedHandlers.redo() - : set((state) => - state.future.length - ? { - scene: state.future[0], - past: [...state.past, state.scene], - future: state.future.slice(1), - revision: state.revision + 1, - selected: state.selected.filter((id) => - state.future[0].parts.some((p) => p.id === id), - ), - ...restoredIsolated(state, state.future[0]), - operation: blankOperation(), - tool: ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) - ? state.tool - : 'select', - navigationMode: null, - pivotPicking: false, - painting: false, - paintHistory: [], - measurement: [], - } - : {}, - ), + undo: () => moveHistory('undo'), + redo: () => moveHistory('redo'), setView: (patch) => { if (patch.orbitSelection !== undefined) saveOrbitPreference(patch.orbitSelection); if (patch.partColors !== undefined) savePartColorMode(patch.partColors); @@ -4808,9 +5024,14 @@ export function warpBrushRadius(state: Pick - state.sharedHistory ? state.sharedHistory.undo > 0 : state.past.length > 0; + !state.sculpt?.pending && + (!!sculptHistoryStep(state, 'undo') || + (state.sharedHistory ? state.sharedHistory.undo > 0 : state.past.length > 0)); export const canRedo = (state: EditorState) => - state.sharedHistory ? state.sharedHistory.redo > 0 : state.future.length > 0; + !state.sculpt?.pending && + (!!sculptHistoryStep(state, 'redo') || + (!state.sculpt?.past.length && + (state.sharedHistory ? state.sharedHistory.redo > 0 : state.future.length > 0))); /** Preview poses never reach recovery, Drive, or other shared-session participants. */ export const committedScene = (state: EditorState) => state.freeTransform?.baseline ?? state.scene; @@ -6716,6 +6937,82 @@ function closesAs(segments: EdgeSegment[]) { : first.kind === 'spline' && samePoint(first.points[0], end); } +// A refused shared edit restores the mask that belonged to the server's geometry. +export function restoreSculptAfterRefusal(scene: SceneDocument, sculpt: SculptSession | null) { + if (!sculpt || useEditor.getState().sculpt?.partId !== sculpt.partId) return; + const geometry = scene.parts.find((part) => part.id === sculpt.partId)?.geometry.uuid; + const start = sculpt.past.findIndex( + (step) => step.before.geometry === geometry && step.after.geometry !== geometry, + ); + if (start < 0) return; + useEditor.setState({ + sculpt: { + ...sculpt, + mask: sculpt.past[start].before.mask, + past: sculpt.past.slice(0, start), + future: [], + pending: null, + revision: nextSculptRevision(), + }, + }); +} + +export function stopSharedSculptHistory() { + const { sculpt } = useEditor.getState(); + if (sculpt?.pending) + useEditor.setState({ + sculpt: { ...sculpt, past: [], future: [], pending: null, revision: nextSculptRevision() }, + }); +} + +useEditor.subscribe((state, previous) => { + const { sculpt } = state; + if (!sculpt) return; + if ( + state.tool !== 'sculpt' || + state.sceneEpoch !== previous.sceneEpoch || + state.selected.length !== 1 || + state.selected[0] !== sculpt.partId + ) { + useEditor.setState({ sculpt: null, ...(state.tool === 'sculpt' ? { tool: 'select' } : {}) }); + return; + } + if (state.scene === previous.scene) return; + const part = state.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!part?.visible || part.locked) { + useEditor.setState({ sculpt: null, tool: 'select' }); + return; + } + const before = previous.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!before) return; + const moved = + !same(part.position, before.position) || + !same(part.quaternion, before.quaternion) || + !same(part.scale, before.scale); + if (sculpt.pending) { + const { direction, step } = sculpt.pending; + if (part.geometry.uuid === (direction === 'undo' ? step.before : step.after).geometry) { + useEditor.setState({ + sculpt: { ...stepSculptSession(sculpt, direction, step), revision: nextSculptRevision() }, + }); + return; + } + } + const replaced = part.geometry.uuid !== before.geometry.uuid; + if (replaced && sculpt.revision === previous.sculpt?.revision) { + useEditor.setState({ + sculpt: { + ...sculpt, + mask: null, + past: [], + future: [], + pending: null, + revision: nextSculptRevision(), + }, + }); + } else if (moved) state.cancelSculptStroke(); +}); + // A refinement is built from one geometry of one scene at one pose. Undo, another editor, // opening a file or leaving the tool by any route ends the session. useEditor.subscribe((state, previous) => { diff --git a/src/core/types.ts b/src/core/types.ts index 75961ae..995a635 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -16,7 +16,33 @@ export type Tool = | 'pins' | 'anchors' | 'warp' - | 'refine'; + | 'refine' + | 'sculpt'; + +export type SculptBrush = + 'draw' | 'grab' | 'smooth' | 'flatten' | 'crease' | 'clay' | 'inflate' | 'mask'; + +export interface SculptureSettings { + brush: SculptBrush; + radius: number; + strength: number; + detail: number; + minEdge: number; + falloff: 'soft' | 'linear' | 'hard'; + symmetry: boolean; + spacing: number; + stabilization: number; + pressureStrength: boolean; + pressureRadius: boolean; + pressureCurve: number; + aspect: number; + rotation: number; + tilt: boolean; + twist: boolean; + pinch: number; + maskVisible: boolean; +} + export type AlignmentMode = 'point' | 'point-plane' | 'plane' | 'multi' | 'surface'; export type AlignmentView = 'scene' | 'pair' | 'active' | 'ghost'; diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 9173317..2569878 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -294,6 +294,10 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { state.setNavigationMode(null); return; } + if (state.tool === 'sculpt') { + state.cancelSculptStroke(); + return; + } // Otherwise Escape leaves the tool, as it does for Warp. if (state.tool === 'refine' && refineKey(state, 'cancel')) return; const wasSelecting = state.tool === 'select'; diff --git a/src/styles.css b/src/styles.css index 37e423f..88d05b0 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6696,7 +6696,8 @@ optgroup { gap: 3px; } .refine-ends select, -.refine-controls .brush-radius > select { +.refine-controls .brush-radius > select, +.sculpt-controls .brush-radius > select { min-width: 0; padding: 6px; border: 1px solid var(--border); @@ -6723,7 +6724,64 @@ optgroup { .refine-counts { margin: 12px 16px 0; } -/* Narrower toolbars show Pin, Anchors, Joint, Warp and Refine as icons, so the strip still fits +.sculpt-controls { + display: grid; + gap: 10px; + padding: 14px 16px; +} +.sculpt-brushes { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 5px; +} +.sculpt-brushes .button { + justify-content: center; + padding-inline: 6px; + white-space: normal; +} +.sculpt-brushes .button.active { + border-color: var(--accent); + color: var(--accent); +} +.sculpt-controls .field-help { + margin: 0; +} +.sculpt-check { + display: flex; + align-items: center; + gap: 8px; + min-height: 24px; + font-size: 11px; + color: var(--muted); +} +.sculpt-check input { + margin: 0; + accent-color: var(--accent); +} +.sculpt-mask-controls { + display: grid; + gap: 6px; + border-top: 1px solid var(--border); + padding-top: 8px; +} +.sculpt-mask-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.sculpt-advanced { + margin-inline: -16px; +} +.sculpt-advanced:not([open]) > summary > svg { + transform: rotate(-90deg); +} +.sculpt-advanced-fields { + display: grid; + gap: 8px; + padding-inline: 16px; +} + +/* Narrower toolbars show secondary tools as icons, so the strip still fits on one row. Their names stay in the tooltip and for assistive technology. */ @media (max-width: 1500px) { .toolbar-left .compact-tool { @@ -6740,13 +6798,15 @@ optgroup { } @media (max-width: 1700px) { .toolbar-left .warp-tool, - .toolbar-left .refine-tool { + .toolbar-left .refine-tool, + .toolbar-left .sculpt-tool { position: relative; } .toolbar-left .warp-tool > span, .toolbar-left .warp-tool > kbd, .toolbar-left .refine-tool > span, - .toolbar-left .refine-tool > kbd { + .toolbar-left .refine-tool > kbd, + .toolbar-left .sculpt-tool > span { position: absolute; width: 1px; height: 1px; diff --git a/src/xr/runtime.ts b/src/xr/runtime.ts index 1645bcb..8579055 100644 --- a/src/xr/runtime.ts +++ b/src/xr/runtime.ts @@ -229,7 +229,7 @@ export class XRRuntime { ) { // Warp and Refine are desktop only. const editor = useEditor.getState(); - if (editor.tool === 'warp' || editor.tool === 'refine') { + if (editor.tool === 'warp' || editor.tool === 'refine' || editor.tool === 'sculpt') { editor.setTool('select'); this.tool = 'select'; } diff --git a/tests/unit/sculpt-session.test.ts b/tests/unit/sculpt-session.test.ts new file mode 100644 index 0000000..850f10a --- /dev/null +++ b/tests/unit/sculpt-session.test.ts @@ -0,0 +1,179 @@ +import { BoxGeometry } from 'three'; +import { afterEach, describe, expect, it } from 'vitest'; +import { EditConflict, SharedDocument } from '../../mcp/document'; +import type { SculptStrokeCommit } from '../../src/core/sculpt-session'; +import { restoreSculptAfterRefusal, useEditor, useSharedHistory } from '../../src/core/store'; +import type { Part, SceneDocument } from '../../src/core/types'; + +function fixture() { + const part: Part = { + id: 'sculpt-target', + name: 'Sculpt target', + geometry: new BoxGeometry(), + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#ffffff', + visible: true, + locked: false, + source: 'test.stl', + }; + const scene: SceneDocument = { name: 'Sculpt', parts: [part], joints: [] }; + return { part, scene }; +} + +function openSculpt() { + const { part, scene } = fixture(); + useEditor.getState().setScene(scene); + useEditor.getState().select(part.id); + expect(useEditor.getState().startSculpt()).toBe(true); + return { part, scene }; +} + +function stroke(patch: Partial): SculptStrokeCommit { + const state = useEditor.getState(); + const part = state.scene.parts[0]; + return { + ...part, + partId: part.id, + source: part.geometry, + epoch: state.sceneEpoch, + revision: state.sculpt!.revision, + geometry: null, + mask: state.sculpt!.mask, + ...patch, + }; +} + +afterEach(() => { + useSharedHistory(null); + useEditor.setState({ sharedHistory: null }); + useEditor.getState().setScene({ name: 'Empty', parts: [], joints: [] }); +}); + +describe('sculpt session', () => { + it('steps through temporary masks and geometry together while preserving committed history', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + store().changeSculptMask('invert'); + const firstMask = store().sculpt!.mask; + const geometry = part.geometry.clone(); + const newMask = new Float32Array(geometry.getAttribute('position').count).fill(0.25); + expect(store().commitSculpt(stroke({ geometry, mask: newMask }))).toBe(true); + store().changeSculptMask('clear'); + expect(store().revision - store().savedRevision).toBe(1); + expect(store().past).toEqual([scene]); + store().undo(); + expect(store().sculpt!.mask).toBe(newMask); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().undo(); + expect(store().sculpt!.mask).toBe(firstMask); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + store().undo(); + expect(store().sculpt!.mask).toBeNull(); + store().redo(); + store().redo(); + expect(store().sculpt!.mask).toBe(newMask); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().redo(); + expect(store().sculpt!.mask).toBeNull(); + store().setTool('select'); + expect(store().sculpt).toBeNull(); + store().undo(); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + }); + + it('remembers settings per brush and rejects a cancelled or moved stroke', () => { + const { part } = openSculpt(); + const store = useEditor.getState; + store().setSculptSettings({ radius: 7 }); + store().setSculptBrush('crease'); + store().setSculptSettings({ pinch: 0.9 }); + store().setSculptBrush('draw'); + expect(store().sculpt!.settings.radius).toBe(7); + store().resetSculptBrush(); + expect(store().sculpt!.settings.radius).toBe(store().sculpt!.defaultRadius); + store().setSculptBrush('crease'); + expect(store().sculpt!.settings.pinch).toBe(0.9); + const stale = stroke({ geometry: part.geometry.clone() }); + store().cancelSculptStroke(); + expect(store().commitSculpt(stale)).toBe(false); + const moved = stroke({ geometry: part.geometry.clone() }); + store().receiveScene({ ...store().scene, parts: [{ ...part, position: [1, 0, 0] }] }); + expect(store().commitSculpt(moved)).toBe(false); + expect(store().past).toHaveLength(0); + }); + + it('restores the appropriate weights on shared undo, redo, and refusal', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + const geometry = part.geometry.clone(); + const next = { ...scene, parts: [{ ...part, geometry }] }; + store().changeSculptMask('invert'); + const initialMask = store().sculpt!.mask; + expect(store().commitSculpt(stroke({ geometry, mask: null }))).toBe(true); + + useEditor.setState({ sharedHistory: { undo: 1, redo: 0 } }); + useSharedHistory({ + undo: () => store().receiveScene(scene), + redo: () => store().receiveScene(next), + }); + store().undo(); + expect(store().sculpt!.mask).toBe(initialMask); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + store().redo(); + expect(store().sculpt!.mask).toBeNull(); + expect(store().scene.parts[0].geometry).toBe(geometry); + + const refused = store().sculpt; + store().receiveScene(scene); + restoreSculptAfterRefusal(scene, refused); + expect(store().sculpt!.mask).toBe(initialMask); + expect(store().sculpt!.past).toHaveLength(1); + expect(store().sculpt!.future).toHaveLength(0); + }); +}); + +describe('shared sculpt transactions', () => { + it('rejects stale geometry and pose while preserving other authors’ changes', () => { + const { part, scene } = fixture(); + const document = new SharedDocument(); + document.replace(scene); + const first = document.version; + const geometry = part.geometry.clone(); + const target = { + partId: part.id, + source: part.geometry.uuid, + position: part.position, + quaternion: part.quaternion, + scale: part.scale, + }; + const edit = { + scene: { ...scene, parts: [{ ...part, geometry }] }, + base: first, + epoch: document.epoch, + checkpoint: true, + sculpt: target, + }; + document.apply('another-tab', { + ...edit, + sculpt: undefined, + scene: { ...scene, name: 'Renamed' }, + }); + document.apply('sculpt-tab', edit); + expect(document.scene.name).toBe('Renamed'); + expect(document.scene.parts[0].geometry).toBe(geometry); + expect(() => document.apply('sculpt-tab', edit)).toThrow(EditConflict); + document.undo('sculpt-tab'); + const base = document.version; + document.apply('another-tab', { + ...edit, + base, + sculpt: undefined, + scene: { ...document.scene, parts: [{ ...part, position: [1, 0, 0] }] }, + }); + expect(() => document.apply('sculpt-tab', { ...edit, base })).toThrow(EditConflict); + expect(document.scene.parts[0].position).toEqual([1, 0, 0]); + expect(document.scene.parts[0].geometry).toBe(part.geometry); + }); +}); From f1cf95cf956fa43ab84dd6a2b2a8aa52f926cf22 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:33:11 -0800 Subject: [PATCH 09/40] (fix) Preserve sculpt growth bounds and separate touching shells --- src/core/sculpt-mesh.ts | 131 ++++++++++++++++++++++++++++----- tests/unit/sculpt-mesh.test.ts | 44 +++++++++++ 2 files changed, 157 insertions(+), 18 deletions(-) diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts index 6f6ee85..0a61d48 100644 --- a/src/core/sculpt-mesh.ts +++ b/src/core/sculpt-mesh.ts @@ -72,6 +72,10 @@ let latestIncidence: } | undefined; +export function clearSculptIncidence() { + latestIncidence = undefined; +} + function rememberIncidence(source: BufferGeometry, incidence: Incidence) { latestIncidence = { source: new WeakRef(source), @@ -83,6 +87,9 @@ function rememberIncidence(source: BufferGeometry, incidence: Incidence) { const maxSplitsPerDab = 192; const maxFacesPerPatch = 8192; +/** Source meshes larger than this remain brushable at their available density. */ +const maxRefinedFaceCount = 1_200_000; +const inheritedFaceLimits = new WeakMap(); const maskName = 'sculptMask'; /** Exact coincident vertices share connectivity without welding a nearby thin shell. */ @@ -122,6 +129,100 @@ function weldVertices(position: Attribute) { return { weldOf, representative: representative.slice(0, count) }; } +/** CSR incidence stays compact for indexed scans and for duplicated render vertices at seams. */ +function buildFaceIncidence(weldOf: Uint32Array, weldCount: number, corners: ArrayLike) { + const faceStart = new Uint32Array(weldCount + 1); + for (let corner = 0; corner < corners.length; corner++) faceStart[weldOf[corners[corner]] + 1]++; + for (let weld = 0; weld < weldCount; weld++) faceStart[weld + 1] += faceStart[weld]; + const next = faceStart.slice(0, -1); + const incidentFaces = new Uint32Array(corners.length); + for (let corner = 0; corner < corners.length; corner++) + incidentFaces[next[weldOf[corners[corner]]]++] = Math.floor(corner / 3); + return { faceStart, incidentFaces }; +} + +/** Two render vertices at the same point are a seam only when their faces share a valid edge. */ +function weldSeams(position: Attribute, corners: ArrayLike) { + const { weldOf, representative } = weldVertices(position); + if (representative.length === position.count) return { weldOf, representative }; + const duplicates = new Uint8Array(representative.length); + for (let vertex = 0; vertex < weldOf.length; vertex++) + if (representative[weldOf[vertex]] !== vertex) duplicates[weldOf[vertex]] = 1; + const { faceStart, incidentFaces } = buildFaceIncidence(weldOf, representative.length, corners); + const parent = Uint32Array.from(weldOf, (_weld, vertex) => vertex); + function root(vertex: number) { + while (parent[vertex] !== vertex) { + parent[vertex] = parent[parent[vertex]]; + vertex = parent[vertex]; + } + return vertex; + } + const valid = new Uint8Array(corners.length / 3); + const point = new Vector3(), + left = new Vector3(), + right = new Vector3(); + function validTriangle(face: number) { + if (valid[face]) return valid[face] === 1; + const corner = face * 3; + point.fromBufferAttribute(position, corners[corner]); + left.fromBufferAttribute(position, corners[corner + 1]).sub(point); + right.fromBufferAttribute(position, corners[corner + 2]).sub(point); + const area = left.cross(right).lengthSq(); + valid[face] = Number.isFinite(area) && area > 0 ? 1 : 2; + return valid[face] === 1; + } + + for (let corner = 0; corner < corners.length; corner++) { + const face = Math.floor(corner / 3); + const u = corners[corner]; + const v = corners[face * 3 + ((corner + 1) % 3)]; + const a = weldOf[u], + b = weldOf[v]; + if (a === b || !(duplicates[a] || duplicates[b])) continue; + let match = -1; + let previous = -1; + for (let i = faceStart[a]; i < faceStart[a + 1]; i++) { + const neighbor = incidentFaces[i]; + if (neighbor === face || neighbor === previous) continue; + previous = neighbor; + const start = neighbor * 3; + if ( + weldOf[corners[start]] !== b && + weldOf[corners[start + 1]] !== b && + weldOf[corners[start + 2]] !== b + ) + continue; + if (match !== -1) { + match = -1; // Non-manifold edge. + break; + } + match = neighbor; + } + if (match <= face || !validTriangle(face) || !validTriangle(match)) continue; + for (let edge = 0; edge < 3; edge++) { + const reverseU = corners[match * 3 + ((edge + 1) % 3)]; + const reverseV = corners[match * 3 + edge]; + if (weldOf[reverseU] !== a || weldOf[reverseV] !== b) continue; + parent[root(reverseU)] = root(u); + parent[root(reverseV)] = root(v); + break; + } + } + + const remap = new Int32Array(position.count).fill(-1); + const seamRepresentative = new Uint32Array(position.count); + let count = 0; + for (let vertex = 0; vertex < weldOf.length; vertex++) { + const united = root(vertex); + if (remap[united] === -1) { + remap[united] = count; + seamRepresentative[count++] = vertex; + } + weldOf[vertex] = remap[united]; + } + return { weldOf, representative: seamRepresentative.slice(0, count) }; +} + function resize(array: T, length: number): T { const ArrayType = array.constructor as new (length: number) => T; const result = new ArrayType(length); @@ -193,7 +294,7 @@ export class SculptMesh { private readonly source: BufferGeometry; private readonly initialVertices: number; private readonly initialFaces: number; - private readonly growthLimit: number; + private readonly faceLimit: number; private vertexCount: number; private faceCount: number; private weldCount = 0; @@ -214,7 +315,10 @@ export class SculptMesh { this.orientation = Math.sign(matrixWorld.determinant()); this.initialVertices = this.vertexCount = source.getAttribute('position').count; this.initialFaces = this.faceCount = Math.floor((source.index?.count ?? this.vertexCount) / 3); - this.growthLimit = Math.min(65_536, Math.max(4096, Math.ceil(this.initialFaces * 0.2))); + const localBudget = Math.min(65_536, Math.max(4096, Math.ceil(this.initialFaces * 0.2))); + this.faceLimit = + inheritedFaceLimits.get(source) ?? + Math.min(maxRefinedFaceCount, this.initialFaces + localBudget); this.geometry.name = source.name; this.geometry.userData = { ...source.userData }; for (const [name, attribute] of Object.entries(source.attributes)) @@ -375,24 +479,14 @@ export class SculptMesh { } private buildIncidence() { - const { weldOf, representative } = weldVertices(this.attribute('position')); + const faces = this.geometry.index!.array.subarray(0, this.faceCount * 3); + const { weldOf, representative } = weldSeams(this.attribute('position'), faces); this.weldOf = weldOf; this.representative = representative; this.weldCount = representative.length; - const faces = this.geometry.index!.array.subarray(0, this.faceCount * 3); - const starts = new Uint32Array(this.weldCount + 1); - for (const vertex of faces) { - const weld = weldOf[vertex]; - starts[weld + 1]++; - // Use a referenced copy when a source contains an unused vertex at the same position. - representative[weld] = vertex; - } - for (let weld = 0; weld < this.weldCount; weld++) starts[weld + 1] += starts[weld]; - const next = starts.slice(0, -1); - this.incidentFaces = new Uint32Array(faces.length); - for (let corner = 0; corner < faces.length; corner++) - this.incidentFaces[next[weldOf[faces[corner]]]++] = Math.floor(corner / 3); - this.faceStart = starts; + const { faceStart, incidentFaces } = buildFaceIncidence(weldOf, this.weldCount, faces); + this.faceStart = faceStart; + this.incidentFaces = incidentFaces; } private incidence(weld: number): Iterable { @@ -685,7 +779,7 @@ export class SculptMesh { choice = { a, b, faces }; } if (!choice) continue; - if (this.faceCount + choice.faces.length > this.initialFaces + this.growthLimit) { + if (this.faceCount + choice.faces.length > this.faceLimit) { this.detailLimited = true; break; } @@ -1027,6 +1121,7 @@ export class SculptMesh { geometry.boundingSphere = new Sphere(bounds.center.clone(), bounds.radius); } this.refitPicking(geometry); + inheritedFaceLimits.set(geometry, this.faceLimit); if (this.faceStart.length) rememberIncidence(geometry, { weldOf: diff --git a/tests/unit/sculpt-mesh.test.ts b/tests/unit/sculpt-mesh.test.ts index d03f749..3190358 100644 --- a/tests/unit/sculpt-mesh.test.ts +++ b/tests/unit/sculpt-mesh.test.ts @@ -115,6 +115,21 @@ describe('sculpt mesh', () => { expect([corners.getX(3), corners.getX(4), corners.getX(5)]).toEqual([3, 4, 5]); }); + it.each([false, true])( + 'keeps separate shells independent at a coincident corner (indexed: %s)', + (indexed) => { + const source = mesh( + [0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, -2, 0, 0, 0, -2, 0], + indexed ? [0, 1, 2, 3, 4, 5] : undefined, + ); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(), { minEdge: 100 }))).toBe(true); + const positions = draft.finish()!.getAttribute('position'); + expect(positions.getZ(0)).toBeGreaterThan(0); + expect(positions.getZ(3)).toBe(0); + }, + ); + it('reuses source ray acceleration and picks live triangle positions after splits', () => { const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); @@ -237,4 +252,33 @@ describe('sculpt mesh', () => { expect(changed).toBe(true); expect(draft.geometry.index!.count / 3).toBeLessThanOrEqual(1 + 2 * 192); }); + + it('keeps the original growth budget across committed strokes', () => { + const positions: number[] = []; + const faces: number[] = []; + for (let i = 0; i < 60; i++) { + const x = i * 100; + positions.push(x - 20, -20, 0, x + 20, -20, 0, x, 20, 0); + faces.push(i * 3, i * 3 + 1, i * 3 + 2); + } + let source = mesh(positions, faces); + let limited = false; + for (let i = 0; i < 60 && !limited; i++) { + const draft = new SculptMesh(source, identity); + draft.dab( + dab(new Vector3(i * 100, 0, 0), { + brush: 'mask', + face: i, + radius: 5, + detail: 1, + minEdge: 0.01, + }), + ); + const committed = draft.finish(); + if (committed) source = committed; + limited = draft.detailLimited; + } + expect(limited).toBe(true); + expect(source.index!.count / 3).toBeLessThanOrEqual(60 + 4096); + }); }); From 1d976b9fc89347d5e084412097fcfc02d8f72482 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:35:02 -0800 Subject: [PATCH 10/40] (test) Verify guarded shared sculpt checkpoints --- tests/e2e/mcp.spec.ts | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 14d23ce..d9bd04b 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -423,3 +423,75 @@ test('tabs and the agent edit one scene, each with its own view', async ({ brows expect(errors).toEqual([]); await context.close(); }); + +test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = await page.locator('canvas').boundingBox(); + expect(canvas).not.toBeNull(); + const x = canvas!.x + canvas!.width / 2; + const y = canvas!.y + canvas!.height / 2; + const editUrl = /\/live\/edit$/; + const ofSculpt = (request: { postDataJSON: () => { sculpt?: unknown } }) => + !!request.postDataJSON().sculpt; + + let unpause = () => {}; + let blocked = new Promise((resolve) => { + unpause = resolve; + }); + let intercept = true; + await page.route(editUrl, async (route) => { + if (intercept && ofSculpt(route.request())) { + intercept = false; + await blocked; + } + await route.continue(); + }); + + const first = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); + await page.mouse.click(x + 8, y - 7); + const firstRequest = await first; + await page.mouse.click(x + 16, y - 7); + const second = page.waitForResponse( + (response) => + editUrl.test(response.url()) && + response.request() !== firstRequest && + ofSculpt(response.request()), + ); + unpause(); + const secondResponse = await second; + expect(secondResponse.status()).toBe(200); + expect(secondResponse.request().postDataJSON().sculpt.source).not.toEqual( + firstRequest.postDataJSON().sculpt.source, + ); + expect(secondResponse.request().postDataJSON().checkpoint).toBe(true); + + blocked = new Promise((resolve) => { + unpause = resolve; + }); + intercept = true; + const third = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); + await page.mouse.click(x + 24, y - 7); + const thirdRequest = await third; + await call('update_parts', { updates: [{ id: 'block', translate: [2, 0, 0] }] }); + const refused = page.waitForResponse((response) => response.request() === thirdRequest); + unpause(); + expect((await refused).status()).toBe(409); + await expect( + page.getByText(/sculpt target changed before the stroke reached the shared scene/i), + ).toBeVisible(); + expect((await call('get_scene')).parts[0].position).toEqual([2, 0, 0]); +}); From b8475f7a307883fd4407e6034cd23b49d6ddf8e6 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:37:33 -0800 Subject: [PATCH 11/40] (test) Measure sculpt input through viewport drawing --- tests/e2e/sculpt-benchmark.spec.ts | 154 +++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 tests/e2e/sculpt-benchmark.spec.ts diff --git a/tests/e2e/sculpt-benchmark.spec.ts b/tests/e2e/sculpt-benchmark.spec.ts new file mode 100644 index 0000000..02f331e --- /dev/null +++ b/tests/e2e/sculpt-benchmark.spec.ts @@ -0,0 +1,154 @@ +import { test, expect, type Page } from '@playwright/test'; +import { arch, cpus, release, type } from 'node:os'; +import type { BufferAttribute, Camera, Mesh } from 'three'; +import { inStore, openScene, screen } from './helpers/refine'; + +// Opt in with KITBASHER_SCULPT_VIEWPORT_BENCH=1. Each native move waits for its first +// changed draw before sending the next one, so these results exclude input queueing. +test.skip(!process.env.KITBASHER_SCULPT_VIEWPORT_BENCH, 'Opt-in viewport benchmark'); + +interface ProbeWindow extends Window { + sculptDrawTimes: number[]; +} + +async function setup(page: Page, segments: number, indexed: boolean) { + await openScene(page); + await expect(page.locator('.part-select[title="Scanned block"]')).toBeVisible(); + await page.evaluate( + async ({ segments, indexed }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const three = await import(urls.find((url) => /\/deps\/three\.js/.test(url))!); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const grid = new three.PlaneGeometry(100, 100, segments, segments); + const geometry = indexed ? grid : grid.toNonIndexed(); + const state = useEditor.getState(); + const part = { + ...state.scene.parts[0], + geometry, + name: 'Benchmark sheet', + position: [0, 55, 0], + }; + state.setScene({ ...state.scene, parts: [part] }); + }, + { segments, indexed }, + ); + await page.locator('.part-select[title="Benchmark sheet"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + if (segments > 1) + await expect + .poll(() => inStore(page, (state) => !!state.scene.parts[0].geometry.boundsTree), { + timeout: 60_000, + }) + .toBe(true); + // Register capture before Sculpt's window listener consumes active stroke events. + const gpu = await installProbe(page); + await page + .getByRole('toolbar', { name: 'Assembly tools' }) + .getByRole('button', { name: 'Sculpt', exact: true }) + .click(); + return { gpu, settings: await inStore(page, (state) => state.sculpt!.settings) }; +} + +async function installProbe(page: Page) { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { partMeshes } = await import( + urls.find((url) => /\/src\/xr\/part-meshes\.ts(?:\?.*)?$/.test(url))! + ); + const { _roots } = await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!); + const root = _roots.get(document.querySelector('canvas')).store.getState(); + const mesh: Mesh = partMeshes.get('block'); + const source = mesh.geometry; + const samples = ((window as unknown as ProbeWindow).sculptDrawTimes = [] as number[]); + let start = -1; + let lastVersion = 0; + let lastPosition = source.getAttribute('position'); + function onPointer(event: PointerEvent) { + if (event.buttons === 1) start = performance.now(); + } + window.addEventListener('pointerdown', onPointer, true); + window.addEventListener('pointermove', onPointer, true); + const previous = mesh.onAfterRender; + mesh.onAfterRender = function (...args) { + previous.apply(this, args); + const camera: Camera = args[2]; + const version = (this.geometry.getAttribute('position') as BufferAttribute).version; + if ( + start >= 0 && + camera === root.camera && + this.geometry !== source && + version > 0 && + (this.geometry.getAttribute('position') !== lastPosition || version > lastVersion) + ) { + samples.push(performance.now() - start); + lastPosition = this.geometry.getAttribute('position'); + lastVersion = version; + start = -1; + } + }; + const context = root.gl.getContext(); + const extension = context.getExtension('WEBGL_debug_renderer_info'); + return extension + ? (context.getParameter(extension.UNMASKED_RENDERER_WEBGL) as string) + : 'unavailable'; + }); +} + +for (const [name, segments, indexed] of [ + ['coarse', 1, true], + ['dense indexed', 707, true], + ['dense unindexed', 707, false], +] as const) { + test(`times pointer receipt to changed viewport draw on a ${name} sheet`, async ({ + page, + browser, + }, info) => { + test.setTimeout(180_000); + const { gpu, settings } = await setup(page, segments, indexed); + const warmSamples = 24; + const step = settings.radius * settings.spacing * 1.35; + const start = await screen(page, [(-step * warmSamples) / 2, 56, 0]); + const end = await screen(page, [(step * warmSamples) / 2, 56, 0]); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let sample = 0; sample <= warmSamples; sample++) { + if (sample) + await page.mouse.move(start.x + ((end.x - start.x) * sample) / warmSamples, start.y); + await page.waitForFunction( + (count) => (window as unknown as ProbeWindow).sculptDrawTimes.length >= count, + sample + 1, + { timeout: 30_000 }, + ); + } + const [firstMs, ...warmMs] = await page.evaluate( + () => (window as unknown as ProbeWindow).sculptDrawTimes, + ); + await page.mouse.up(); + await expect + .poll(() => inStore(page, (state) => state.sculpt?.past.length), { timeout: 60_000 }) + .toBe(1); + const sorted = [...warmMs].sort((a, b) => a - b); + const report = { + name, + triangles: segments * segments * 2, + indexed, + brushRadius: settings.radius, + browser: browser.version(), + os: [type(), release(), arch()].join(' '), + cpu: cpus()[0].model, + gpu, + firstMs, + warmP95Ms: sorted[Math.ceil(sorted.length * 0.95) - 1], + warmWorstMs: sorted.at(-1), + warmMs, + }; + console.log(JSON.stringify(report)); + await info.attach('sculpt-viewport.json', { + body: JSON.stringify(report, null, 2), + contentType: 'application/json', + }); + }); +} From 303fcdbe12d7e618aa15fedd47197c91796bef48 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:40:47 -0800 Subject: [PATCH 12/40] (fix) Preserve remote meshes across queued sculpt edits --- src/core/live.ts | 143 +++++++++++++++++------------- src/core/store.ts | 15 ++++ tests/e2e/mcp.spec.ts | 84 ++++++++++++++++++ tests/unit/sculpt-session.test.ts | 22 ++++- 4 files changed, 203 insertions(+), 61 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 0ea7ce1..59309dc 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -1,5 +1,6 @@ import type { BufferGeometry } from 'three'; import { uid } from './geometry'; +import { geometryBytes } from './history-budget'; import { appendGeometry, parseSceneDocument, readGeometry, validateLayout } from './scene-file'; import { committedScene, @@ -8,18 +9,39 @@ import { stopSharedSculptHistory, useEditor, useSharedHistory, + useSharedSculptQueueGuard, } from './store'; import { useXR } from './xr-session'; -import { matchesSculptTarget, type SculptTarget } from './sculpt-session'; +import { matchesSculptTarget, sculptHistoryBytes, type SculptTarget } from './sculpt-session'; import { keepUnchanged, mergeScenes, sharedScene } from './sync'; import type { GeometryLayout, SceneDocument } from './types'; -interface QueuedEdit { +interface OrdinaryEdit { before: SceneDocument; scene: SceneDocument; checkpoint: boolean; replace: boolean; - sculpt?: SculptTarget; +} + +interface SculptEdit { + sculpt: SculptTarget; + geometry: BufferGeometry; +} + +type QueuedEdit = OrdinaryEdit | SculptEdit; + +function applyQueuedEdit(scene: SceneDocument, edit: QueuedEdit): SceneDocument { + if (!('sculpt' in edit)) + return edit.replace ? edit.scene : mergeScenes(edit.before, edit.scene, scene); + const { sculpt, geometry } = edit; + return { + ...scene, + parts: scene.parts.map((part) => + part.id === sculpt.partId && part.geometry.uuid === sculpt.source + ? { ...part, geometry } + : part, + ), + }; } interface Message { @@ -80,14 +102,12 @@ export function joinLiveSession() { let latest: Message | null = null; let receiving = false; let pumping = false; - let sending = false; let applyingRemote = false; let connected = false; let closed = false; let viewMoved = false; - let dirty = false; - let checkpoint = false; - let replace = false; + let dirtyEdit: OrdinaryEdit | null = null; + let activeEdit: QueuedEdit | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; let awaitedSculptHistory = 0; @@ -104,6 +124,14 @@ export function joinLiveSession() { } }; + useSharedSculptQueueGuard((geometry) => { + if (!connected) return false; + const queued = [activeEdit, ...edits].flatMap((edit) => + edit && 'sculpt' in edit ? [edit.geometry] : [], + ); + return queued.length < 40 && geometryBytes([...queued, geometry]) <= sculptHistoryBytes; + }); + const unsubscribe = useEditor.subscribe((state, previous) => { const before = committedScene(previous); const scene = committedScene(state); @@ -123,12 +151,10 @@ export function joinLiveSession() { step.after.geometry === changed.geometry.uuid ) { // Keep each geometry stroke as a separate shared undo step, even during an upload. - if (dirty) edits.push({ before: confirmed.scene, scene: before, checkpoint, replace }); + if (dirtyEdit) edits.push(dirtyEdit); + dirtyEdit = null; edits.push({ - before, - scene, - checkpoint: true, - replace: false, + geometry: changed.geometry, sculpt: { partId: target.id, source: target.geometry.uuid, @@ -137,15 +163,23 @@ export function joinLiveSession() { scale: target.scale, }, }); - dirty = checkpoint = replace = false; } else { - dirty = true; - if (state.sceneEpoch !== previous.sceneEpoch) { + const replace = state.sceneEpoch !== previous.sceneEpoch; + if (replace) { edits.length = 0; - replace = true; + dirtyEdit = null; } - // An action that adds an undo step here starts a new one on the server; a drag extends it. - if (replace || state.past !== previous.past) checkpoint = true; + // Accumulate only ordinary edits, each relative to what this action actually changed. + // In particular, an optimistic sculpt mesh in both scenes must not enter this batch. + dirtyEdit = { + before: dirtyEdit?.before ?? before, + scene: + dirtyEdit && dirtyEdit.scene !== before + ? mergeScenes(before, scene, dirtyEdit.scene) + : scene, + checkpoint: replace || !!dirtyEdit?.checkpoint || state.past !== previous.past, + replace: replace || !!dirtyEdit?.replace, + }; } void pump(); }); @@ -176,16 +210,18 @@ export function joinLiveSession() { const local = committedScene(useEditor.getState()); const first = !confirmed; const replaced = !!confirmed && message.epoch !== confirmed.epoch; + const unsent = [...edits, dirtyEdit].filter((edit): edit is QueuedEdit => !!edit); + const replacing = unsent.some((edit) => !('sculpt' in edit) && edit.replace); let next = scene; - // This tab is about to replace the scene, so it keeps its own. - if (replace) next = local; - // Changes made on a scene that has since been replaced no longer apply. - else if (first || replaced) { - dirty = false; + // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. + if (!replacing && (first || replaced)) { + dirtyEdit = null; edits.length = 0; if (replaced && useEditor.getState().sculpt) useEditor.getState().setTool('select'); - } else if (dirty || sending || edits.length) - next = mergeScenes(confirmed!.scene, local, scene, 'ours'); + } else { + const pending = activeEdit ? [activeEdit, ...unsent] : unsent; + next = pending.reduce(applyQueuedEdit, scene); + } confirmed = { version: message.version, epoch: message.epoch, scene }; const [undo, redo] = message.history[client] ?? [0, 0]; useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); @@ -195,7 +231,7 @@ export function joinLiveSession() { awaitedSculptHistory = 0; stopSharedSculptHistory(); } - if (!replace && (first || replaced)) useEditor.getState().settleWarp(true); + if (!replacing && (first || replaced)) useEditor.getState().settleWarp(true); const shown = useEditor.getState().scene; if (first) useEditor.getState().markSaved(useEditor.getState().revision); // Keep a growing model in view, until the person watching takes over the camera. @@ -240,9 +276,7 @@ export function joinLiveSession() { /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ const refused = (reason?: string) => { edits.length = 0; - dirty = false; - replace = false; - checkpoint = true; + dirtyEdit = null; if (confirmed) { const { sculpt } = useEditor.getState(); show(confirmed.scene); @@ -263,32 +297,25 @@ export function joinLiveSession() { useEditor.setState({ liveStatus: 'disconnected', sharedHistory: null, past: [], future: [] }); }; - const sendEdit = async (queued?: QueuedEdit) => { + const sendEdit = async (edit: QueuedEdit) => { // Keep the submitted draft separate from any warp applied while this edit is in flight. const base = confirmed!; - const flags = queued - ? { checkpoint: queued.checkpoint, replace: queued.replace } - : { checkpoint, replace }; - const sculpt = queued?.sculpt; - if (!queued) dirty = checkpoint = replace = false; - sending = true; + const sculpt = 'sculpt' in edit ? edit.sculpt : undefined; + const checkpoint = 'sculpt' in edit || edit.checkpoint; + const replace = !('sculpt' in edit) && edit.replace; + activeEdit = edit; if (!sculpt) useEditor.getState().submitWarp(); try { - if (sculpt) { - const target = base.scene.parts.find((part) => part.id === sculpt.partId); - const result = queued.scene.parts.find((part) => part.id === sculpt.partId); + if ('sculpt' in edit) { + const target = base.scene.parts.find((part) => part.id === edit.sculpt.partId); // A request can succeed even when the connection drops before its response arrives. - if (target && target.geometry.uuid === result?.geometry.uuid) return; - if (!matchesSculptTarget(target, sculpt)) + if (target?.geometry.uuid === edit.geometry.uuid) return; + if (!matchesSculptTarget(target, edit.sculpt)) throw new Refusal( 'The sculpt target changed before the stroke reached the shared scene.', ); } - const scene = !queued - ? committedScene(useEditor.getState()) - : flags.replace - ? queued.scene - : mergeScenes(queued.before, queued.scene, base.scene); + const scene = applyQueuedEdit(base.scene, edit); for (const { geometry } of scene.parts) { const key = geometry.uuid; if (known.has(key)) continue; @@ -300,7 +327,8 @@ export function joinLiveSession() { client, base: base.version, epoch: base.epoch, - ...flags, + checkpoint, + replace, sculpt, scene: sharedScene(scene), }); @@ -312,22 +340,16 @@ export function joinLiveSession() { if (error instanceof Refusal) refused(error.message); else { // Kept for when the agent can be reached again. - if (queued) edits.unshift(queued); - else { - dirty = true; - checkpoint ||= flags.checkpoint; - replace ||= flags.replace; - } + edits.unshift(edit); if (!sculpt) useEditor.getState().retryWarp(); lost(); } } finally { - sending = false; + activeEdit = null; } }; const sendHistory = async (direction: 'undo' | 'redo') => { - sending = true; try { const response = await post(`live/${direction}`, { client }); if (!response.ok) { @@ -350,8 +372,6 @@ export function joinLiveSession() { ); } catch { lost(); - } finally { - sending = false; } }; @@ -360,9 +380,11 @@ export function joinLiveSession() { pumping = true; try { while (!closed && connected && confirmed && awaited <= confirmed.version) { - if (edits.length) await sendEdit(edits.shift()); - else if (dirty) await sendEdit(); - else if (requests.length) await sendHistory(requests.shift()!); + const edit = edits.shift() ?? dirtyEdit; + if (edit) { + if (edit === dirtyEdit) dirtyEdit = null; + await sendEdit(edit); + } else if (requests.length) await sendHistory(requests.shift()!); else break; } } finally { @@ -407,6 +429,7 @@ export function joinLiveSession() { closed = true; source.close(); unsubscribe(); + useSharedSculptQueueGuard(null); useSharedHistory(null); stopSharedSculptHistory(); useEditor.setState({ liveStatus: null }); diff --git a/src/core/store.ts b/src/core/store.ts index c8169ff..dbd9131 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -3493,6 +3493,15 @@ export const useEditor = create((set, get) => ({ state.notify('This stroke exceeded the mesh size limit for Sculpt.', 'info'); return false; } + if (geometry !== part.geometry && sharedSculptQueueGuard && !sharedSculptQueueGuard(geometry)) { + state.notify( + state.liveStatus === 'disconnected' + ? 'Reconnect to the shared scene to commit sculpt strokes.' + : 'Wait for pending sculpt strokes to reach the shared scene.', + 'info', + ); + return false; + } const step = { before: { geometry: part.geometry.uuid, mask: sculpt.mask }, after: { geometry: geometry.uuid, mask }, @@ -4988,6 +4997,12 @@ useEditor.subscribe((state, previous) => { recordNotification(state.toast.message, state.toast.kind); }); +let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; + +export function useSharedSculptQueueGuard(guard: typeof sharedSculptQueueGuard) { + sharedSculptQueueGuard = guard; +} + let sharedHandlers: { undo: () => void; redo: () => void } | null = null; /** In a shared scene, undo and redo step through this tab's own changes on the server. */ diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index d9bd04b..28421f8 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -495,3 +495,87 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos ).toBeVisible(); expect((await call('get_scene')).parts[0].position).toEqual([2, 0, 0]); }); + +test('an ordinary edit between queued strokes preserves a newer remote mesh', async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = (await page.locator('canvas').boundingBox())!; + const x = canvas.x + canvas.width / 2; + const y = canvas.y + canvas.height / 2; + const editUrl = /\/live\/edit$/; + let unblock = () => {}; + const blocked = new Promise((resolve) => { + unblock = resolve; + }); + let applyRemote = () => {}; + const remoteReady = new Promise((resolve) => { + applyRemote = resolve; + }); + let held = false; + let completed = false; + let remoteGeometry = ''; + await page.route(editUrl, async (route) => { + const body = route.request().postDataJSON(); + if (held || !body.sculpt) return await route.continue(); + held = true; + await remoteReady; + const accepted = await route.fetch(); + if (accepted.ok()) { + const { version } = await accepted.json(); + remoteGeometry = body.sculpt.source; + // Replace the stroke's mesh using a separate author's edit before this tab can send again. + const remote = await page.request.post(route.request().url(), { + data: { + client: 'remote-editor', + base: version, + epoch: body.epoch, + checkpoint: true, + scene: { + ...body.scene, + parts: body.scene.parts.map((part: { id: string }) => ({ + ...part, + ...(part.id === body.sculpt.partId + ? { geometry: remoteGeometry, name: 'Remotely edited block' } + : {}), + })), + }, + }, + }); + completed = remote.ok(); + } + await blocked; + await route.fulfill({ response: accepted }); + }); + + await page.mouse.click(x + 8, y - 7); + await expect.poll(() => held).toBe(true); + await page.getByTitle('Rename assembly').click(); + await page.getByRole('textbox', { name: 'Assembly name' }).fill('Renamed while sculpting'); + await page.getByRole('textbox', { name: 'Assembly name' }).press('Enter'); + await page.mouse.click(x + 16, y - 7); + applyRemote(); + await expect.poll(() => completed).toBe(true); + await expect(page.locator(part('Remotely edited block'))).toBeVisible(); + const ordinary = page.waitForRequest( + (request) => editUrl.test(request.url()) && !request.postDataJSON().sculpt, + ); + unblock(); + const request = await ordinary; + expect((await request.response())?.status()).toBe(200); + await expect( + page.getByText(/sculpt target changed before the stroke reached the shared scene/i), + ).toBeVisible(); + expect((await call('get_scene')).name).toBe('Renamed while sculpting'); + expect(request.postDataJSON().scene.parts[0].geometry).toBe(remoteGeometry); +}); diff --git a/tests/unit/sculpt-session.test.ts b/tests/unit/sculpt-session.test.ts index 850f10a..63e85f3 100644 --- a/tests/unit/sculpt-session.test.ts +++ b/tests/unit/sculpt-session.test.ts @@ -2,7 +2,12 @@ import { BoxGeometry } from 'three'; import { afterEach, describe, expect, it } from 'vitest'; import { EditConflict, SharedDocument } from '../../mcp/document'; import type { SculptStrokeCommit } from '../../src/core/sculpt-session'; -import { restoreSculptAfterRefusal, useEditor, useSharedHistory } from '../../src/core/store'; +import { + restoreSculptAfterRefusal, + useEditor, + useSharedHistory, + useSharedSculptQueueGuard, +} from '../../src/core/store'; import type { Part, SceneDocument } from '../../src/core/types'; function fixture() { @@ -47,6 +52,7 @@ function stroke(patch: Partial): SculptStrokeCommit { afterEach(() => { useSharedHistory(null); + useSharedSculptQueueGuard(null); useEditor.setState({ sharedHistory: null }); useEditor.getState().setScene({ name: 'Empty', parts: [], joints: [] }); }); @@ -104,6 +110,20 @@ describe('sculpt session', () => { expect(store().past).toHaveLength(0); }); + it('leaves the mesh and weights unchanged when the shared stroke queue is full', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + useSharedSculptQueueGuard(() => false); + store().changeSculptMask('invert'); + const session = store().sculpt; + expect(store().commitSculpt(stroke({ geometry: part.geometry.clone(), mask: null }))).toBe( + false, + ); + expect(store().scene).toBe(scene); + expect(store().sculpt).toBe(session); + expect(store().toast?.message).toMatch(/pending sculpt strokes/); + }); + it('restores the appropriate weights on shared undo, redo, and refusal', () => { const { part, scene } = openSculpt(); const store = useEditor.getState; From b77bd6afa331b14ffb783c32f416f1ef645a8d5a Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:42:06 -0800 Subject: [PATCH 13/40] (fix) Preserve sculpt history across shared document undo --- src/core/live.ts | 35 +++++++++++++++++++++---------- src/core/sculpt-session.ts | 2 +- src/core/store.ts | 21 +++++++++++++------ tests/unit/sculpt-session.test.ts | 18 ++++++++++++++-- 4 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 59309dc..66e7cae 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -30,6 +30,11 @@ interface SculptEdit { type QueuedEdit = OrdinaryEdit | SculptEdit; +interface HistoryRequest { + direction: 'undo' | 'redo'; + sculpt: number | null; +} + function applyQueuedEdit(scene: SceneDocument, edit: QueuedEdit): SceneDocument { if (!('sculpt' in edit)) return edit.replace ? edit.scene : mergeScenes(edit.before, edit.scene, scene); @@ -96,7 +101,7 @@ export function joinLiveSession() { /** Mesh keys the server already holds. */ const known = new Set(); const edits: QueuedEdit[] = []; - const requests: ('undo' | 'redo')[] = []; + const requests: HistoryRequest[] = []; /** The last scene the server sent. Unsent changes here are relative to it. */ let confirmed: { version: number; epoch: number; scene: SceneDocument } | null = null; let latest: Message | null = null; @@ -110,7 +115,7 @@ export function joinLiveSession() { let activeEdit: QueuedEdit | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; - let awaitedSculptHistory = 0; + let awaitedHistory: { version: number; sculpt: number | null } | null = null; const notify = (message: string, kind: 'error' | 'info' = 'error') => useEditor.getState().notify(message, kind); @@ -227,9 +232,9 @@ export function joinLiveSession() { useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); const before = new Set(local.parts.map((part) => part.id)); show(next); - if (awaitedSculptHistory && message.version >= awaitedSculptHistory) { - awaitedSculptHistory = 0; - stopSharedSculptHistory(); + if (awaitedHistory && message.version >= awaitedHistory.version) { + stopSharedSculptHistory(true, awaitedHistory.sculpt); + awaitedHistory = null; } if (!replacing && (first || replaced)) useEditor.getState().settleWarp(true); const shown = useEditor.getState().scene; @@ -291,6 +296,7 @@ export function joinLiveSession() { const lost = () => { if (closed) return; connected = false; + awaitedHistory = null; useSharedHistory(null); stopSharedSculptHistory(); // While the agent is away, undo here covers only changes made in the meantime. @@ -349,11 +355,11 @@ export function joinLiveSession() { } }; - const sendHistory = async (direction: 'undo' | 'redo') => { + const sendHistory = async ({ direction, sculpt }: HistoryRequest) => { try { const response = await post(`live/${direction}`, { client }); if (!response.ok) { - stopSharedSculptHistory(); + stopSharedSculptHistory(false, sculpt); notify((await errorOf(response)) ?? `This could not be ${direction}ne.`); return; } @@ -363,8 +369,9 @@ export function joinLiveSession() { empty?: boolean; }; awaited = result.version; - if (result.changed && awaited > confirmed!.version) awaitedSculptHistory = awaited; - else stopSharedSculptHistory(); + if (sculpt && result.changed && awaited > confirmed!.version) + awaitedHistory = { version: awaited, sculpt }; + else stopSharedSculptHistory(result.changed, sculpt); if (!result.changed && !result.empty) notify( `Nothing to ${direction}: ${other} has since changed everything that step touched.`, @@ -394,11 +401,17 @@ export function joinLiveSession() { const history = { undo: () => { - requests.push('undo'); + requests.push({ + direction: 'undo', + sculpt: useEditor.getState().sculpt?.pending?.id ?? null, + }); void pump(); }, redo: () => { - requests.push('redo'); + requests.push({ + direction: 'redo', + sculpt: useEditor.getState().sculpt?.pending?.id ?? null, + }); void pump(); }, }; diff --git a/src/core/sculpt-session.ts b/src/core/sculpt-session.ts index f5afc59..388610a 100644 --- a/src/core/sculpt-session.ts +++ b/src/core/sculpt-session.ts @@ -53,7 +53,7 @@ export interface SculptSession { revision: number; past: SculptStep[]; future: SculptStep[]; - pending: { direction: 'undo' | 'redo'; step: SculptStep } | null; + pending: { id: number; direction: 'undo' | 'redo'; step: SculptStep } | null; } export function sculptDefaults( diff --git a/src/core/store.ts b/src/core/store.ts index dbd9131..cf43596 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -2040,7 +2040,11 @@ function moveHistory(direction: HistoryDirection) { if (step.before.geometry === step.after.geometry) useEditor.setState({ sculpt: next }); else if (sharedHandlers) { useEditor.setState({ - sculpt: { ...sculpt, pending: { direction, step }, revision: next.revision }, + sculpt: { + ...sculpt, + pending: { id: next.revision, direction, step }, + revision: next.revision, + }, }); sharedHandlers[direction](); } else { @@ -6972,12 +6976,17 @@ export function restoreSculptAfterRefusal(scene: SceneDocument, sculpt: SculptSe }); } -export function stopSharedSculptHistory() { +export function stopSharedSculptHistory(applied = false, pendingId?: number | null) { const { sculpt } = useEditor.getState(); - if (sculpt?.pending) - useEditor.setState({ - sculpt: { ...sculpt, past: [], future: [], pending: null, revision: nextSculptRevision() }, - }); + if (!sculpt?.pending || (pendingId !== undefined && pendingId !== sculpt.pending.id)) return; + useEditor.setState({ + sculpt: { + ...sculpt, + ...(!applied ? { past: [], future: [] } : {}), + pending: null, + revision: nextSculptRevision(), + }, + }); } useEditor.subscribe((state, previous) => { diff --git a/tests/unit/sculpt-session.test.ts b/tests/unit/sculpt-session.test.ts index 63e85f3..66a5e0b 100644 --- a/tests/unit/sculpt-session.test.ts +++ b/tests/unit/sculpt-session.test.ts @@ -4,6 +4,7 @@ import { EditConflict, SharedDocument } from '../../mcp/document'; import type { SculptStrokeCommit } from '../../src/core/sculpt-session'; import { restoreSculptAfterRefusal, + stopSharedSculptHistory, useEditor, useSharedHistory, useSharedSculptQueueGuard, @@ -133,12 +134,25 @@ describe('sculpt session', () => { const initialMask = store().sculpt!.mask; expect(store().commitSculpt(stroke({ geometry, mask: null }))).toBe(true); - useEditor.setState({ sharedHistory: { undo: 1, redo: 0 } }); + useEditor.setState({ sharedHistory: { undo: 2, redo: 0 } }); + let ordinaryUndo = false; useSharedHistory({ - undo: () => store().receiveScene(scene), + undo: () => { + if (ordinaryUndo) store().receiveScene(scene); + else { + const pending = store().sculpt!.pending!.id; + store().receiveScene({ ...next, name: 'Ordinary change reverted' }); + stopSharedSculptHistory(true, pending); + ordinaryUndo = true; + } + }, redo: () => store().receiveScene(next), }); store().undo(); + expect(store().sculpt!.pending).toBeNull(); + expect(store().sculpt!.past).toHaveLength(2); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().undo(); expect(store().sculpt!.mask).toBe(initialMask); expect(store().scene.parts[0].geometry).toBe(part.geometry); store().redo(); From 623055d1fd5e6aebb225c08a69d0045e6c61d54f Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:44:17 -0800 Subject: [PATCH 14/40] (fix) Commit released strokes and preserve pen controls --- src/components/SculptPointer.tsx | 197 +++++++++++++++++++++---------- tests/e2e/sculpt.spec.ts | 68 +++++++++-- 2 files changed, 194 insertions(+), 71 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index c345efb..6e4e4be 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -16,22 +16,37 @@ import { type Intersection, } from 'three'; import { acceleratedRaycast } from 'three-mesh-bvh'; -import { SculptMesh, type SculptDab } from '../core/sculpt-mesh'; +import { clearSculptIncidence, SculptMesh, type SculptDab } from '../core/sculpt-mesh'; +import { triangleCount } from '../core/geometry'; +import { workerIndexTriangles } from '../core/spatial-index'; import { useEditor } from '../core/store'; import type { Part, SculptureSettings } from '../core/types'; import { partMeshes } from '../xr/part-meshes'; +import { boundsEntry } from './RefinePointer'; type Sample = Pick< PointerEvent, - 'clientX' | 'clientY' | 'pressure' | 'pointerType' | 'tiltX' | 'tiltY' | 'twist' + | 'clientX' + | 'clientY' + | 'pressure' + | 'pointerType' + | 'tiltX' + | 'tiltY' + | 'twist' + | 'shiftKey' + | 'altKey' >; type Hit = Pick; +const maxQueuedDabs = 8; + const lerp = (a: number, b: number, t: number) => a + (b - a) * t; function interpolate(a: Sample, b: Sample, t: number): Sample { return { pointerType: b.pointerType, + shiftKey: b.shiftKey, + altKey: b.altKey, clientX: lerp(a.clientX, b.clientX, t), clientY: lerp(a.clientY, b.clientY, t), pressure: lerp(a.pressure, b.pressure, t), @@ -73,6 +88,7 @@ function hitFrom(intersection: Intersection, mesh: Mesh): Hit | null { interface Stroke { id: number; target: Part; + mask: Float32Array | null; epoch: number; revision: number; own: Mesh; @@ -82,12 +98,11 @@ interface Stroke { controls: { enabled: boolean } | null; controlsEnabled: boolean; brush: SculptDab['brush']; - inverted: boolean; - softenMask: boolean; + eraser: boolean; last: Sample; + latest: Sample; pending: Sample[]; changed: boolean; - end: boolean; spacing: number; first: Hit; grabPoint: Vector3; @@ -206,15 +221,32 @@ export function SculptPointer() { stroke.draft.raycast(ray, mesh, hits); return hits; }; - const pick = (sample: Sample, own: Mesh): Hit | null => { + const pick = (sample: Sample, own: Mesh, exactOcclusion = false): Hit | null => { setRay(sample); - let closest: Intersection | undefined; + const hit = intersect(own)[0]; + if (!hit || !visible(own)) return null; for (const mesh of partMeshes.values()) { - if (!visible(mesh)) continue; - const hit = intersect(mesh)[0]; - if (hit && (!closest || hit.distance < closest.distance)) closest = hit; + if (mesh === own || !visible(mesh)) continue; + const geometry = mesh.geometry; + if (geometry.boundsTree || triangleCount(geometry) <= workerIndexTriangles) { + const other = intersect(mesh)[0]; + if (other && other.distance <= hit.distance) return null; + continue; + } + const entry = boundsEntry(ray.ray, mesh); + if (entry === null || entry > hit.distance) continue; + // Exact fallback is reserved for stroke samples near a mesh whose index is unavailable. + if (!exactOcclusion) return null; + const hits: Intersection[] = []; + ray.far = hit.distance; + try { + Mesh.prototype.raycast.call(mesh, ray, hits); + } finally { + ray.far = Infinity; + } + if (hits.length) return null; } - return closest?.object === own ? hitFrom(closest, own) : null; + return hitFrom(hit, own); }; const mirror = (hit: Hit, own: Mesh, radius: number): Hit | null => { const inverse = new Matrix4().copy(own.matrixWorld).invert(); @@ -266,11 +298,28 @@ export function SculptPointer() { ); return tangent.normalize().applyAxisAngle(hit.normal, angle); }; - const show = (i: number, hit: Hit | null, radius: number, aspect: number, angle: number) => { + const reflect = (vector: Vector3, own: Mesh) => { + const local = vector + .clone() + .applyMatrix3(new Matrix3().setFromMatrix4(own.matrixWorld.clone().invert())); + local.x = -local.x; + return local.applyMatrix3(new Matrix3().setFromMatrix4(own.matrixWorld)); + }; + const reflectedTangent = (tangent: Vector3, hit: Hit, own: Mesh) => { + const reflected = reflect(tangent, own); + reflected.addScaledVector(hit.normal, -reflected.dot(hit.normal)); + return reflected.lengthSq() > 1e-8 ? reflected.normalize() : tangentAt(hit, 0); + }; + const show = ( + i: number, + hit: Hit | null, + radius: number, + aspect: number, + tangent?: Vector3, + ) => { const cursor = cursors[i]; - cursor.visible = !!hit && radius > 0; - if (!hit) return; - const tangent = tangentAt(hit, angle); + cursor.visible = !!hit && !!tangent && radius > 0; + if (!hit || !tangent) return; cursor.position.copy(hit.point).addScaledVector(hit.normal, radius * 0.006); cursor.quaternion.setFromRotationMatrix( new Matrix4().makeBasis( @@ -335,8 +384,16 @@ export function SculptPointer() { const hit = pick(hover, own); const aspect = settings.brush === 'draw' ? settings.aspect : 1; const angle = footprint(settings, hover); - show(0, hit, radius, aspect, angle); - show(1, hit && settings.symmetry ? mirror(hit, own, radius) : null, radius, aspect, -angle); + const tangent = hit ? tangentAt(hit, angle) : undefined; + const twin = hit && settings.symmetry ? mirror(hit, own, radius) : null; + show(0, hit, radius, aspect, tangent); + show( + 1, + twin, + radius, + aspect, + twin && tangent ? reflectedTangent(tangent, twin, own) : undefined, + ); } displayMask(); invalidate(); @@ -352,7 +409,12 @@ export function SculptPointer() { if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; if (accept && active.changed) { const geometry = active.draft.finish(); - const mask = active.draft.getMask(); + const grew = + geometry && + geometry.getAttribute('position').count !== + active.target.geometry.getAttribute('position').count; + const mask = + active.brush === 'mask' || (grew && active.mask) ? active.draft.getMask() : active.mask; const { id: partId, geometry: source, position, quaternion, scale } = active.target; if ( !useEditor.getState().commitSculpt({ @@ -364,7 +426,7 @@ export function SculptPointer() { quaternion, scale, geometry, - mask: mask.some((value) => value > 0) ? mask : null, + mask: mask?.some((value) => value > 0) ? mask : null, }) ) geometry?.dispose(); @@ -382,14 +444,16 @@ export function SculptPointer() { }; const apply = (active: Stroke, sample: Sample) => { const s = active.settings; - const hit = active.brush === 'grab' ? active.first : pick(sample, active.own); + const brush = + sample.shiftKey && !active.eraser && active.brush !== 'mask' ? 'smooth' : active.brush; + const hit = brush === 'grab' ? active.first : pick(sample, active.own, true); if (!hit) return; const p = pressure(sample, s); const strength = s.strength * (s.pressureStrength ? p : 1); if (!(strength > 0)) return; const radius = s.radius * (s.pressureRadius ? Math.max(0.08, p) : 1); let angle = footprint(s, sample); - if (active.brush === 'crease' && active.applied) { + if (brush === 'crease' && active.applied) { const dx = sample.clientX - active.applied.clientX; const dy = active.applied.clientY - sample.clientY; if (dx || dy) angle = Math.atan2(dy, dx); @@ -397,11 +461,7 @@ export function SculptPointer() { active.applied = sample; const tangent = tangentAt(hit, angle); const twin = - active.brush === 'grab' - ? active.grabMirror - : s.symmetry - ? mirror(hit, active.own, radius) - : null; + brush === 'grab' ? active.grabMirror : s.symmetry ? mirror(hit, active.own, radius) : null; let grab: Vector3 | undefined; let mirroredGrab: Vector3 | undefined; if (active.brush === 'grab') { @@ -411,13 +471,7 @@ export function SculptPointer() { const point = ray.ray.at(projection / ray.ray.direction.dot(direction), new Vector3()); grab = point.clone().sub(active.grabPoint); active.grabPoint.copy(point); - if (twin) { - const local = grab - .clone() - .applyMatrix3(new Matrix3().setFromMatrix4(active.own.matrixWorld.clone().invert())); - local.x = -local.x; - mirroredGrab = local.applyMatrix3(new Matrix3().setFromMatrix4(active.own.matrixWorld)); - } + if (twin) mirroredGrab = reflect(grab, active.own); } active.changed = active.draft.dab({ @@ -426,16 +480,16 @@ export function SculptPointer() { strength, detail: s.detail, minEdge: s.minEdge, - brush: active.brush, + brush, falloff: s.falloff, - inverted: active.inverted, + inverted: active.eraser || sample.altKey, pinch: s.pinch, - softenMask: active.softenMask, + softenMask: brush === 'mask' && sample.shiftKey, grab, tangent, - aspect: active.brush === 'draw' ? s.aspect : 1, + aspect: brush === 'draw' ? s.aspect : 1, mirror: twin - ? { ...twin, tangent: tangentAt(twin, -angle), grab: mirroredGrab } + ? { ...twin, tangent: reflectedTangent(tangent, twin, active.own), grab: mirroredGrab } : undefined, }) || active.changed; }; @@ -450,12 +504,22 @@ export function SculptPointer() { const sample = active.pending.shift(); if (sample) apply(active, sample); } while (active.pending.length && performance.now() < until); - if (!active.pending.length && active.end) detach(true); - else if (active.pending.length) schedule(); + if (active.pending.length) schedule(); } refresh(); }); }; + const queue = (active: Stroke, sample: Sample) => { + active.pending.push(sample); + if (active.pending.length > maxQueuedDabs * 2) { + // Keep both endpoints and evenly thin old dabs when input outruns rendering. + const pending = active.pending; + active.pending = Array.from( + { length: maxQueuedDabs }, + (_, i) => pending[Math.round((i * (pending.length - 1)) / (maxQueuedDabs - 1))], + ); + } + }; const enqueue = (active: Stroke, incoming: Sample, final = false) => { const sample = final ? incoming @@ -464,16 +528,24 @@ export function SculptPointer() { sample.clientX - active.last.clientX, sample.clientY - active.last.clientY, ); - const steps = Math.min(32, Math.floor(distance / active.spacing)); + const scale = active.settings.pressureRadius + ? Math.max(0.08, pressure(sample, active.settings)) + : 1; + const spacing = Math.max(0.5, active.spacing * scale); + const steps = Math.min(32, Math.floor(distance / spacing)); if (steps) { + const interval = Math.max(spacing, distance / 32); for (let i = 1; i <= steps; i++) - active.pending.push(interpolate(active.last, sample, i / steps)); + queue(active, interpolate(active.last, sample, (interval * i) / distance)); + active.last = active.pending.at(-1)!; + if (!final || distance - interval * steps <= 0.1) return; + queue(active, sample); } else if ( final ? distance > 0.1 : distance < 0.1 && Math.abs(sample.pressure - active.last.pressure) > 0.015 ) { - active.pending.push(sample); + queue(active, sample); } else return; active.last = sample; }; @@ -502,7 +574,7 @@ export function SculptPointer() { const target = state.scene.parts.find((part) => part.id === sculpt.partId); const own = target && partMeshes.get(target.id); if (!target || !own || target.locked || !visible(own)) return; - const hit = pick(event, own); + const hit = pick(event, own, true); if (!hit) return; event.preventDefault(); event.stopImmediatePropagation(); @@ -534,17 +606,11 @@ export function SculptPointer() { const draft = cached ?? new SculptMesh(target.geometry, own.matrixWorld, sculpt.mask ?? undefined); const eraser = event.button === 5; - const brush = - settings.brush === 'mask' - ? 'mask' - : eraser - ? 'draw' - : event.shiftKey - ? 'smooth' - : settings.brush; + const brush = settings.brush === 'mask' ? 'mask' : eraser ? 'draw' : settings.brush; stroke = { id: event.pointerId, target, + mask: sculpt.mask, epoch: state.sceneEpoch, revision: sculpt.revision, own, @@ -554,17 +620,16 @@ export function SculptPointer() { controlsEnabled: controls?.enabled ?? false, settings, brush, - inverted: eraser || event.altKey, - softenMask: brush === 'mask' && event.shiftKey, + eraser, first: hit, grabPoint: hit.point.clone(), grabMirror: brush === 'grab' && settings.symmetry ? mirror(hit, own, settings.radius) : null, applied: null, last: event, + latest: event, pending: [event], changed: false, - end: false, spacing: Math.max(0.75, radiusPixels * settings.spacing), }; if (controls) controls.enabled = false; @@ -576,8 +641,8 @@ export function SculptPointer() { if (stroke) { if (event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); - if (stroke.end) return; const events = event.getCoalescedEvents?.() ?? []; + stroke.latest = events.at(-1) ?? event; for (const sample of events.length ? events : [event]) enqueue(stroke, sample); } else if (!canvas.contains(event.target as Node) || event.pointerType === 'touch') return; hover = event; @@ -586,19 +651,30 @@ export function SculptPointer() { const release = (event: PointerEvent) => { if (!stroke || event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); + const { pressure, pointerType, tiltX, tiltY, twist } = stroke.latest; enqueue( stroke, - { ...interpolate(stroke.last, event, 1), pressure: stroke.last.pressure }, + { + clientX: event.clientX, + clientY: event.clientY, + pressure, + pointerType, + tiltX, + tiltY, + twist, + shiftKey: event.shiftKey, + altKey: event.altKey, + }, true, ); - stroke.end = true; suppressClick = true; window.clearTimeout(clickTimer); clickTimer = window.setTimeout(() => (suppressClick = false), 300); - schedule(); + for (const sample of stroke.pending) apply(stroke, sample); + detach(true); }; const cancel = (event: PointerEvent) => { - if (stroke?.id === event.pointerId && !stroke.end) detach(false); + if (stroke?.id === event.pointerId) detach(false); }; const escape = (event: KeyboardEvent) => { if (event.key !== 'Escape' || !stroke) return; @@ -664,6 +740,7 @@ export function SculptPointer() { detach(false); window.clearTimeout(warmTimer); discardWarm(); + clearSculptIncidence(); scene.remove(...cursors, overlay); cursorShape.dispose(); cursorPaint.dispose(); diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 69e9d40..ee9a295 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -19,8 +19,8 @@ const block = { ], }; -async function openSculpt(page: Page) { - await openScene(page, block); +async function openSculpt(page: Page, scene = block) { + await openScene(page, scene); await page.locator('.part-select[title="Coarse block"]').click(); await page.keyboard.press('1'); await page.keyboard.press('Home'); @@ -68,6 +68,53 @@ async function penTap(page: Page, pressure: number) { } } +test('only sculpts the selected part when its surface is visible under the tip', async ({ + page, +}) => { + await openSculpt(page, { + ...block, + parts: [block.parts[0], { ...block.parts[0], id: 'cover', name: 'Cover', position: [0, 0, 6] }], + }); + const before = await mesh(page); + await penTap(page, 0.9); + await page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + expect(await mesh(page)).toEqual(before); + await page.getByRole('button', { name: 'Hide Cover' }).click(); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + +test('commits a released stroke before a tool change in the same frame', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (spot) => { + const storeUrl = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!; + const { useEditor } = await import(storeUrl); + const canvas = document.querySelector('canvas')!; + const event = { + clientX: spot.x, + clientY: spot.y, + pointerId: 42, + pointerType: 'pen', + isPrimary: true, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...event, buttons: 1, pressure: 0.8 })); + canvas.dispatchEvent(new PointerEvent('pointerup', event)); + useEditor.getState().setTool('select'); + }, point); + expect((await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + test('draws into a coarse face with pen pressure and undoes topology with displacement', async ({ page, }) => { @@ -138,14 +185,14 @@ test('cancels an active stroke and reopens the completed stroke from disk', asyn test('a fully inverted mask protects the coarse surface until cleared', async ({ page }) => { await openSculpt(page); const before = await mesh(page); - await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); await page.getByRole('button', { name: /invert mask/i }).click(); - await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('draw'); + await page.getByRole('button', { name: 'Draw', exact: true }).click(); await penTap(page, 0.9); expect(await mesh(page)).toEqual(before); - await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); await page.getByRole('button', { name: /clear mask/i }).click(); - await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('draw'); + await page.getByRole('button', { name: 'Draw', exact: true }).click(); await penTap(page, 0.9); await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); }); @@ -156,7 +203,7 @@ test('mask paint subdivides without displacement and restores weights with undo await openSculpt(page); const before = await mesh(page); const weights = () => inStore(page, (state) => Array.from(state.sculpt?.mask ?? [])); - await page.getByRole('combobox', { name: 'Brush', exact: true }).selectOption('mask'); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); await penTap(page, 0.8); await expect.poll(async () => (await weights()).some((weight) => weight > 0)).toBe(true); const painted = await mesh(page); @@ -176,20 +223,19 @@ test('applies Clay Buildup and Inflate and keeps their falloff settings independ }) => { await openSculpt(page); const before = await mesh(page); - const brush = page.getByRole('combobox', { name: 'Brush', exact: true }); const falloff = page.getByRole('combobox', { name: 'Falloff' }); await page.getByText('Advanced brush settings', { exact: true }).click(); - await brush.selectOption({ label: 'Clay Buildup' }); + await page.getByRole('button', { name: 'Clay Buildup', exact: true }).click(); await falloff.selectOption('hard'); await penTap(page, 0.9); await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); await page.keyboard.press('ControlOrMeta+z'); await expect.poll(() => mesh(page)).toEqual(before); - await brush.selectOption({ label: 'Inflate/Deflate' }); + await page.getByRole('button', { name: 'Inflate/Deflate', exact: true }).click(); await expect(falloff).toHaveValue('soft'); await penTap(page, 0.9); await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); - await brush.selectOption({ label: 'Clay Buildup' }); + await page.getByRole('button', { name: 'Clay Buildup', exact: true }).click(); await expect(falloff).toHaveValue('hard'); await page.getByRole('button', { name: 'Reset brush settings' }).click(); await expect(falloff).toHaveValue('soft'); From 6a83cc355dfc07c47bf00ad3bb1b117d61bc61a6 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:45:03 -0800 Subject: [PATCH 15/40] (docs) Record sculpt verification and viewport timings --- .../plans/2026-11-23-browser-sculpting.md | 32 +++++++++++++++---- tests/unit/sculpt-benchmark.test.ts | 9 +----- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/docs/superpowers/plans/2026-11-23-browser-sculpting.md b/docs/superpowers/plans/2026-11-23-browser-sculpting.md index 6e876c6..d6133fc 100644 --- a/docs/superpowers/plans/2026-11-23-browser-sculpting.md +++ b/docs/superpowers/plans/2026-11-23-browser-sculpting.md @@ -3,16 +3,36 @@ Implement the [Sculpt v1 design](../specs/2026-11-23-browser-sculpting-design.md) in the existing Three.js workbench. Keep working geometry separate from committed parts. -- [ ] Build and unit-test the editable mesh and brush kernel in `src/core/sculpt-mesh.ts`. +- [x] Build and unit-test the editable mesh and brush kernel in `src/core/sculpt-mesh.ts`. Verify local conforming subdivision of a coarse triangle, connected footprints, masks, seam interpolation, bounded growth, and brush-specific displacement. -- [ ] Add the Sculpt tool, settings and history in `src/core/store.ts`, +- [x] Add the Sculpt tool, settings and history in `src/core/store.ts`, `src/components/SculptControls.tsx` and the existing workbench tool entry points. Verify target identity, visibility and lock eligibility before accepting geometry. -- [ ] Connect native pointer input and the editable preview in `src/components/SculptPointer.tsx` +- [x] Connect native pointer input and the editable preview in `src/components/SculptPointer.tsx` and `src/components/Viewport.tsx`. Verify pressure and orientation, capture and cancellation, occlusion, mask preview, symmetry and a single checkpoint per accepted stroke. -- [ ] Exercise the workflow through the viewport, including undo/redo, automatic detail, +- [x] Exercise the workflow through the viewport, including undo/redo, automatic detail, masking and save/reopen. Run the unit suite and production build. -- [ ] Measure dense-mesh stroke latency and memory. Record physical Wacom results by OS, - browser, tablet and driver before claiming compatibility. +- [x] Measure coarse and dense draft timing and committed mesh size. The sculpt history budget + is 256 MiB for geometry and 64 MiB for mask snapshots. +- [ ] Record physical Wacom results by OS, browser, tablet and driver before claiming compatibility. + +## Viewport measurements + +Chrome 158 on Apple M3 with ANGLE Metal. Times cover pointer receipt through Three.js draw +submission for a fitted 3 mm Draw brush. The probe sends each sample after the previous changed +draw. Queued input, GPU completion, and display presentation need separate measurement. + +| Fixture | First draw | Warm p95 | Warm worst | +| --------------------------- | ---------: | -------: | ---------: | +| 2 triangles | 25.2 ms | 17.5 ms | 17.6 ms | +| 999,698 indexed triangles | 88.0 ms | 25.7 ms | 26.1 ms | +| 999,698 unindexed triangles | 387.9 ms | 29.2 ms | 29.8 ms | + +The dense indexed CPU fixture used about 28 MB per committed mesh. Topology changes on dense +meshes may briefly delay the next stroke while picking is rebuilt. The viewport measurements +exceeded the 60 Hz frame budget on the tested fixtures. + +Run `KITBASHER_SCULPT_VIEWPORT_BENCH=1 npm run test:e2e -- tests/e2e/sculpt-benchmark.spec.ts` to +repeat the viewport measurements. diff --git a/tests/unit/sculpt-benchmark.test.ts b/tests/unit/sculpt-benchmark.test.ts index 82cdc5f..79bbf57 100644 --- a/tests/unit/sculpt-benchmark.test.ts +++ b/tests/unit/sculpt-benchmark.test.ts @@ -2,14 +2,7 @@ import { it, expect } from 'vitest'; import { writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { - DoubleSide, - Matrix4, - Mesh, - MeshBasicMaterial, - PlaneGeometry, - Raycaster, -} from 'three'; +import { DoubleSide, Matrix4, Mesh, MeshBasicMaterial, PlaneGeometry, Raycaster } from 'three'; import { MeshBVH } from 'three-mesh-bvh'; import { SculptMesh } from '../../src/core/sculpt-mesh'; From ea00c929b44cb001c56696f25742c725a5ca1885 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:45:13 -0800 Subject: [PATCH 16/40] (fix) Keep shared meshes current after delayed sculpt responses --- src/core/live.ts | 21 +++++++++++-- tests/e2e/mcp.spec.ts | 69 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 2 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 66e7cae..58bc72c 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -113,6 +113,7 @@ export function joinLiveSession() { let viewMoved = false; let dirtyEdit: OrdinaryEdit | null = null; let activeEdit: QueuedEdit | null = null; + let activeSculptObserved = false; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; let awaitedHistory: { version: number; sculpt: number | null } | null = null; @@ -129,6 +130,8 @@ export function joinLiveSession() { } }; + const unsentEdits = () => (dirtyEdit ? [...edits, dirtyEdit] : edits); + useSharedSculptQueueGuard((geometry) => { if (!connected) return false; const queued = [activeEdit, ...edits].flatMap((edit) => @@ -215,7 +218,16 @@ export function joinLiveSession() { const local = committedScene(useEditor.getState()); const first = !confirmed; const replaced = !!confirmed && message.epoch !== confirmed.epoch; - const unsent = [...edits, dirtyEdit].filter((edit): edit is QueuedEdit => !!edit); + const unsent = unsentEdits(); + if (activeEdit && 'sculpt' in activeEdit) { + const { sculpt, geometry } = activeEdit; + if ( + scene.parts.some( + (part) => part.id === sculpt.partId && part.geometry.uuid === geometry.uuid, + ) + ) + activeSculptObserved = true; + } const replacing = unsent.some((edit) => !('sculpt' in edit) && edit.replace); let next = scene; // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. @@ -224,7 +236,7 @@ export function joinLiveSession() { edits.length = 0; if (replaced && useEditor.getState().sculpt) useEditor.getState().setTool('select'); } else { - const pending = activeEdit ? [activeEdit, ...unsent] : unsent; + const pending = activeEdit && !activeSculptObserved ? [activeEdit, ...unsent] : unsent; next = pending.reduce(applyQueuedEdit, scene); } confirmed = { version: message.version, epoch: message.epoch, scene }; @@ -310,6 +322,7 @@ export function joinLiveSession() { const checkpoint = 'sculpt' in edit || edit.checkpoint; const replace = !('sculpt' in edit) && edit.replace; activeEdit = edit; + activeSculptObserved = false; if (!sculpt) useEditor.getState().submitWarp(); try { if ('sculpt' in edit) { @@ -341,6 +354,10 @@ export function joinLiveSession() { if (response.ok) { awaited = ((await response.json()) as { version: number }).version; if (!sculpt) useEditor.getState().settleWarp(true, true); + else if (!closed && confirmed && confirmed.version >= awaited) { + // The stream can skip the accepted mesh or show it before the HTTP response arrives. + show(unsentEdits().reduce(applyQueuedEdit, confirmed.scene)); + } } else refused(await errorOf(response)); } catch (error) { if (error instanceof Refusal) refused(error.message); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 28421f8..6211752 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -579,3 +579,72 @@ test('an ordinary edit between queued strokes preserves a newer remote mesh', as expect((await call('get_scene')).name).toBe('Renamed while sculpting'); expect(request.postDataJSON().scene.parts[0].geometry).toBe(remoteGeometry); }); + +test('a remote mesh survives the delayed response for a single sculpt stroke', async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = page.locator('canvas'); + const box = (await canvas.boundingBox())!; + const triangles = page.locator('.scene-summary').getByText(/triangles$/); + const baseline = await triangles.innerText(); + const editUrl = /\/live\/edit$/; + let finish = () => {}; + const held = new Promise((resolve) => { + finish = resolve; + }); + let acceptedVersion = 0; + await page.route(editUrl, async (route) => { + const accepted = await route.fetch(); + if (accepted.ok() && route.request().postDataJSON().sculpt) { + const { version } = await accepted.json(); + acceptedVersion = version; + await held; + } + await route.fulfill({ response: accepted }); + }); + + const sent = page.waitForRequest( + (request) => editUrl.test(request.url()) && !!request.postDataJSON().sculpt, + ); + await page.mouse.click(box.x + box.width / 2 + 8, box.y + box.height / 2 - 7); + await page.mouse.move(box.x - 2, box.y + 2); + const request = await sent; + await expect.poll(() => acceptedVersion).toBeGreaterThan(0); + await expect(triangles).not.toHaveText(baseline); + + const original = request.postDataJSON(); + const remote = await page.request.post(request.url(), { + data: { + client: 'remote-editor', + base: acceptedVersion, + epoch: original.epoch, + checkpoint: true, + scene: { + ...original.scene, + parts: original.scene.parts.map((part: { id: string }) => ({ + ...part, + ...(part.id === original.sculpt.partId + ? { geometry: original.sculpt.source, name: 'Restored block' } + : {}), + })), + }, + }, + }); + expect(remote.ok()).toBe(true); + await expect(page.locator(part('Restored block'))).toBeVisible(); + const completed = page.waitForResponse((response) => response.request() === request); + finish(); + expect((await completed).ok()).toBe(true); + await expect(triangles).toHaveText(baseline); +}); From 95cb63bd9c244b9d1a37e1455f8f787ba93728c1 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 19:45:46 -0800 Subject: [PATCH 17/40] (fix) Skip retrying confirmed sculpt strokes --- src/core/live.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 58bc72c..1a6f2e9 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -362,8 +362,8 @@ export function joinLiveSession() { } catch (error) { if (error instanceof Refusal) refused(error.message); else { - // Kept for when the agent can be reached again. - edits.unshift(edit); + // Retry an interrupted request unless the stream already confirmed the stroke. + if (!activeSculptObserved) edits.unshift(edit); if (!sculpt) useEditor.getState().retryWarp(); lost(); } From 910d665aa1ccb286a284532cf42ecb022239167d Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 21:51:02 -0800 Subject: [PATCH 18/40] (fix) Preserve shared sculpt history and full brush coverage --- mcp/document.ts | 6 +++++- src/core/live.ts | 32 ++++++++++++++++++++++--------- src/core/sculpt-mesh.ts | 14 ++++++++------ tests/e2e/mcp.spec.ts | 6 ++++++ tests/unit/history-budget.test.ts | 3 ++- tests/unit/sculpt-mesh.test.ts | 21 ++++++++++++++++++++ 6 files changed, 65 insertions(+), 17 deletions(-) diff --git a/mcp/document.ts b/mcp/document.ts index a0639f2..12af4d0 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -252,7 +252,11 @@ export class SharedDocument { this.log.set(this.version, { author, summary: summarizePatch(patch), replaced }); this.versions.delete(this.version - keepVersions); this.log.delete(this.version - keepVersions); - for (const part of this.scene.parts) this.meshes.set(part.geometry.uuid, part.geometry); + for (const part of this.scene.parts) { + const { geometry } = part; + this.meshes.set(geometry.uuid, geometry); + this.uploads.delete(geometry.uuid); + } if (changesGeometry(patch)) this.trimMemory(); if (this.version % 50 === 0) this.prune(); for (const listener of this.listeners) listener(); diff --git a/src/core/live.ts b/src/core/live.ts index 1a6f2e9..68d5128 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -114,6 +114,7 @@ export function joinLiveSession() { let dirtyEdit: OrdinaryEdit | null = null; let activeEdit: QueuedEdit | null = null; let activeSculptObserved = false; + let acceptedSculpt: { edit: SculptEdit; version: number; epoch: number } | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; let awaitedHistory: { version: number; sculpt: number | null } | null = null; @@ -134,7 +135,7 @@ export function joinLiveSession() { useSharedSculptQueueGuard((geometry) => { if (!connected) return false; - const queued = [activeEdit, ...edits].flatMap((edit) => + const queued = [activeEdit, acceptedSculpt?.edit, ...edits].flatMap((edit) => edit && 'sculpt' in edit ? [edit.geometry] : [], ); return queued.length < 40 && geometryBytes([...queued, geometry]) <= sculptHistoryBytes; @@ -228,6 +229,11 @@ export function joinLiveSession() { ) activeSculptObserved = true; } + if ( + acceptedSculpt && + (message.epoch !== acceptedSculpt.epoch || message.version >= acceptedSculpt.version) + ) + acceptedSculpt = null; const replacing = unsent.some((edit) => !('sculpt' in edit) && edit.replace); let next = scene; // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. @@ -236,11 +242,16 @@ export function joinLiveSession() { edits.length = 0; if (replaced && useEditor.getState().sculpt) useEditor.getState().setTool('select'); } else { - const pending = activeEdit && !activeSculptObserved ? [activeEdit, ...unsent] : unsent; + const optimistic = acceptedSculpt?.edit ?? (activeSculptObserved ? null : activeEdit); + const pending = optimistic ? [optimistic, ...unsent] : unsent; next = pending.reduce(applyQueuedEdit, scene); } confirmed = { version: message.version, epoch: message.epoch, scene }; const [undo, redo] = message.history[client] ?? [0, 0]; + if (!connected) { + connected = true; + useSharedHistory(history); + } useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); const before = new Set(local.parts.map((part) => part.id)); show(next); @@ -291,7 +302,12 @@ export function joinLiveSession() { }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ - const refused = (reason?: string) => { + const refused = (reason?: string, sculpt = false) => { + // History requests queued behind a refused stroke refer to the discarded optimistic scene. + if (sculpt) { + requests.length = 0; + stopSharedSculptHistory(); + } edits.length = 0; dirtyEdit = null; if (confirmed) { @@ -357,10 +373,12 @@ export function joinLiveSession() { else if (!closed && confirmed && confirmed.version >= awaited) { // The stream can skip the accepted mesh or show it before the HTTP response arrives. show(unsentEdits().reduce(applyQueuedEdit, confirmed.scene)); + } else if ('sculpt' in edit && !activeSculptObserved && confirmed?.epoch === base.epoch) { + acceptedSculpt = { edit, version: awaited, epoch: base.epoch }; } - } else refused(await errorOf(response)); + } else refused(await errorOf(response), !!sculpt); } catch (error) { - if (error instanceof Refusal) refused(error.message); + if (error instanceof Refusal) refused(error.message, !!sculpt); else { // Retry an interrupted request unless the stream already confirmed the stroke. if (!activeSculptObserved) edits.unshift(edit); @@ -441,10 +459,6 @@ export function joinLiveSession() { source.addEventListener('scene', (event) => { latest = JSON.parse((event as MessageEvent).data); - if (!connected) { - connected = true; - useSharedHistory(history); - } void receive(); }); // Sent only to tabs on the computer that holds the scene: how another device joins it. diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts index 0a61d48..12b7551 100644 --- a/src/core/sculpt-mesh.ts +++ b/src/core/sculpt-mesh.ts @@ -86,7 +86,6 @@ function rememberIncidence(source: BufferGeometry, incidence: Incidence) { } const maxSplitsPerDab = 192; -const maxFacesPerPatch = 8192; /** Source meshes larger than this remain brushable at their available density. */ const maxRefinedFaceCount = 1_200_000; const inheritedFaceLimits = new WeakMap(); @@ -179,17 +178,20 @@ function weldSeams(position: Attribute, corners: ArrayLike) { const a = weldOf[u], b = weldOf[v]; if (a === b || !(duplicates[a] || duplicates[b])) continue; + // Looking up the smaller fan avoids walking a high-valence center for every spoke. + const smaller = faceStart[a + 1] - faceStart[a] <= faceStart[b + 1] - faceStart[b] ? a : b; + const opposite = smaller === a ? b : a; let match = -1; let previous = -1; - for (let i = faceStart[a]; i < faceStart[a + 1]; i++) { + for (let i = faceStart[smaller]; i < faceStart[smaller + 1]; i++) { const neighbor = incidentFaces[i]; if (neighbor === face || neighbor === previous) continue; previous = neighbor; const start = neighbor * 3; if ( - weldOf[corners[start]] !== b && - weldOf[corners[start + 1]] !== b && - weldOf[corners[start + 2]] !== b + weldOf[corners[start]] !== opposite && + weldOf[corners[start + 1]] !== opposite && + weldOf[corners[start + 2]] !== opposite ) continue; if (match !== -1) { @@ -592,7 +594,7 @@ export class SculptMesh { if (seed < 0 || seed >= this.faceCount || !Number.isInteger(seed)) return faces; const visited = new Set([seed]); const queue = [seed]; - for (let i = 0; i < queue.length && i < maxFacesPerPatch; i++) { + for (let i = 0; i < queue.length; i++) { const face = queue[i]; if (!this.overlaps(face, footprint)) continue; faces.add(face); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 6211752..0a865d4 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -486,6 +486,11 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos const third = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); await page.mouse.click(x + 24, y - 7); const thirdRequest = await third; + const extraUndo: string[] = []; + page.on('request', (request) => { + if (/\/live\/undo$/.test(request.url())) extraUndo.push(request.url()); + }); + await page.keyboard.press('ControlOrMeta+z'); await call('update_parts', { updates: [{ id: 'block', translate: [2, 0, 0] }] }); const refused = page.waitForResponse((response) => response.request() === thirdRequest); unpause(); @@ -494,6 +499,7 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos page.getByText(/sculpt target changed before the stroke reached the shared scene/i), ).toBeVisible(); expect((await call('get_scene')).parts[0].position).toEqual([2, 0, 0]); + expect(extraUndo).toEqual([]); }); test('an ordinary edit between queued strokes preserves a newer remote mesh', async ({ page }) => { diff --git a/tests/unit/history-budget.test.ts b/tests/unit/history-budget.test.ts index 4d71a44..e6acdb5 100644 --- a/tests/unit/history-budget.test.ts +++ b/tests/unit/history-budget.test.ts @@ -111,7 +111,7 @@ describe('history budget', () => { expect(useEditor.getState().past).toHaveLength(3); }); - it('trims the shared document history over budget and frees dropped meshes', () => { + it('trims the shared document history and frees adopted uploads when dropped', () => { const doc = new SharedDocument(1024 * 1024); doc.replace(sceneOf(mesh(100_000))); const uuids: string[] = []; @@ -119,6 +119,7 @@ describe('history budget', () => { const before = doc.scene; const geometry = mesh(100_000 + i); uuids.push(geometry.uuid); + doc.addMesh(geometry.uuid, geometry); useEditor.setState((state) => ({ scene: { ...before, parts: [part('p0', geometry)] }, revision: state.revision + 1, diff --git a/tests/unit/sculpt-mesh.test.ts b/tests/unit/sculpt-mesh.test.ts index 3190358..e358feb 100644 --- a/tests/unit/sculpt-mesh.test.ts +++ b/tests/unit/sculpt-mesh.test.ts @@ -4,6 +4,7 @@ import { Matrix4, Mesh, MeshBasicMaterial, + PlaneGeometry, Raycaster, Vector3, type Intersection, @@ -35,6 +36,26 @@ function mesh(positions: number[], corners?: number[]) { } describe('sculpt mesh', () => { + it('protects the full footprint of a large mask on a dense surface', () => { + const segments = 200; + const source = new PlaneGeometry(100, 100, segments, segments); + const draft = new SculptMesh(source, identity); + expect( + draft.dab( + dab(new Vector3(), { + face: 2 * ((segments / 2) * segments + segments / 2), + radius: 30, + brush: 'mask', + falloff: 'hard', + detail: 0, + }), + ), + ).toBe(true); + const positions = source.getAttribute('position'); + const weights = draft.getMask(); + for (let i = 0; i < positions.count; i++) + expect(weights[i]).toBe(Math.hypot(positions.getX(i), positions.getY(i)) < 30 ? 1 : 0); + }); it('adds detail under a small dab in a coarse face, keeping original positions and winding', () => { const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); const draft = new SculptMesh(source, identity); From 2ea0b85ff8cf3d41e252efa4a30c4897045d4435 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 21:54:55 -0800 Subject: [PATCH 19/40] (fix) Restore sculpt masks and ignore stale stream loads --- src/core/live.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 68d5128..3e03242 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -105,6 +105,7 @@ export function joinLiveSession() { /** The last scene the server sent. Unsent changes here are relative to it. */ let confirmed: { version: number; epoch: number; scene: SceneDocument } | null = null; let latest: Message | null = null; + let streamGeneration = 0; let receiving = false; let pumping = false; let applyingRemote = false; @@ -279,7 +280,8 @@ export function joinLiveSession() { while (latest && !closed) { const message = latest; latest = null; - if ((await load(message)) && !closed) apply(message); + const generation = streamGeneration; + if ((await load(message)) && !closed && generation === streamGeneration) apply(message); } } catch (error) { notify(`The shared scene stopped updating. ${(error as Error).message}`); @@ -302,16 +304,16 @@ export function joinLiveSession() { }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ - const refused = (reason?: string, sculpt = false) => { + const refused = (reason?: string, sculptStroke = false) => { + const { sculpt } = useEditor.getState(); // History requests queued behind a refused stroke refer to the discarded optimistic scene. - if (sculpt) { + if (sculptStroke) { requests.length = 0; stopSharedSculptHistory(); } edits.length = 0; dirtyEdit = null; if (confirmed) { - const { sculpt } = useEditor.getState(); show(confirmed.scene); restoreSculptAfterRefusal(confirmed.scene, sculpt); } @@ -466,7 +468,11 @@ export function joinLiveSession() { useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }), ); // EventSource keeps retrying, so a server that is only briefly unreachable reconnects by itself. - source.onerror = lost; + source.onerror = () => { + streamGeneration++; + latest = null; + lost(); + }; useEditor.setState({ liveStatus: 'connecting' }); return () => { From 63e1ca81d51bf79b4ec12d3e734045c3e619a446 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 21:57:11 -0800 Subject: [PATCH 20/40] (fix) Process reconnect snapshots after stale load failures --- src/core/live.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 3e03242..74998cf 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -281,10 +281,13 @@ export function joinLiveSession() { const message = latest; latest = null; const generation = streamGeneration; - if ((await load(message)) && !closed && generation === streamGeneration) apply(message); + try { + if ((await load(message)) && !closed && generation === streamGeneration) apply(message); + } catch (error) { + if (!closed && generation === streamGeneration) + notify(`The shared scene stopped updating. ${(error as Error).message}`); + } } - } catch (error) { - notify(`The shared scene stopped updating. ${(error as Error).message}`); } finally { receiving = false; } From e65c8557c55c483c60c8b7f3e7889c8e98a356b4 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:00:53 -0800 Subject: [PATCH 21/40] (fix) Preserve global undo history when sculpting --- src/core/store.ts | 26 +++++++---------------- tests/unit/history-budget.test.ts | 35 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/core/store.ts b/src/core/store.ts index cf43596..d20b0bf 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -1885,12 +1885,7 @@ function appliedWarpGeometry(source: BufferGeometry, output: WarpOutput) { return geometry; } -const changed = ( - state: EditorState, - scene: SceneDocument, - checkpoint = true, - budget = historyBudgetBytes, -) => { +const changed = (state: EditorState, scene: SceneDocument, checkpoint = true) => { const base = committedScene(state); let past = checkpoint ? [...state.past.slice(-(historyLimit - 1)), base] : state.past; let notice = {}; @@ -1899,7 +1894,7 @@ const changed = ( past, [], [scene, ...(state.clipboard ? [{ name: '', parts: state.clipboard.parts, joints: [] }] : [])], - budget, + historyBudgetBytes, ); if (kept.trimmed) { past = kept.past; @@ -3515,17 +3510,12 @@ export const useEditor = create((set, get) => ({ ? state.future.length ? { future: [] } : {} - : changed( - state, - { - ...state.scene, - parts: state.scene.parts.map((candidate) => - candidate.id === part.id ? { ...part, geometry } : candidate, - ), - }, - true, - sculptHistoryBytes, - )), + : changed(state, { + ...state.scene, + parts: state.scene.parts.map((candidate) => + candidate.id === part.id ? { ...part, geometry } : candidate, + ), + })), sculpt: { ...sculpt, revision: nextSculptRevision(), diff --git a/tests/unit/history-budget.test.ts b/tests/unit/history-budget.test.ts index e6acdb5..b20aa41 100644 --- a/tests/unit/history-budget.test.ts +++ b/tests/unit/history-budget.test.ts @@ -30,6 +30,10 @@ const sceneOf = (...geometries: BufferGeometry[]): SceneDocument => ({ }); const tiny = vi.hoisted(() => ({ on: false })); +vi.mock('../../src/core/sculpt-session', async (original) => ({ + ...(await original()), + sculptHistoryBytes: 1024, +})); vi.mock('../../src/core/history-budget', async (original) => { const actual = await original(); return { @@ -100,6 +104,37 @@ describe('history budget', () => { expect(useEditor.getState().historyTrimNotified).toBe(false); }); + it('preserves unrelated undo steps when they exceed the Sculpt mesh limit', () => { + const previous = mesh(300); + const sculptable = new BoxGeometry(); + const scene = sceneOf(previous, sculptable); + const store = useEditor.getState; + store().setScene(scene); + store().patchParts(['p0'], { geometry: mesh(3) }); + const beforeStroke = store().scene; + store().select('p1'); + expect(store().startSculpt()).toBe(true); + expect( + store().commitSculpt({ + partId: 'p1', + source: sculptable, + epoch: store().sceneEpoch, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + geometry: sculptable.clone(), + mask: null, + }), + ).toBe(true); + + expect(store().past).toEqual([scene, beforeStroke]); + expect(store().historyTrimNotified).toBe(false); + store().setTool('select'); + store().undo(); + store().undo(); + expect(store().scene.parts[0].geometry).toBe(previous); + }); + it('keeps undo steps when Cut retains the removed meshes in the new clipboard', () => { tiny.on = true; useEditor.getState().setScene(sceneOf(mesh(30), mesh(30))); From bcf58ac673e8d51b5020ae1077c279698a4b2a0b Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:01:44 -0800 Subject: [PATCH 22/40] (fix) Discard queued undo when a shared edit is refused --- src/core/live.ts | 14 +++++------- tests/e2e/mcp.spec.ts | 52 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 74998cf..74db979 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -307,13 +307,11 @@ export function joinLiveSession() { }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ - const refused = (reason?: string, sculptStroke = false) => { + const refused = (reason?: string) => { const { sculpt } = useEditor.getState(); - // History requests queued behind a refused stroke refer to the discarded optimistic scene. - if (sculptStroke) { - requests.length = 0; - stopSharedSculptHistory(); - } + // Queued history requests refer to the discarded optimistic scene. + requests.length = 0; + stopSharedSculptHistory(true); edits.length = 0; dirtyEdit = null; if (confirmed) { @@ -381,9 +379,9 @@ export function joinLiveSession() { } else if ('sculpt' in edit && !activeSculptObserved && confirmed?.epoch === base.epoch) { acceptedSculpt = { edit, version: awaited, epoch: base.epoch }; } - } else refused(await errorOf(response), !!sculpt); + } else refused(await errorOf(response)); } catch (error) { - if (error instanceof Refusal) refused(error.message, !!sculpt); + if (error instanceof Refusal) refused(error.message); else { // Retry an interrupted request unless the stream already confirmed the stroke. if (!activeSculptObserved) edits.unshift(edit); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 0a865d4..6e152b4 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -424,6 +424,49 @@ test('tabs and the agent edit one scene, each with its own view', async ({ brows await context.close(); }); +test('refusing an ordinary shared edit discards its queued undo', async ({ page }) => { + await call('add_parts', { parts: model }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await expect(page.getByText('Shared with agent')).toBeVisible(); + const undo = page.getByRole('button', { name: /^Undo \((⌘|Ctrl)\+Z\)$/ }); + const rename = async (name: string) => { + await page.getByTitle('Rename assembly').click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + await rename('Accepted assembly name'); + await expect(undo).toBeEnabled(); + + let reject = () => {}; + const held = new Promise((resolve) => { + reject = resolve; + }); + const edit = /\/live\/edit$/; + await page.route(edit, async (route) => { + await held; + await route.fulfill({ status: 409, json: { error: 'Edit refused for this test.' } }); + }); + const submitted = page.waitForRequest(edit); + await rename('Refused assembly name'); + await submitted; + const undoRequests: string[] = []; + page.on('request', (request) => { + if (/\/live\/undo$/.test(request.url())) undoRequests.push(request.url()); + }); + await undo.click(); + reject(); + await expect(page.getByText(/edit refused for this test/i)).toBeVisible(); + await expect(page.getByTitle('Rename assembly')).toHaveText('Accepted assembly name'); + + await page.unroute(edit); + const nextEdit = page.waitForResponse(edit); + await rename('New assembly name'); + expect((await nextEdit).ok()).toBe(true); + expect(undoRequests).toEqual([]); +}); + test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ page, }) => { @@ -479,6 +522,13 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos ); expect(secondResponse.request().postDataJSON().checkpoint).toBe(true); + // The stroke can change geometry through zero-valued weights, which it then discards. + const invertMask = page.getByRole('button', { name: 'Invert mask', exact: true }); + const clearMask = page.getByRole('button', { name: 'Clear mask', exact: true }); + await invertMask.click(); + await invertMask.click(); + await expect(clearMask).toBeEnabled(); + blocked = new Promise((resolve) => { unpause = resolve; }); @@ -486,6 +536,7 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos const third = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); await page.mouse.click(x + 24, y - 7); const thirdRequest = await third; + await expect(clearMask).toBeDisabled(); const extraUndo: string[] = []; page.on('request', (request) => { if (/\/live\/undo$/.test(request.url())) extraUndo.push(request.url()); @@ -498,6 +549,7 @@ test('shared sculpt strokes keep their checkpoints and refuse a stale target pos await expect( page.getByText(/sculpt target changed before the stroke reached the shared scene/i), ).toBeVisible(); + await expect(clearMask).toBeEnabled(); expect((await call('get_scene')).parts[0].position).toEqual([2, 0, 0]); expect(extraUndo).toEqual([]); }); From 252e10edd0320cf7d84251aa1b4aee081bfe2045 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:02:18 -0800 Subject: [PATCH 23/40] (fix) Keep fast sculpt strokes continuous --- src/components/SculptPointer.tsx | 135 ++++++++++--------------------- src/core/commands.ts | 18 ++++- src/core/sculpt-path.ts | 100 +++++++++++++++++++++++ src/core/store.ts | 27 ++++++- tests/e2e/sculpt.spec.ts | 55 ++++++++++++- tests/unit/sculpt-path.test.ts | 43 ++++++++++ 6 files changed, 277 insertions(+), 101 deletions(-) create mode 100644 src/core/sculpt-path.ts create mode 100644 tests/unit/sculpt-path.test.ts diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 6e4e4be..9a49629 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -19,43 +19,14 @@ import { acceleratedRaycast } from 'three-mesh-bvh'; import { clearSculptIncidence, SculptMesh, type SculptDab } from '../core/sculpt-mesh'; import { triangleCount } from '../core/geometry'; import { workerIndexTriangles } from '../core/spatial-index'; -import { useEditor } from '../core/store'; +import { useEditor, useSculptStrokeFinisher } from '../core/store'; import type { Part, SculptureSettings } from '../core/types'; import { partMeshes } from '../xr/part-meshes'; +import { SculptPath, type SculptSample as Sample } from '../core/sculpt-path'; import { boundsEntry } from './RefinePointer'; -type Sample = Pick< - PointerEvent, - | 'clientX' - | 'clientY' - | 'pressure' - | 'pointerType' - | 'tiltX' - | 'tiltY' - | 'twist' - | 'shiftKey' - | 'altKey' ->; type Hit = Pick; -const maxQueuedDabs = 8; - -const lerp = (a: number, b: number, t: number) => a + (b - a) * t; - -function interpolate(a: Sample, b: Sample, t: number): Sample { - return { - pointerType: b.pointerType, - shiftKey: b.shiftKey, - altKey: b.altKey, - clientX: lerp(a.clientX, b.clientX, t), - clientY: lerp(a.clientY, b.clientY, t), - pressure: lerp(a.pressure, b.pressure, t), - tiltX: lerp(a.tiltX, b.tiltX, t), - tiltY: lerp(a.tiltY, b.tiltY, t), - twist: (a.twist + (((b.twist - a.twist + 540) % 360) - 180) * t + 360) % 360, - }; -} - const visible = (mesh: Mesh) => { for (let object = mesh.parent; object; object = object.parent) if (!object.visible) return false; return mesh.visible; @@ -99,11 +70,10 @@ interface Stroke { controlsEnabled: boolean; brush: SculptDab['brush']; eraser: boolean; - last: Sample; latest: Sample; - pending: Sample[]; + path: SculptPath; + released: boolean; changed: boolean; - spacing: number; first: Hit; grabPoint: Vector3; grabMirror: Hit | null; @@ -493,63 +463,27 @@ export function SculptPointer() { : undefined, }) || active.changed; }; + const drain = (active: Stroke, until: number) => { + do { + const sample = active.path.next(); + if (sample) apply(active, sample); + } while (active.path.pending && performance.now() < until); + if (active.released && !active.path.pending) detach(true); + }; + const finishReleased = () => { + if (stroke?.released) drain(stroke, Infinity); + }; const schedule = () => { if (frame) return; frame = requestAnimationFrame(() => { frame = 0; - const active = stroke; - if (active) { - const until = performance.now() + 6; - do { - const sample = active.pending.shift(); - if (sample) apply(active, sample); - } while (active.pending.length && performance.now() < until); - if (active.pending.length) schedule(); - } + if (stroke) drain(stroke, performance.now() + 6); + if (stroke?.path.pending) schedule(); refresh(); }); }; - const queue = (active: Stroke, sample: Sample) => { - active.pending.push(sample); - if (active.pending.length > maxQueuedDabs * 2) { - // Keep both endpoints and evenly thin old dabs when input outruns rendering. - const pending = active.pending; - active.pending = Array.from( - { length: maxQueuedDabs }, - (_, i) => pending[Math.round((i * (pending.length - 1)) / (maxQueuedDabs - 1))], - ); - } - }; - const enqueue = (active: Stroke, incoming: Sample, final = false) => { - const sample = final - ? incoming - : interpolate(active.last, incoming, 1 - active.settings.stabilization * 0.85); - const distance = Math.hypot( - sample.clientX - active.last.clientX, - sample.clientY - active.last.clientY, - ); - const scale = active.settings.pressureRadius - ? Math.max(0.08, pressure(sample, active.settings)) - : 1; - const spacing = Math.max(0.5, active.spacing * scale); - const steps = Math.min(32, Math.floor(distance / spacing)); - if (steps) { - const interval = Math.max(spacing, distance / 32); - for (let i = 1; i <= steps; i++) - queue(active, interpolate(active.last, sample, (interval * i) / distance)); - active.last = active.pending.at(-1)!; - if (!final || distance - interval * steps <= 0.1) return; - queue(active, sample); - } else if ( - final - ? distance > 0.1 - : distance < 0.1 && Math.abs(sample.pressure - active.last.pressure) > 0.015 - ) { - queue(active, sample); - } else return; - active.last = sample; - }; const down = (event: PointerEvent) => { + finishReleased(); const state = useEditor.getState(); const sculpt = state.sculpt; if (stroke) { @@ -626,11 +560,20 @@ export function SculptPointer() { grabMirror: brush === 'grab' && settings.symmetry ? mirror(hit, own, settings.radius) : null, applied: null, - last: event, latest: event, - pending: [event], + path: new SculptPath( + event, + (a, b) => { + const scale = settings.pressureRadius + ? Math.max(0.08, Math.min(pressure(a, settings), pressure(b, settings))) + : 1; + const footprint = settings.brush === 'draw' ? settings.aspect : 1; + return Math.max(0.025, radiusPixels * footprint * settings.spacing * scale); + }, + settings.stabilization, + ), changed: false, - spacing: Math.max(0.75, radiusPixels * settings.spacing), + released: false, }; if (controls) controls.enabled = false; own.geometry = draft.geometry; @@ -641,19 +584,19 @@ export function SculptPointer() { if (stroke) { if (event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); + if (stroke.released) return; const events = event.getCoalescedEvents?.() ?? []; stroke.latest = events.at(-1) ?? event; - for (const sample of events.length ? events : [event]) enqueue(stroke, sample); + for (const sample of events.length ? events : [event]) stroke.path.push(sample); } else if (!canvas.contains(event.target as Node) || event.pointerType === 'touch') return; hover = event; schedule(); }; const release = (event: PointerEvent) => { - if (!stroke || event.pointerId !== stroke.id) return; + if (!stroke || stroke.released || event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); const { pressure, pointerType, tiltX, tiltY, twist } = stroke.latest; - enqueue( - stroke, + stroke.path.push( { clientX: event.clientX, clientY: event.clientY, @@ -670,11 +613,13 @@ export function SculptPointer() { suppressClick = true; window.clearTimeout(clickTimer); clickTimer = window.setTimeout(() => (suppressClick = false), 300); - for (const sample of stroke.pending) apply(stroke, sample); - detach(true); + const active = stroke; + active.released = true; + drain(active, performance.now() + 6); + if (stroke) schedule(); }; const cancel = (event: PointerEvent) => { - if (stroke?.id === event.pointerId) detach(false); + if (stroke?.id === event.pointerId && !stroke.released) detach(false); }; const escape = (event: KeyboardEvent) => { if (event.key !== 'Escape' || !stroke) return; @@ -684,7 +629,7 @@ export function SculptPointer() { }; const blur = () => { hover = null; - detach(false); + if (!stroke?.released) detach(false); refresh(); }; const leave = () => { @@ -714,6 +659,7 @@ export function SculptPointer() { schedule(); }); prepare(); + useSculptStrokeFinisher(finishReleased); canvas.addEventListener('pointerdown', down, true); canvas.addEventListener('lostpointercapture', cancel); canvas.addEventListener('pointerleave', leave); @@ -725,6 +671,7 @@ export function SculptPointer() { window.addEventListener('blur', blur); return () => { unsubscribe(); + useSculptStrokeFinisher(null); canvas.removeEventListener('pointerdown', down, true); canvas.removeEventListener('lostpointercapture', cancel); canvas.removeEventListener('pointerleave', leave); diff --git a/src/core/commands.ts b/src/core/commands.ts index 00cb135..8049dcd 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -4,7 +4,15 @@ import { nextIsolation } from './isolation'; import { matchKeyAction } from './keybindings'; import type { KeyActionId, KeyInput } from './keybindings'; import { primaryShortcutText, usePreferences } from './preferences'; -import { canRedo, canUndo, refineEdited, useEditor, warpEdited, type WarpGizmo } from './store'; +import { + canRedo, + canUndo, + finishReleasedSculpt, + refineEdited, + useEditor, + warpEdited, + type WarpGizmo, +} from './store'; import { activeTransformTool, stepTransform, @@ -14,6 +22,7 @@ import { import type { SurfacePoint } from './types'; export async function saveCurrentScene() { + finishReleasedSculpt(); if (useEditor.getState().driveFile) { if (!(await driveAutosave.flush())) useDrive.setState({ dialogOpen: true }); return; @@ -22,6 +31,7 @@ export async function saveCurrentScene() { } export async function downloadCurrentScene() { + finishReleasedSculpt(); const state = useEditor.getState(); if (state.busy) return; const { revision } = state; @@ -293,7 +303,10 @@ export function editorCommands(context: CommandContext = {}) { ), export: command( 'Export assembly…', - () => state.setModal('export'), + () => { + finishReleasedSculpt(); + state.setModal('export'); + }, !!state.scene.parts.length, 'export', ), @@ -319,6 +332,7 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { + finishReleasedSculpt(); const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/sculpt-path.ts b/src/core/sculpt-path.ts new file mode 100644 index 0000000..1aa4e7a --- /dev/null +++ b/src/core/sculpt-path.ts @@ -0,0 +1,100 @@ +/** A pointer sample and the pen properties that affect a sculpt dab. */ +export type SculptSample = Pick< + PointerEvent, + | 'clientX' + | 'clientY' + | 'pressure' + | 'pointerType' + | 'tiltX' + | 'tiltY' + | 'twist' + | 'shiftKey' + | 'altKey' +>; + +function interpolate(a: SculptSample, b: SculptSample, t: number): SculptSample { + const lerp = (start: number, end: number) => start + (end - start) * t; + return { + pointerType: b.pointerType, + shiftKey: b.shiftKey, + altKey: b.altKey, + clientX: lerp(a.clientX, b.clientX), + clientY: lerp(a.clientY, b.clientY), + pressure: lerp(a.pressure, b.pressure), + tiltX: lerp(a.tiltX, b.tiltX), + tiltY: lerp(a.tiltY, b.tiltY), + twist: (a.twist + (((b.twist - a.twist + 540) % 360) - 180) * t + 360) % 360, + }; +} + +const distance = (a: SculptSample, b: SculptSample) => + Math.hypot(b.clientX - a.clientX, b.clientY - a.clientY); + +/** Keep input segments intact and produce only as many dabs as the caller has time to apply. */ +export class SculptPath { + private queue: { sample: SculptSample; final: boolean }[] = []; + private head = 0; + private cursor: SculptSample; + private filtered: SculptSample; + private lastDab: SculptSample; + private first = true; + private travelled = 0; + + constructor( + start: SculptSample, + private readonly spacing: (a: SculptSample, b: SculptSample) => number, + private readonly stabilization: number, + ) { + this.cursor = this.filtered = this.lastDab = start; + } + + get pending() { + return this.first || this.head < this.queue.length; + } + + push(incoming: SculptSample, final = false) { + this.filtered = final + ? incoming + : interpolate(this.filtered, incoming, 1 - this.stabilization * 0.85); + this.queue.push({ sample: this.filtered, final }); + } + + private consume() { + if (++this.head === this.queue.length) { + this.queue.length = 0; + this.head = 0; + } else if (this.head >= 256) { + this.queue = this.queue.slice(this.head); + this.head = 0; + } + } + + next(): SculptSample | undefined { + if (this.first) { + this.first = false; + return this.cursor; + } + while (this.head < this.queue.length) { + const { sample, final } = this.queue[this.head]; + const length = distance(this.cursor, sample); + const remaining = Math.max(0.001, this.spacing(this.cursor, sample) - this.travelled); + if (length >= remaining) { + this.cursor = interpolate(this.cursor, sample, remaining / length); + this.travelled = 0; + this.lastDab = this.cursor; + return this.cursor; + } + this.travelled += length; + this.cursor = sample; + this.consume(); + if ( + (final && this.travelled > 0.001) || + (this.travelled < 0.1 && Math.abs(sample.pressure - this.lastDab.pressure) > 0.015) + ) { + this.travelled = 0; + this.lastDab = sample; + return sample; + } + } + } +} diff --git a/src/core/store.ts b/src/core/store.ts index d20b0bf..bba045c 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -2133,7 +2133,8 @@ export const useEditor = create((set, get) => ({ indexingMeshes: 0, focusRequest: { id: 0, all: true }, measurement: [], - select: (id, additive = false) => + select: (id, additive = false) => { + finishReleasedSculpt(); set((state) => ({ selected: id ? additive @@ -2142,7 +2143,8 @@ export const useEditor = create((set, get) => ({ : [...state.selected, id] : [id] : [], - })), + })); + }, selectAll: () => set((state) => ({ selected: state.scene.parts.map((part) => part.id) })), isolate: (ids) => set({ isolated: ids?.length ? ids : null }), toggleIsolation: () => { @@ -2246,6 +2248,7 @@ export const useEditor = create((set, get) => ({ })), closeContextMenu: () => set({ contextMenu: null }), setTool: (tool) => { + finishReleasedSculpt(); const state = get(); if (tool === 'warp' && state.tool === 'warp' && state.warp) set({ navigationMode: null, pivotPicking: false }); @@ -4956,8 +4959,14 @@ export const useEditor = create((set, get) => ({ const next = name.trim() || 'Untitled assembly'; return next === state.scene.name ? {} : changed(state, { ...state.scene, name: next }); }), - undo: () => moveHistory('undo'), - redo: () => moveHistory('redo'), + undo: () => { + finishReleasedSculpt(); + moveHistory('undo'); + }, + redo: () => { + finishReleasedSculpt(); + moveHistory('redo'); + }, setView: (patch) => { if (patch.orbitSelection !== undefined) saveOrbitPreference(patch.orbitSelection); if (patch.partColors !== undefined) savePartColorMode(patch.partColors); @@ -4991,6 +5000,16 @@ useEditor.subscribe((state, previous) => { recordNotification(state.toast.message, state.toast.kind); }); +let finishSculptStroke: (() => void) | null = null; + +export function useSculptStrokeFinisher(finish: typeof finishSculptStroke) { + finishSculptStroke = finish; +} + +export function finishReleasedSculpt() { + finishSculptStroke?.(); +} + let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; export function useSharedSculptQueueGuard(guard: typeof sharedSculptQueueGuard) { diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index ee9a295..9ae2940 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Page } from '@playwright/test'; -import { BoxGeometry } from 'three'; +import { BoxGeometry, PlaneGeometry } from 'three'; import { serializeGeometry } from '../../src/core/geometry'; import { fixture, inStore, openScene, screen } from './helpers/refine'; import { failOnBrowserErrors } from './helpers/warp-grid'; @@ -115,6 +115,59 @@ test('commits a released stroke before a tool change in the same frame', async ( expect((await mesh(page)).peak).toBeGreaterThan(before.peak); }); +test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { + await openSculpt(page, { + ...block, + parts: [ + { + ...block.parts[0], + geometry: serializeGeometry(new PlaneGeometry(8, 6, 160, 120).translate(0, 0, 2)), + }, + ], + }); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('0.12'); + await radius.press('Enter'); + const start = await screen(page, [-2, 0, 2]); + const end = await screen(page, [2, 0, 2]); + await page.evaluate( + ({ start, end }) => { + const canvas = document.querySelector('canvas')!; + const pen = { + pointerId: 17, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent( + new PointerEvent('pointerdown', { ...pen, clientX: start.x, clientY: start.y, buttons: 1 }), + ); + canvas.dispatchEvent( + new PointerEvent('pointermove', { ...pen, clientX: end.x, clientY: end.y, buttons: 1 }), + ); + canvas.dispatchEvent( + new PointerEvent('pointerup', { ...pen, clientX: end.x, clientY: end.y }), + ); + }, + { start, end }, + ); + await expect + .poll(() => + inStore(page, (state) => { + const positions = state.scene.parts[0].geometry.getAttribute('position'); + const covered = new Set(); + for (let i = 0; i < positions.count; i++) { + const x = positions.getX(i); + if (x >= -2 && x < 2 && positions.getZ(i) > 2 + 1e-5) + covered.add(Math.floor((x + 2) * 10)); + } + return [covered.size, state.sculpt?.past.length]; + }), + ) + .toEqual([40, 1]); +}); + test('draws into a coarse face with pen pressure and undoes topology with displacement', async ({ page, }) => { diff --git a/tests/unit/sculpt-path.test.ts b/tests/unit/sculpt-path.test.ts new file mode 100644 index 0000000..78c8341 --- /dev/null +++ b/tests/unit/sculpt-path.test.ts @@ -0,0 +1,43 @@ +import { expect, it } from 'vitest'; +import { SculptPath, type SculptSample } from '../../src/core/sculpt-path'; + +const pen = (clientX: number, clientY = 0, pressure = 1): SculptSample => ({ + clientX, + clientY, + pressure, + pointerType: 'pen', + tiltX: 0, + tiltY: 0, + twist: 0, + shiftKey: false, + altKey: false, +}); + +it('lazily covers a fast sweep at the configured spacing and keeps its endpoint', () => { + const path = new SculptPath(pen(0, 0, 0.1), () => 2, 0); + path.push(pen(475, 0, 1), true); + expect(path.next()).toEqual(pen(0, 0, 0.1)); + let previous = 0; + let count = 0; + for (let sample = path.next(); sample; sample = path.next()) { + expect(sample.clientX - previous).toBeLessThanOrEqual(2.00001); + previous = sample.clientX; + count++; + } + expect(count).toBe(238); + expect(previous).toBe(475); + expect(path.pending).toBe(false); +}); + +it('carries spacing around the actual input path and accepts another move after draining', () => { + const path = new SculptPath(pen(0), () => 4, 0); + path.push(pen(3)); + path.push(pen(3, 3)); + expect(path.next()).toEqual(pen(0)); + expect(path.next()).toEqual(pen(3, 1)); + expect(path.next()).toBeUndefined(); + path.push(pen(6, 3), true); + expect(path.next()).toEqual(pen(5, 3)); + expect(path.next()).toEqual(pen(6, 3)); + expect(path.next()).toBeUndefined(); +}); From a751f61107bc69bdac56f8e48c58ba3bc205858d Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:02:19 -0800 Subject: [PATCH 24/40] (fix) Cancel pending Sculpt work on shared scene replacement --- src/core/live.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/live.ts b/src/core/live.ts index 74db979..a3fb563 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -241,7 +241,9 @@ export function joinLiveSession() { if (!replacing && (first || replaced)) { dirtyEdit = null; edits.length = 0; - if (replaced && useEditor.getState().sculpt) useEditor.getState().setTool('select'); + // A released stroke still draining belongs to the previous scene. + if (replaced && useEditor.getState().sculpt) + useEditor.setState({ tool: 'select', sculpt: null }); } else { const optimistic = acceptedSculpt?.edit ?? (activeSculptObserved ? null : activeEdit); const pending = optimistic ? [optimistic, ...unsent] : unsent; From 6d583ffa163ee70b0c48510ad34b7eaa89878430 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:03:07 -0800 Subject: [PATCH 25/40] (fix) Isolate sculpt fans and speed up dense brush dabs --- src/core/sculpt-mesh.ts | 444 ++++++++++++++++++++++++--------- tests/unit/sculpt-mesh.test.ts | 47 ++++ 2 files changed, 380 insertions(+), 111 deletions(-) diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts index 12b7551..ad088d0 100644 --- a/src/core/sculpt-mesh.ts +++ b/src/core/sculpt-mesh.ts @@ -60,6 +60,7 @@ interface Incidence { representative: Uint32Array; faceStart: Uint32Array; incidentFaces: Uint32Array; + adjacent: Int32Array; edits: ReadonlyMap>; } @@ -101,7 +102,8 @@ function weldVertices(position: Attribute) { const bits = new Uint32Array(coordinate.buffer); function hash(value: number) { coordinate[0] = value || 0; - return Math.imul(bits[0], 0x45d9f3b) ^ bits[1]; + const mixed = Math.imul(bits[0] ^ bits[1], 0x85ebca6b); + return mixed ^ (mixed >>> 16); } let count = 0; for (let vertex = 0; vertex < position.count; vertex++) { @@ -140,22 +142,23 @@ function buildFaceIncidence(weldOf: Uint32Array, weldCount: number, corners: Arr return { faceStart, incidentFaces }; } -/** Two render vertices at the same point are a seam only when their faces share a valid edge. */ -function weldSeams(position: Attribute, corners: ArrayLike) { - const { weldOf, representative } = weldVertices(position); - if (representative.length === position.count) return { weldOf, representative }; - const duplicates = new Uint8Array(representative.length); - for (let vertex = 0; vertex < weldOf.length; vertex++) - if (representative[weldOf[vertex]] !== vertex) duplicates[weldOf[vertex]] = 1; - const { faceStart, incidentFaces } = buildFaceIncidence(weldOf, representative.length, corners); - const parent = Uint32Array.from(weldOf, (_weld, vertex) => vertex); - function root(vertex: number) { - while (parent[vertex] !== vertex) { - parent[vertex] = parent[parent[vertex]]; - vertex = parent[vertex]; +/** Link corners through edges, then give each disconnected fan its own render vertex. */ +function weldSeams(position: Attribute, corners: Uint32Array) { + const { weldOf: coordinateOf, representative } = weldVertices(position); + const { faceStart, incidentFaces } = buildFaceIncidence( + coordinateOf, + representative.length, + corners, + ); + const parent = Uint32Array.from(corners, (_vertex, corner) => corner); + function root(corner: number) { + while (parent[corner] !== corner) { + parent[corner] = parent[parent[corner]]; + corner = parent[corner]; } - return vertex; + return corner; } + const adjacent = new Int32Array(corners.length).fill(-1); const valid = new Uint8Array(corners.length / 3); const point = new Vector3(), left = new Vector3(), @@ -173,56 +176,106 @@ function weldSeams(position: Attribute, corners: ArrayLike) { for (let corner = 0; corner < corners.length; corner++) { const face = Math.floor(corner / 3); + const end = face * 3 + ((corner + 1) % 3); const u = corners[corner]; - const v = corners[face * 3 + ((corner + 1) % 3)]; - const a = weldOf[u], - b = weldOf[v]; - if (a === b || !(duplicates[a] || duplicates[b])) continue; + const v = corners[end]; + if (u === v) { + parent[root(end)] = root(corner); + continue; + } + const a = coordinateOf[u], + b = coordinateOf[v]; // Looking up the smaller fan avoids walking a high-valence center for every spoke. const smaller = faceStart[a + 1] - faceStart[a] <= faceStart[b + 1] - faceStart[b] ? a : b; - const opposite = smaller === a ? b : a; - let match = -1; + let reverse = -1; + let matchCount = 0; let previous = -1; for (let i = faceStart[smaller]; i < faceStart[smaller + 1]; i++) { const neighbor = incidentFaces[i]; if (neighbor === face || neighbor === previous) continue; previous = neighbor; const start = neighbor * 3; - if ( - weldOf[corners[start]] !== opposite && - weldOf[corners[start + 1]] !== opposite && - weldOf[corners[start + 2]] !== opposite - ) - continue; - if (match !== -1) { - match = -1; // Non-manifold edge. - break; + let shared = false; + for (let edge = 0; edge < 3; edge++) { + const p = start + edge; + const q = start + ((edge + 1) % 3); + if (coordinateOf[corners[p]] === b && coordinateOf[corners[q]] === a) { + shared = true; + reverse = p; + if (neighbor > face && corners[q] === u && corners[p] === v) { + parent[root(q)] = root(corner); + parent[root(p)] = root(end); + } + } else if (coordinateOf[corners[p]] === a && coordinateOf[corners[q]] === b) { + shared = true; + if (neighbor > face && corners[p] === u && corners[q] === v) { + parent[root(p)] = root(corner); + parent[root(q)] = root(end); + } + } } - match = neighbor; + if (shared) matchCount++; } - if (match <= face || !validTriangle(face) || !validTriangle(match)) continue; - for (let edge = 0; edge < 3; edge++) { - const reverseU = corners[match * 3 + ((edge + 1) % 3)]; - const reverseV = corners[match * 3 + edge]; - if (weldOf[reverseU] !== a || weldOf[reverseV] !== b) continue; - parent[root(reverseU)] = root(u); - parent[root(reverseV)] = root(v); - break; + const match = Math.floor(reverse / 3); + if (matchCount === 1 && a !== b && reverse !== -1) adjacent[corner] = reverse; + else if (matchCount > 1) adjacent[corner] = -2; + if ( + a !== b && + matchCount === 1 && + match > face && + (corners[reverse] !== v || corners[match * 3 + ((reverse + 1) % 3)] !== u) && + validTriangle(face) && + validTriangle(match) + ) { + parent[root(match * 3 + ((reverse + 1) % 3))] = root(corner); + parent[root(reverse)] = root(end); } } - const remap = new Int32Array(position.count).fill(-1); - const seamRepresentative = new Uint32Array(position.count); - let count = 0; - for (let vertex = 0; vertex < weldOf.length; vertex++) { - const united = root(vertex); - if (remap[united] === -1) { - remap[united] = count; - seamRepresentative[count++] = vertex; + const weldOf = new Uint32Array(position.count); + const weldByRoot = new Uint32Array(corners.length); + const used = new Uint8Array(position.count); + const fanRepresentative: number[] = []; + const copies: number[] = []; + const copyByFan = new Map>(); + for (let corner = 0; corner < corners.length; corner++) { + const original = corners[corner]; + const fan = root(corner); + if (!weldByRoot[fan]) { + weldByRoot[fan] = fanRepresentative.length + 1; + fanRepresentative.push(original); + } + const weld = weldByRoot[fan] - 1; + if (!used[original]) { + used[original] = 1; + weldOf[original] = weld; + } else if (weldOf[original] !== weld) { + let byVertex = copyByFan.get(weld); + if (!byVertex) copyByFan.set(weld, (byVertex = new Map())); + let duplicate = byVertex.get(original); + if (duplicate === undefined) { + duplicate = position.count + copies.length; + copies.push(original); + byVertex.set(original, duplicate); + if (fanRepresentative[weld] === original) fanRepresentative[weld] = duplicate; + } + corners[corner] = duplicate; } - weldOf[vertex] = remap[united]; } - return { weldOf, representative: seamRepresentative.slice(0, count) }; + for (let vertex = 0; vertex < weldOf.length; vertex++) { + if (used[vertex]) continue; + weldOf[vertex] = fanRepresentative.length; + fanRepresentative.push(vertex); + } + const vertices = copies.length ? resize(weldOf, position.count + copies.length) : weldOf; + for (const [weld, byVertex] of copyByFan) + for (const duplicate of byVertex.values()) vertices[duplicate] = weld; + return { + weldOf: vertices, + representative: Uint32Array.from(fanRepresentative), + adjacent, + copies, + }; } function resize(array: T, length: number): T { @@ -273,10 +326,14 @@ class Footprint { overlaps(a: Vector3, b: Vector3, c: Vector3) { const triangle = this.triangle; - this.project(a, triangle.a); - this.project(b, triangle.b); - this.project(c, triangle.c); - return triangle.closestPointToPoint(origin, this.offset).lengthSq() < this.radius ** 2; + const squared = this.radius ** 2; + if ( + this.project(a, triangle.a).lengthSq() < squared || + this.project(b, triangle.b).lengthSq() < squared || + this.project(c, triangle.c).lengthSq() < squared + ) + return true; + return triangle.closestPointToPoint(origin, this.offset).lengthSq() < squared; } distance(point: Vector3) { @@ -304,11 +361,14 @@ export class SculptMesh { private representative = new Uint32Array(0); private faceStart = new Uint32Array(0); private incidentFaces = new Uint32Array(0); + private adjacent = new Int32Array(0); private baseEdits: ReadonlyMap> = new Map(); private incidentEdits = new Map>(); private readonly editedFaces = new Set(); private grabSamples: Map | undefined; private changed = false; + private readonly facePoints = [new Vector3(), new Vector3(), new Vector3()]; + private readonly faceEdges = [new Vector3(), new Vector3()]; constructor(source: BufferGeometry, matrixWorld: Matrix4, mask?: Float32Array) { this.source = source; @@ -344,7 +404,10 @@ export class SculptMesh { } getMask() { - return (this.geometry.getAttribute(maskName).array as Float32Array).slice(0, this.vertexCount); + return (this.geometry.getAttribute(maskName).array as Float32Array).slice( + 0, + this.changed ? this.vertexCount : this.initialVertices, + ); } /** Build or reuse incidence before pen-down when the controller has an idle opportunity. */ @@ -356,21 +419,25 @@ export class SculptMesh { cached.position === this.source.getAttribute('position') && cached.index === this.source.index ) { - const { weldOf, representative, faceStart, incidentFaces, edits } = cached.incidence; + const { weldOf, representative, faceStart, incidentFaces, adjacent, edits } = + cached.incidence; this.weldOf = weldOf; this.representative = representative; this.weldCount = representative.length; this.faceStart = faceStart; this.incidentFaces = incidentFaces; + this.adjacent = adjacent; this.baseEdits = edits; return; } this.buildIncidence(); + if (this.vertexCount !== this.initialVertices) return; rememberIncidence(this.source, { weldOf: this.weldOf, representative: this.representative, faceStart: this.faceStart, incidentFaces: this.incidentFaces, + adjacent: this.adjacent, edits: this.baseEdits, }); } @@ -481,12 +548,36 @@ export class SculptMesh { } private buildIncidence() { - const faces = this.geometry.index!.array.subarray(0, this.faceCount * 3); - const { weldOf, representative } = weldSeams(this.attribute('position'), faces); - this.weldOf = weldOf; - this.representative = representative; + const faces = (this.geometry.index!.array as Uint32Array).subarray(0, this.faceCount * 3); + const { weldOf, representative, adjacent, copies } = weldSeams( + this.attribute('position'), + faces, + ); + if (copies.length) { + this.ensureCapacity(this.vertexCount + copies.length, this.faceCount); + for (const attribute of Object.values(this.geometry.attributes) as BufferAttribute[]) { + const { array, itemSize } = attribute; + for (let copy = 0; copy < copies.length; copy++) { + const source = copies[copy] * itemSize; + array.copyWithin((this.vertexCount + copy) * itemSize, source, source + itemSize); + } + attribute.needsUpdate = true; + } + this.vertexCount += copies.length; + this.syncCounts(); + this.geometry.index!.needsUpdate = true; + } + const capacity = this.attribute('position').array.length / 3; + this.weldOf = capacity === weldOf.length ? weldOf : resize(weldOf, capacity); + this.representative = + capacity === weldOf.length ? representative : resize(representative, capacity); + this.adjacent = adjacent; this.weldCount = representative.length; - const { faceStart, incidentFaces } = buildFaceIncidence(weldOf, this.weldCount, faces); + const { faceStart, incidentFaces } = buildFaceIncidence( + weldOf, + this.weldCount, + this.geometry.index!.array.subarray(0, this.faceCount * 3), + ); this.faceStart = faceStart; this.incidentFaces = incidentFaces; } @@ -513,8 +604,9 @@ export class SculptMesh { } private maskAt(weld: number) { - let protection = 0; const attribute = this.attribute(maskName); + if (this.vertexCount === this.weldCount) return attribute.getX(this.representative[weld]); + let protection = 0; for (const face of this.incidence(weld)) { for (const vertex of this.face(face)) if (this.weldOf[vertex] === weld) protection = Math.max(protection, attribute.getX(vertex)); @@ -579,11 +671,12 @@ export class SculptMesh { } private overlaps(id: number, footprint: Footprint) { - const vertices = this.face(id); - const a = this.worldAt(vertices[0]); - const b = this.worldAt(vertices[1]); - const c = this.worldAt(vertices[2]); - const normal = new Vector3().subVectors(b, a).cross(new Vector3().subVectors(c, a)); + const index = this.geometry.index!.array; + const start = id * 3; + const a = this.worldAt(index[start], this.facePoints[0]); + const b = this.worldAt(index[start + 1], this.facePoints[1]); + const c = this.worldAt(index[start + 2], this.facePoints[2]); + const normal = this.faceEdges[0].subVectors(b, a).cross(this.faceEdges[1].subVectors(c, a)); const facing = normal.dot(footprint.normal) * this.orientation; return Number.isFinite(facing) && facing > 0 && footprint.overlaps(a, b, c); } @@ -592,22 +685,37 @@ export class SculptMesh { const faces = new Set(); const seed = footprint.hit.face; if (seed < 0 || seed >= this.faceCount || !Number.isInteger(seed)) return faces; - const visited = new Set([seed]); + const visited = new Uint8Array(this.faceCount); + visited[seed] = 1; const queue = [seed]; + const index = this.geometry.index!.array; + const weldOf = this.weldOf; + const enqueue = (neighbor: number) => { + if (visited[neighbor]) return; + visited[neighbor] = 1; + queue.push(neighbor); + }; for (let i = 0; i < queue.length; i++) { const face = queue[i]; if (!this.overlaps(face, footprint)) continue; faces.add(face); - const vertices = this.face(face); + const start = face * 3; for (let edge = 0; edge < 3; edge++) { - const a = this.weldOf[vertices[edge]]; - const b = this.weldOf[vertices[(edge + 1) % 3]]; - const incidents = this.splittableFaces(a, b); - if (incidents.length !== 2) continue; - for (const neighbor of incidents) { - if (visited.has(neighbor)) continue; - visited.add(neighbor); - queue.push(neighbor); + const a = weldOf[index[start + edge]]; + const b = weldOf[index[start + ((edge + 1) % 3)]]; + const reverse = this.adjacent[start + edge]; + if ( + reverse === undefined || + reverse === -2 || + this.incidentEdits.has(a) || + this.baseEdits.has(a) + ) { + const incidents = this.splittableFaces(a, b); + if (incidents.length === 2) enqueue(incidents[0] === face ? incidents[1] : incidents[0]); + } else if (reverse >= 0) { + const neighbor = Math.floor(reverse / 3); + const end = neighbor * 3 + ((reverse + 1) % 3); + if (weldOf[index[reverse]] === b && weldOf[index[end]] === a) enqueue(neighbor); } } } @@ -740,20 +848,34 @@ export class SculptMesh { settings.radius * MathUtils.lerp(0.95, 0.22, settings.detail), ); const minEdgeSquared = (settings.minEdge ?? 0) ** 2; - const queue = [...new Set(brushes.flatMap(({ faces }) => [...faces]))]; + const queue = + brushes.length === 1 + ? [...brushes[0].faces] + : [...new Set(brushes.flatMap(({ faces }) => [...faces]))]; + const edited = new Set(); + const points = [new Vector3(), new Vector3(), new Vector3()]; + const targetSquared = target ** 2; for (let i = 0; i < queue.length; i++) { const id = queue[i]; - const active = brushes.filter( - ({ faces, footprint }) => faces.has(id) && this.overlaps(id, footprint), - ); - if (!active.length) continue; + if ( + edited.has(id) && + !brushes.some(({ faces, footprint }) => faces.has(id) && this.overlaps(id, footprint)) + ) + continue; const vertices = this.face(id); - const points = vertices.map((vertex) => this.worldAt(vertex)); - const protectedFace = + for (let corner = 0; corner < 3; corner++) this.worldAt(vertices[corner], points[corner]); + if ( + points[0].distanceToSquared(points[1]) <= targetSquared && + points[1].distanceToSquared(points[2]) <= targetSquared && + points[2].distanceToSquared(points[0]) <= targetSquared + ) + continue; + if ( settings.brush !== 'mask' && - vertices.every((vertex) => this.maskAt(this.weldOf[vertex]) === 1); - if (protectedFace) continue; - let longest = target ** 2; + vertices.every((vertex) => this.maskAt(this.weldOf[vertex]) === 1) + ) + continue; + let longest = targetSquared; let choice: { a: number; b: number; faces: number[] } | undefined; for (let edge = 0; edge < 3; edge++) { const next = (edge + 1) % 3; @@ -790,11 +912,13 @@ export class SculptMesh { splits.push(split); for (const { id: parent, child } of split.faces) { for (const { faces } of brushes) if (faces.has(parent)) faces.add(child); + edited.add(parent); + edited.add(child); queue.push(parent, child); } } for (const { faces, footprint } of brushes) - for (const id of faces) if (!this.overlaps(id, footprint)) faces.delete(id); + for (const id of edited) if (faces.has(id) && !this.overlaps(id, footprint)) faces.delete(id); return splits; } @@ -897,30 +1021,119 @@ export class SculptMesh { } private renderVertices(weld: number) { + if (this.vertexCount === this.weldCount) return [this.representative[weld]]; const vertices = new Set(); for (const id of this.incidence(weld)) for (const vertex of this.face(id)) if (this.weldOf[vertex] === weld) vertices.add(vertex); return vertices; } - private localFaceCross(id: number) { - const [ia, ib, ic] = this.face(id); + private localFaceCross(id: number, cross = new Vector3()) { + const index = this.geometry.index!.array; + const start = id * 3; const position = this.attribute('position'); - const a = new Vector3().fromBufferAttribute(position, ia); - const cross = new Vector3() - .fromBufferAttribute(position, ib) + const a = this.facePoints[0].fromBufferAttribute(position, index[start]); + cross + .fromBufferAttribute(position, index[start + 1]) .sub(a) - .cross(new Vector3().fromBufferAttribute(position, ic).sub(a)); + .cross(this.facePoints[1].fromBufferAttribute(position, index[start + 2]).sub(a)); return Number.isFinite(cross.lengthSq()) ? cross : cross.set(0, 0, 0); } - private deform(moves: Map) { + private applyMoves(moves: Map) { const position = this.attribute('position'); + const bounds = this.geometry.boundingBox; + const sphere = this.geometry.boundingSphere; + let first = this.vertexCount; + let last = -1; + const batch = moves.size > 4096; + for (const [weld, local] of moves) { + for (const vertex of this.renderVertices(weld)) { + position.setXYZ(vertex, local.x, local.y, local.z); + if (batch) { + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } else position.addUpdateRange(vertex * 3, 3); + } + bounds?.expandByPoint(local); + if (sphere) sphere.radius = Math.max(sphere.radius, local.distanceTo(sphere.center)); + } + if (batch) position.addUpdateRange(first * 3, (last - first + 1) * 3); + position.needsUpdate = true; + } + + /** Accumulate area-weighted render normals in flat buffers for widely affected surfaces. */ + private deformDense( + moves: Map, + changedFaces: Set, + output: BufferAttribute, + ) { + const index = this.geometry.index!.array; + const affected = new Uint8Array(this.vertexCount); + let first = this.vertexCount; + let last = -1; + for (const face of changedFaces) { + for (let corner = face * 3; corner < face * 3 + 3; corner++) { + const vertex = index[corner]; + affected[vertex] = 1; + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } + } + const size = (last - first + 1) * 3; + const faceCross = new Vector3(); + const accumulate = () => { + const sums = new Float64Array(size); + for (let face = 0; face < this.faceCount; face++) { + const corner = face * 3; + const a = index[corner]; + const b = index[corner + 1]; + const c = index[corner + 2]; + if (!(affected[a] || affected[b] || affected[c])) continue; + this.localFaceCross(face, faceCross); + // Repeated corners form a zero-area face and contribute nothing. + for (let offset = 0; offset < 3; offset++) { + const vertex = index[corner + offset]; + if (!affected[vertex]) continue; + const component = (vertex - first) * 3; + sums[component] += faceCross.x; + sums[component + 1] += faceCross.y; + sums[component + 2] += faceCross.z; + } + } + return sums; + }; + const before = accumulate(); + this.applyMoves(moves); + const after = accumulate(); + const previous = new Vector3(); + const current = new Vector3(); + const normal = new Vector3(); + const rotate = new Quaternion(); + for (let vertex = first; vertex <= last; vertex++) { + if (!affected[vertex]) continue; + const component = (vertex - first) * 3; + previous.fromArray(before, component); + current.fromArray(after, component); + if (!previous.lengthSq() || !current.lengthSq()) continue; + rotate.setFromUnitVectors(previous.normalize(), current.normalize()); + normal.fromBufferAttribute(output, vertex).applyQuaternion(rotate).normalize(); + output.setXYZ(vertex, normal.x, normal.y, normal.z); + } + output.addUpdateRange(first * 3, size); + output.needsUpdate = true; + } + + private deform(moves: Map) { const outputNormals = this.geometry.getAttribute('normal') as BufferAttribute | undefined; const changedFaces = new Set(); for (const weld of moves.keys()) for (const face of this.incidence(weld)) changedFaces.add(face); for (const face of changedFaces) this.editedFaces.add(face); + if (outputNormals && changedFaces.size > Math.max(4096, this.faceCount / 8)) { + this.deformDense(moves, changedFaces, outputNormals); + return; + } const normals = new Map(); const renderFaces = new Map>(); const faceBefore = new Map(); @@ -941,17 +1154,7 @@ export class SculptMesh { } } } - const bounds = this.geometry.boundingBox; - const sphere = this.geometry.boundingSphere; - for (const [weld, local] of moves) { - for (const vertex of this.renderVertices(weld)) { - position.setXYZ(vertex, local.x, local.y, local.z); - position.addUpdateRange(vertex * 3, 3); - } - bounds?.expandByPoint(local); - if (sphere) sphere.radius = Math.max(sphere.radius, local.distanceTo(sphere.center)); - } - position.needsUpdate = true; + this.applyMoves(moves); if (outputNormals) { const after = new Map(); const rotate = new Quaternion(); @@ -990,11 +1193,18 @@ export class SculptMesh { }); splits = this.refine(settings, brushes); samples = new Map(); + const visited = new Uint8Array(this.weldCount); + const index = this.geometry.index!.array; + const point = new Vector3(); for (const { footprint, faces, mirrored } of brushes) { + const pass = mirrored ? 2 : 1; for (const face of faces) { - for (const vertex of this.face(face)) { + for (let i = face * 3; i < face * 3 + 3; i++) { + const vertex = index[i]; const weld = this.weldOf[vertex]; - const weight = this.weight(footprint, this.worldAt(vertex), settings); + if (visited[weld] === pass) continue; + visited[weld] = pass; + const weight = this.weight(footprint, this.worldAt(vertex, point), settings); if (weight > (samples.get(weld)?.weight ?? 0)) samples.set(weld, { footprint, weight, mirrored }); } @@ -1056,15 +1266,22 @@ export class SculptMesh { if (moves.size) this.deform(moves); if (masks.size) { const mask = this.attribute(maskName); + const batch = masks.size > 4096; + let first = this.vertexCount; + let last = -1; for (const [weld, value] of masks) { for (const vertex of this.renderVertices(weld)) { mask.setX(vertex, value); - mask.addUpdateRange(vertex, 1); + if (batch) { + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } else mask.addUpdateRange(vertex, 1); } } + if (batch) mask.addUpdateRange(first, last - first + 1); mask.needsUpdate = true; } - this.changed ||= moves.size > 0 || splits.length > 0; + this.changed ||= moves.size > 0 || this.vertexCount !== this.initialVertices; return true; } @@ -1079,9 +1296,13 @@ export class SculptMesh { const dirtyBounds = new Box3(); const sourcePosition = this.source.getAttribute('position'); const point = new Vector3(); - for (const face of this.editedFaces) - for (const vertex of this.face(face)) + for (const face of this.editedFaces) { + for (let offset = 0; offset < 3; offset++) { + const corner = face * 3 + offset; + const vertex = this.source.index?.getX(corner) ?? corner; dirtyBounds.expandByPoint(point.fromBufferAttribute(sourcePosition, vertex)); + } + } const nodes = new Set(); sourceTree.shapecast({ intersectsBounds: (bounds, _leaf, _score, _depth, node) => { @@ -1136,6 +1357,7 @@ export class SculptMesh { : this.representative.slice(0, this.weldCount), faceStart: this.faceStart, incidentFaces: this.incidentFaces, + adjacent: this.adjacent, edits: new Map([ ...this.baseEdits, ...Array.from(this.incidentEdits, ([vertex, faces]) => [vertex, new Set(faces)] as const), diff --git a/tests/unit/sculpt-mesh.test.ts b/tests/unit/sculpt-mesh.test.ts index e358feb..c20659c 100644 --- a/tests/unit/sculpt-mesh.test.ts +++ b/tests/unit/sculpt-mesh.test.ts @@ -56,6 +56,27 @@ describe('sculpt mesh', () => { for (let i = 0; i < positions.count; i++) expect(weights[i]).toBe(Math.hypot(positions.getX(i), positions.getY(i)) < 30 ? 1 : 0); }); + it('updates area-weighted normals across a dense draw footprint', () => { + const source = new PlaneGeometry(20, 20, 80, 80); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(), { face: 6480, radius: 8, minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const actual = output.getAttribute('normal'); + const reference = output.clone(); + reference.computeVertexNormals(); + const expected = reference.getAttribute('normal'); + const difference = new Vector3(); + const normal = new Vector3(); + let maxError = 0; + for (let vertex = 0; vertex < actual.count; vertex++) { + difference + .fromBufferAttribute(actual, vertex) + .sub(normal.fromBufferAttribute(expected, vertex)); + maxError = Math.max(maxError, difference.length()); + } + expect(maxError).toBeLessThan(1e-6); + }); + it('adds detail under a small dab in a coarse face, keeping original positions and winding', () => { const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); const draft = new SculptMesh(source, identity); @@ -151,6 +172,32 @@ describe('sculpt mesh', () => { }, ); + it.each(['draw', 'mask'] as const)( + 'isolates a shared indexed corner during a %s dab', + (brush) => { + const source = mesh([0, 0, 0, 2, 0, 0, 0, 2, 0, -2, 0, 0, 0, -2, 0], [0, 1, 2, 0, 3, 4]); + source.addGroup(0, 3, 0); + source.addGroup(3, 3, 1); + source.setAttribute( + 'color', + new BufferAttribute(Uint8Array.from([127, 0, 0, 0, 0]), 1, true), + ); + const draft = new SculptMesh(source, identity, Float32Array.from([0.25, 0, 0, 0, 0])); + expect(draft.dab(dab(new Vector3(), { brush, minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const first = output.index!.getX(0); + const second = output.index!.getX(3); + expect(first).not.toBe(second); + expect(output.groups).toEqual(source.groups); + expect(output.getAttribute('color').array[second]).toBe(127); + expect(output.getAttribute('position').getZ(second)).toBe(0); + expect(draft.getMask()[second]).toBe(0.25); + if (brush === 'draw') expect(output.getAttribute('position').getZ(first)).toBeGreaterThan(0); + else expect(draft.getMask()[first]).toBe(1); + expect(Array.from(source.index!.array)).toEqual([0, 1, 2, 0, 3, 4]); + }, + ); + it('reuses source ray acceleration and picks live triangle positions after splits', () => { const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); From 3dc65eceb29473932f378a35ae90abd2d63ceeef Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:06:33 -0800 Subject: [PATCH 26/40] (perf) Spread dense sculpt dabs across frames --- .../plans/2026-11-23-browser-sculpting.md | 10 + src/components/SculptPointer.tsx | 60 +++-- src/core/sculpt-mesh.ts | 205 ++++++++++++------ tests/unit/sculpt-benchmark.test.ts | 69 +++++- 4 files changed, 252 insertions(+), 92 deletions(-) diff --git a/docs/superpowers/plans/2026-11-23-browser-sculpting.md b/docs/superpowers/plans/2026-11-23-browser-sculpting.md index d6133fc..d29ff56 100644 --- a/docs/superpowers/plans/2026-11-23-browser-sculpting.md +++ b/docs/superpowers/plans/2026-11-23-browser-sculpting.md @@ -36,3 +36,13 @@ exceeded the 60 Hz frame budget on the tested fixtures. Run `KITBASHER_SCULPT_VIEWPORT_BENCH=1 npm run test:e2e -- tests/e2e/sculpt-benchmark.spec.ts` to repeat the viewport measurements. + +## Wide dab measurements + +A 500,000-triangle sheet with a full-footprint 80 mm brush took 213 ms of CPU work for Mask +and 393 ms for Draw. The viewport spreads that work across frames. In the CPU probe, slices +targeted 6 ms and measured 6.4 ms at p95, with a 9.4 ms worst slice. The Draw commit took +19 ms. Preparing the first draft took 166 ms. These times exclude browser rendering. + +Run `KITBASHER_SCULPT_BENCH=1 npx vitest run tests/unit/sculpt-benchmark.test.ts` to repeat +the wide dab measurements. diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 9a49629..04fd318 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -73,6 +73,7 @@ interface Stroke { latest: Sample; path: SculptPath; released: boolean; + work: Generator | null; changed: boolean; first: Hit; grabPoint: Vector3; @@ -334,6 +335,7 @@ export function SculptPointer() { overlay.visible = true; }; const refresh = () => { + if (stroke?.work) return; const state = useEditor.getState(); const sculpt = state.sculpt; const own = sculpt && partMeshes.get(sculpt.partId); @@ -408,6 +410,7 @@ export function SculptPointer() { 'Sculpt detail reached its limit. You can keep brushing at this density.', 'info', ); + active.work?.return(false); active.draft.geometry.dispose(); prepare(); refresh(); @@ -443,32 +446,40 @@ export function SculptPointer() { active.grabPoint.copy(point); if (twin) mirroredGrab = reflect(grab, active.own); } - active.changed = - active.draft.dab({ - ...hit, - radius, - strength, - detail: s.detail, - minEdge: s.minEdge, - brush, - falloff: s.falloff, - inverted: active.eraser || sample.altKey, - pinch: s.pinch, - softenMask: brush === 'mask' && sample.shiftKey, - grab, - tangent, - aspect: brush === 'draw' ? s.aspect : 1, - mirror: twin - ? { ...twin, tangent: reflectedTangent(tangent, twin, active.own), grab: mirroredGrab } - : undefined, - }) || active.changed; + active.work = active.draft.dabWork({ + ...hit, + radius, + strength, + detail: s.detail, + minEdge: s.minEdge, + brush, + falloff: s.falloff, + inverted: active.eraser || sample.altKey, + pinch: s.pinch, + softenMask: brush === 'mask' && sample.shiftKey, + grab, + tangent, + aspect: brush === 'draw' ? s.aspect : 1, + mirror: twin + ? { ...twin, tangent: reflectedTangent(tangent, twin, active.own), grab: mirroredGrab } + : undefined, + }); }; const drain = (active: Stroke, until: number) => { do { - const sample = active.path.next(); - if (sample) apply(active, sample); - } while (active.path.pending && performance.now() < until); - if (active.released && !active.path.pending) detach(true); + if (active.work) { + const result = active.work.next(); + if (result.done) { + active.changed ||= result.value; + active.work = null; + } + } else { + const sample = active.path.next(); + if (!sample) break; + apply(active, sample); + } + } while ((active.work || active.path.pending) && performance.now() < until); + if (active.released && !active.work && !active.path.pending) detach(true); }; const finishReleased = () => { if (stroke?.released) drain(stroke, Infinity); @@ -478,7 +489,7 @@ export function SculptPointer() { frame = requestAnimationFrame(() => { frame = 0; if (stroke) drain(stroke, performance.now() + 6); - if (stroke?.path.pending) schedule(); + if (stroke && (stroke.work || stroke.path.pending)) schedule(); refresh(); }); }; @@ -574,6 +585,7 @@ export function SculptPointer() { ), changed: false, released: false, + work: null, }; if (controls) controls.enabled = false; own.geometry = draft.geometry; diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts index ad088d0..9781d3d 100644 --- a/src/core/sculpt-mesh.ts +++ b/src/core/sculpt-mesh.ts @@ -86,6 +86,9 @@ function rememberIncidence(source: BufferGeometry, incidence: Incidence) { }; } +// Let the caller enforce a frame budget between batches on large footprints. +const batchMask = 511; + const maxSplitsPerDab = 192; /** Source meshes larger than this remain brushable at their available density. */ const maxRefinedFaceCount = 1_200_000; @@ -365,6 +368,8 @@ export class SculptMesh { private baseEdits: ReadonlyMap> = new Map(); private incidentEdits = new Map>(); private readonly editedFaces = new Set(); + private readonly editedFaceBuckets = new Map(); + private readonly editedPoint = new Vector3(); private grabSamples: Map | undefined; private changed = false; private readonly facePoints = [new Vector3(), new Vector3(), new Vector3()]; @@ -442,6 +447,20 @@ export class SculptMesh { }); } + private trackEditedFace(face: number) { + const key = Math.floor(face / 128); + let bucket = this.editedFaceBuckets.get(key); + if (!bucket) this.editedFaceBuckets.set(key, (bucket = { bounds: new Box3(), faces: [] })); + if (!this.editedFaces.has(face)) { + this.editedFaces.add(face); + bucket.faces.push(face); + } + const position = this.attribute('position'); + const index = this.geometry.index!.array; + for (let corner = face * 3; corner < face * 3 + 3; corner++) + bucket.bounds.expandByPoint(this.editedPoint.fromBufferAttribute(position, index[corner])); + } + /** Unedited faces remain in the source index. Test edited faces at their live positions. */ raycast(raycaster: Raycaster, mesh: Mesh, hits: Intersection[]) { const tree = this.source.boundsTree; @@ -481,32 +500,35 @@ export class SculptMesh { b = new Vector3(), c = new Vector3(), point = new Vector3(); - for (const faceIndex of this.editedFaces) { - const [ia, ib, ic] = this.face(faceIndex); - a.fromBufferAttribute(position, ia); - b.fromBufferAttribute(position, ib); - c.fromBufferAttribute(position, ic); - const contact = - side === BackSide - ? ray.intersectTriangle(c, b, a, true, point) - : ray.intersectTriangle(a, b, c, side === FrontSide, point); - if (!contact) continue; - point.applyMatrix4(world); - const distance = point.distanceTo(raycaster.ray.origin); - if (distance < raycaster.near || distance > raycaster.far) continue; - found.push({ - distance, - point: point.clone(), - object: mesh, - faceIndex, - face: { - a: ia, - b: ib, - c: ic, - normal: Triangle.getNormal(a, b, c, new Vector3()), - materialIndex: 0, - }, - }); + for (const bucket of this.editedFaceBuckets.values()) { + if (!ray.intersectsBox(bucket.bounds)) continue; + for (const faceIndex of bucket.faces) { + const [ia, ib, ic] = this.face(faceIndex); + a.fromBufferAttribute(position, ia); + b.fromBufferAttribute(position, ib); + c.fromBufferAttribute(position, ic); + const contact = + side === BackSide + ? ray.intersectTriangle(c, b, a, true, point) + : ray.intersectTriangle(a, b, c, side === FrontSide, point); + if (!contact) continue; + point.applyMatrix4(world); + const distance = point.distanceTo(raycaster.ray.origin); + if (distance < raycaster.near || distance > raycaster.far) continue; + found.push({ + distance, + point: point.clone(), + object: mesh, + faceIndex, + face: { + a: ia, + b: ib, + c: ic, + normal: Triangle.getNormal(a, b, c, new Vector3()), + materialIndex: 0, + }, + }); + } } found.sort((a, b) => a.distance - b.distance); hits.push(...(raycaster.firstHitOnly ? found.slice(0, 1) : found)); @@ -681,7 +703,7 @@ export class SculptMesh { return Number.isFinite(facing) && facing > 0 && footprint.overlaps(a, b, c); } - private patch(footprint: Footprint) { + private *patch(footprint: Footprint): Generator, void> { const faces = new Set(); const seed = footprint.hit.face; if (seed < 0 || seed >= this.faceCount || !Number.isInteger(seed)) return faces; @@ -696,6 +718,7 @@ export class SculptMesh { queue.push(neighbor); }; for (let i = 0; i < queue.length; i++) { + if (i && (i & batchMask) === 0) yield; const face = queue[i]; if (!this.overlaps(face, footprint)) continue; faces.add(face); @@ -841,7 +864,10 @@ export class SculptMesh { this.syncCounts(); } - private refine(settings: SculptDab, brushes: { footprint: Footprint; faces: Set }[]) { + private *refine( + settings: SculptDab, + brushes: { footprint: Footprint; faces: Set }[], + ): Generator { const splits: Split[] = []; const target = Math.max( settings.minEdge * 2, @@ -856,6 +882,7 @@ export class SculptMesh { const points = [new Vector3(), new Vector3(), new Vector3()]; const targetSquared = target ** 2; for (let i = 0; i < queue.length; i++) { + if (i && (i & batchMask) === 0) yield; const id = queue[i]; if ( edited.has(id) && @@ -1040,14 +1067,17 @@ export class SculptMesh { return Number.isFinite(cross.lengthSq()) ? cross : cross.set(0, 0, 0); } - private applyMoves(moves: Map) { + private *applyMoves(moves: Map): Generator { const position = this.attribute('position'); const bounds = this.geometry.boundingBox; const sphere = this.geometry.boundingSphere; let first = this.vertexCount; let last = -1; const batch = moves.size > 4096; + let count = 0; for (const [weld, local] of moves) { + if (count && (count & batchMask) === 0) yield; + count++; for (const vertex of this.renderVertices(weld)) { position.setXYZ(vertex, local.x, local.y, local.z); if (batch) { @@ -1063,16 +1093,19 @@ export class SculptMesh { } /** Accumulate area-weighted render normals in flat buffers for widely affected surfaces. */ - private deformDense( + private *deformDense( moves: Map, changedFaces: Set, output: BufferAttribute, - ) { + ): Generator { const index = this.geometry.index!.array; const affected = new Uint8Array(this.vertexCount); let first = this.vertexCount; let last = -1; + let count = 0; for (const face of changedFaces) { + if (count && (count & batchMask) === 0) yield; + count++; for (let corner = face * 3; corner < face * 3 + 3; corner++) { const vertex = index[corner]; affected[vertex] = 1; @@ -1082,9 +1115,10 @@ export class SculptMesh { } const size = (last - first + 1) * 3; const faceCross = new Vector3(); - const accumulate = () => { + const accumulate = function* (this: SculptMesh): Generator { const sums = new Float64Array(size); for (let face = 0; face < this.faceCount; face++) { + if (face && (face & batchMask) === 0) yield; const corner = face * 3; const a = index[corner]; const b = index[corner + 1]; @@ -1103,14 +1137,15 @@ export class SculptMesh { } return sums; }; - const before = accumulate(); - this.applyMoves(moves); - const after = accumulate(); + const before = yield* accumulate.call(this); + yield* this.applyMoves(moves); + const after = yield* accumulate.call(this); const previous = new Vector3(); const current = new Vector3(); const normal = new Vector3(); const rotate = new Quaternion(); for (let vertex = first; vertex <= last; vertex++) { + if (vertex !== first && (vertex & batchMask) === 0) yield; if (!affected[vertex]) continue; const component = (vertex - first) * 3; previous.fromArray(before, component); @@ -1124,14 +1159,18 @@ export class SculptMesh { output.needsUpdate = true; } - private deform(moves: Map) { + private *deform(moves: Map): Generator { const outputNormals = this.geometry.getAttribute('normal') as BufferAttribute | undefined; const changedFaces = new Set(); - for (const weld of moves.keys()) + let count = 0; + for (const weld of moves.keys()) { + if (count && (count & batchMask) === 0) yield; + count++; for (const face of this.incidence(weld)) changedFaces.add(face); - for (const face of changedFaces) this.editedFaces.add(face); + } if (outputNormals && changedFaces.size > Math.max(4096, this.faceCount / 8)) { - this.deformDense(moves, changedFaces, outputNormals); + yield* this.deformDense(moves, changedFaces, outputNormals); + yield* this.trackEditedFaces(changedFaces); return; } const normals = new Map(); @@ -1139,6 +1178,7 @@ export class SculptMesh { const faceBefore = new Map(); if (outputNormals) { for (const face of changedFaces) { + if ((count++ & batchMask) === 0) yield; for (const vertex of this.face(face)) { if (renderFaces.has(vertex)) continue; const fan = new Set(); @@ -1154,12 +1194,13 @@ export class SculptMesh { } } } - this.applyMoves(moves); + yield* this.applyMoves(moves); if (outputNormals) { const after = new Map(); const rotate = new Quaternion(); const normal = new Vector3(); for (const [vertex, fan] of renderFaces) { + if ((count++ & batchMask) === 0) yield; const current = new Vector3(); for (const face of fan) { if (!after.has(face)) after.set(face, this.localFaceCross(face)); @@ -1174,9 +1215,27 @@ export class SculptMesh { } outputNormals.needsUpdate = true; } + yield* this.trackEditedFaces(changedFaces); + } + + private *trackEditedFaces(faces: Set) { + let count = 0; + for (const face of faces) { + if (count && (count & batchMask) === 0) yield; + count++; + this.trackEditedFace(face); + } } - dab(settings: SculptDab) { + dab(settings: SculptDab): boolean { + const work = this.dabWork(settings); + let result = work.next(); + while (!result.done) result = work.next(); + return result.value; + } + + /** A cancellable draft operation. The source geometry remains immutable between batches. */ + *dabWork(settings: SculptDab): Generator { if (!(settings.radius > 0 && settings.strength > 0) || !this.orientation) return false; if (settings.brush !== 'grab') this.grabSamples = undefined; else if (!settings.grab?.lengthSq() && !settings.mirror?.grab?.lengthSq()) return false; @@ -1184,14 +1243,17 @@ export class SculptMesh { const groupCount = this.geometry.groups.length; let samples = this.grabSamples; let splits: Split[] = []; + let count = 0; if (!samples) { const hits: SculptHit[] = [settings]; if (settings.mirror) hits.push(settings.mirror); - const brushes = hits.map((hit, index) => { + const brushes = []; + for (const hit of hits) { const footprint = new Footprint(hit, settings.radius, settings.aspect ?? 1); - return { footprint, faces: this.patch(footprint), mirrored: index === 1 }; - }); - splits = this.refine(settings, brushes); + const faces = yield* this.patch(footprint); + brushes.push({ footprint, faces, mirrored: hit === settings.mirror }); + } + splits = yield* this.refine(settings, brushes); samples = new Map(); const visited = new Uint8Array(this.weldCount); const index = this.geometry.index!.array; @@ -1199,6 +1261,8 @@ export class SculptMesh { for (const { footprint, faces, mirrored } of brushes) { const pass = mirrored ? 2 : 1; for (const face of faces) { + if (count && (count & batchMask) === 0) yield; + count++; for (let i = face * 3; i < face * 3 + 3; i++) { const vertex = index[i]; const weld = this.weldOf[vertex]; @@ -1214,6 +1278,8 @@ export class SculptMesh { const moves = new Map(); const masks = new Map(); for (const [weld, { footprint, weight, mirrored }] of samples) { + if (count && (count & batchMask) === 0) yield; + count++; const protection = this.maskAt(weld); const strength = Math.min(1, settings.strength) * weight; if (settings.brush === 'mask') { @@ -1259,17 +1325,19 @@ export class SculptMesh { this.geometry.index!.needsUpdate = true; for (const split of splits) for (const { id, child } of split.faces) { - this.editedFaces.add(id); - this.editedFaces.add(child); + this.trackEditedFace(id); + this.trackEditedFace(child); } } - if (moves.size) this.deform(moves); + if (moves.size) yield* this.deform(moves); if (masks.size) { const mask = this.attribute(maskName); const batch = masks.size > 4096; let first = this.vertexCount; let last = -1; for (const [weld, value] of masks) { + if (count && (count & batchMask) === 0) yield; + count++; for (const vertex of this.renderVertices(weld)) { mask.setX(vertex, value); if (batch) { @@ -1293,28 +1361,31 @@ export class SculptMesh { !this.editedFaces.size ) return; - const dirtyBounds = new Box3(); - const sourcePosition = this.source.getAttribute('position'); - const point = new Vector3(); - for (const face of this.editedFaces) { - for (let offset = 0; offset < 3; offset++) { - const corner = face * 3 + offset; - const vertex = this.source.index?.getX(corner) ?? corner; - dirtyBounds.expandByPoint(point.fromBufferAttribute(sourcePosition, vertex)); - } - } - const nodes = new Set(); - sourceTree.shapecast({ - intersectsBounds: (bounds, _leaf, _score, _depth, node) => { - if (!bounds.intersectsBox(dirtyBounds)) return false; - nodes.add(node); - return true; - }, - }); const data = MeshBVH.serialize(sourceTree, { cloneBuffers: false }); const roots = data.roots.map((root) => root.slice(0)); const tree = MeshBVH.deserialize({ ...data, roots }, geometry, { setIndex: false }); - tree.refit(nodes); + if (this.editedFaces.size * 4 > this.faceCount) tree.refit(); + else { + const dirtyBounds = new Box3(); + const sourcePosition = this.source.getAttribute('position'); + const point = new Vector3(); + for (const face of this.editedFaces) { + for (let offset = 0; offset < 3; offset++) { + const corner = face * 3 + offset; + const vertex = this.source.index?.getX(corner) ?? corner; + dirtyBounds.expandByPoint(point.fromBufferAttribute(sourcePosition, vertex)); + } + } + const nodes = new Set(); + sourceTree.shapecast({ + intersectsBounds: (bounds, _leaf, _score, _depth, node) => { + if (!bounds.intersectsBox(dirtyBounds)) return false; + nodes.add(node); + return true; + }, + }); + tree.refit(nodes); + } geometry.boundsTree = tree; } diff --git a/tests/unit/sculpt-benchmark.test.ts b/tests/unit/sculpt-benchmark.test.ts index 79bbf57..81c4b5b 100644 --- a/tests/unit/sculpt-benchmark.test.ts +++ b/tests/unit/sculpt-benchmark.test.ts @@ -2,7 +2,15 @@ import { it, expect } from 'vitest'; import { writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { DoubleSide, Matrix4, Mesh, MeshBasicMaterial, PlaneGeometry, Raycaster } from 'three'; +import { + DoubleSide, + Matrix4, + Mesh, + MeshBasicMaterial, + PlaneGeometry, + Raycaster, + Vector3, +} from 'three'; import { MeshBVH } from 'three-mesh-bvh'; import { SculptMesh } from '../../src/core/sculpt-mesh'; @@ -77,3 +85,62 @@ it.skipIf(!enabled)('profiles coarse and dense sculpt strokes', () => { JSON.stringify(metrics, null, 2), ); }); + +it.skipIf(!enabled)('profiles cooperative wide dabs on a dense mesh', () => { + const segments = 500; + const source = new PlaneGeometry(100, 100, segments, segments); + source.boundsTree = new MeshBVH(source, { indirect: true }); + const measurements = []; + for (const brush of ['mask', 'draw'] as const) { + const draft = new SculptMesh(source, new Matrix4()); + const preparation = timed(() => draft.prepare()); + const job = draft.dabWork({ + brush, + point: new Vector3(), + normal: new Vector3(0, 0, 1), + face: 2 * ((segments / 2) * segments + segments / 2), + radius: 80, + strength: 1, + detail: 0, + minEdge: 0.04, + falloff: 'hard', + }); + let changed = false; + let done = false; + const slices: number[] = []; + while (!done) { + const { ms } = timed(() => { + const deadline = performance.now() + 6; + do { + const result = job.next(); + if (result.done) { + done = true; + changed = result.value; + } + } while (!done && performance.now() < deadline); + }); + slices.push(ms); + } + expect(changed).toBe(true); + expect(slices.length).toBeGreaterThan(1); + const committed = timed(() => draft.finish()); + const sorted = [...slices].sort((a, b) => a - b); + measurements.push({ + brush, + triangles: source.index!.count / 3, + prepareMs: preparation.ms, + totalDabMs: slices.reduce((sum, value) => sum + value, 0), + slices: slices.length, + sliceP95Ms: sorted[Math.ceil(sorted.length * 0.95) - 1], + sliceWorstMs: sorted.at(-1), + commitMs: committed.ms, + }); + committed.result?.dispose(); + draft.geometry.dispose(); + } + source.dispose(); + writeFileSync( + join(tmpdir(), 'kitbasher-sculpt-wide.json'), + JSON.stringify(measurements, null, 2), + ); +}); From 4749411d487f416301647510ee9107e967f3cd80 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:12:57 -0800 Subject: [PATCH 27/40] (fix) Queue input while sculpt strokes finish --- src/components/SculptPointer.tsx | 124 ++++++++++++++++++++++++++----- src/core/commands.ts | 24 ++++-- src/core/store.ts | 23 +++--- src/hooks/useWorkbench.ts | 9 ++- tests/e2e/sculpt.spec.ts | 50 +++++++++++++ 5 files changed, 193 insertions(+), 37 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 04fd318..b08d1de 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -135,6 +135,16 @@ export function SculptPointer() { let idleSource: BufferGeometry | null = null; let idleWeights: Float32Array | null = null; let stroke: Stroke | null = null; + let disposed = false; + const afterStroke: (() => void)[] = []; + let queuedPointer: { + down: PointerEvent; + partId: string; + epoch: number; + moves: PointerEvent[]; + up?: PointerEvent; + cancelled: boolean; + } | null = null; let warm: { source: BufferGeometry; mask: Float32Array | null; @@ -192,9 +202,30 @@ export function SculptPointer() { stroke.draft.raycast(ray, mesh, hits); return hits; }; - const pick = (sample: Sample, own: Mesh, exactOcclusion = false): Hit | null => { + const pick = ( + sample: Sample, + own: Mesh, + exactOcclusion = false, + source?: BufferGeometry, + ): Hit | null => { setRay(sample); - const hit = intersect(own)[0]; + let hit: Intersection | undefined; + if (source) { + // The view can still hold the previous render's mesh immediately after a commit. + const displayed = own.geometry; + const hits: Intersection[] = []; + own.geometry = source; + try { + acceleratedRaycast.call(own, ray, hits); + hit = hits.reduce( + (nearest, current) => + !nearest || current.distance < nearest.distance ? current : nearest, + undefined, + ); + } finally { + own.geometry = displayed; + } + } else hit = intersect(own)[0]; if (!hit || !visible(own)) return null; for (const mesh of partMeshes.values()) { if (mesh === own || !visible(mesh)) continue; @@ -375,7 +406,8 @@ export function SculptPointer() { if (!active) return; stroke = null; if (active.controls) active.controls.enabled = active.controlsEnabled; - if (canvas.hasPointerCapture(active.id)) canvas.releasePointerCapture(active.id); + if (!active.released && canvas.hasPointerCapture(active.id)) + canvas.releasePointerCapture(active.id); if (active.own.geometry === active.draft.geometry) active.own.geometry = active.before; overlay.visible = false; if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; @@ -412,6 +444,7 @@ export function SculptPointer() { ); active.work?.return(false); active.draft.geometry.dispose(); + for (const action of afterStroke.splice(0)) action(); prepare(); refresh(); }; @@ -481,8 +514,10 @@ export function SculptPointer() { } while ((active.work || active.path.pending) && performance.now() < until); if (active.released && !active.work && !active.path.pending) detach(true); }; - const finishReleased = () => { - if (stroke?.released) drain(stroke, Infinity); + const defer = (action: () => void) => { + if (!stroke?.released) return false; + afterStroke.push(action); + return true; }; const schedule = () => { if (frame) return; @@ -493,11 +528,17 @@ export function SculptPointer() { refresh(); }); }; - const down = (event: PointerEvent) => { - finishReleased(); + const capture = (event: PointerEvent) => { + try { + canvas.setPointerCapture(event.pointerId); + } catch { + /* The pointer may have ended before the queued press is replayed. */ + } + }; + const down = (event: PointerEvent, ended = false) => { const state = useEditor.getState(); const sculpt = state.sculpt; - if (stroke) { + if (stroke && !stroke.released) { event.stopImmediatePropagation(); return; } @@ -516,18 +557,30 @@ export function SculptPointer() { event.metaKey ) return; + if (stroke?.released) { + event.preventDefault(); + event.stopImmediatePropagation(); + if (queuedPointer) return; + const gesture = { + down: event, + partId: sculpt.partId, + epoch: state.sceneEpoch, + moves: [], + cancelled: false, + }; + queuedPointer = gesture; + capture(event); + defer(() => replay(gesture)); + return; + } const target = state.scene.parts.find((part) => part.id === sculpt.partId); const own = target && partMeshes.get(target.id); if (!target || !own || target.locked || !visible(own)) return; - const hit = pick(event, own, true); + const hit = pick(event, own, true, target.geometry); if (!hit) return; event.preventDefault(); event.stopImmediatePropagation(); - try { - canvas.setPointerCapture(event.pointerId); - } catch { - /* Synthetic pointer events lack native capture. */ - } + if (!ended) capture(event); const controls = get().controls as { enabled: boolean } | null; const settings = sculpt.settings; const camera = get().camera; @@ -592,7 +645,12 @@ export function SculptPointer() { hover = event; schedule(); }; - const move = (event: PointerEvent) => { + const move = (event: PointerEvent, replayed = false) => { + if (!replayed && queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.moves.push(event); + event.stopImmediatePropagation(); + return; + } if (stroke) { if (event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); @@ -604,7 +662,13 @@ export function SculptPointer() { hover = event; schedule(); }; - const release = (event: PointerEvent) => { + const release = (event: PointerEvent, replayed = false) => { + if (!replayed && queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.up = event; + queuedPointer = null; + event.stopImmediatePropagation(); + return; + } if (!stroke || stroke.released || event.pointerId !== stroke.id) return; event.stopImmediatePropagation(); const { pressure, pointerType, tiltX, tiltY, twist } = stroke.latest; @@ -630,17 +694,40 @@ export function SculptPointer() { drain(active, performance.now() + 6); if (stroke) schedule(); }; + const replay = (gesture: NonNullable) => { + if (defer(() => replay(gesture))) return; + if (queuedPointer === gesture) queuedPointer = null; + const state = useEditor.getState(); + if ( + disposed || + gesture.cancelled || + state.sceneEpoch !== gesture.epoch || + state.sculpt?.partId !== gesture.partId + ) + return; + down(gesture.down, !!gesture.up); + for (const event of gesture.moves) move(event, true); + if (gesture.up) release(gesture.up, true); + }; const cancel = (event: PointerEvent) => { + if (queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.cancelled = true; + queuedPointer = null; + } if (stroke?.id === event.pointerId && !stroke.released) detach(false); }; const escape = (event: KeyboardEvent) => { if (event.key !== 'Escape' || !stroke) return; event.preventDefault(); event.stopImmediatePropagation(); - detach(false); + if (!stroke.released) detach(false); }; const blur = () => { hover = null; + if (queuedPointer) { + queuedPointer.cancelled = true; + queuedPointer = null; + } if (!stroke?.released) detach(false); refresh(); }; @@ -671,7 +758,7 @@ export function SculptPointer() { schedule(); }); prepare(); - useSculptStrokeFinisher(finishReleased); + useSculptStrokeFinisher(defer); canvas.addEventListener('pointerdown', down, true); canvas.addEventListener('lostpointercapture', cancel); canvas.addEventListener('pointerleave', leave); @@ -682,6 +769,7 @@ export function SculptPointer() { window.addEventListener('keydown', escape, true); window.addEventListener('blur', blur); return () => { + disposed = true; unsubscribe(); useSculptStrokeFinisher(null); canvas.removeEventListener('pointerdown', down, true); diff --git a/src/core/commands.ts b/src/core/commands.ts index 8049dcd..31b1fdd 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -7,7 +7,7 @@ import { primaryShortcutText, usePreferences } from './preferences'; import { canRedo, canUndo, - finishReleasedSculpt, + afterReleasedSculpt, refineEdited, useEditor, warpEdited, @@ -21,8 +21,19 @@ import { } from './transform-selection'; import type { SurfacePoint } from './types'; +function waitForReleasedSculpt(run: () => Promise) { + let resolveSave!: () => void; + let rejectSave!: (error: unknown) => void; + const saved = new Promise((resolve, reject) => { + resolveSave = resolve; + rejectSave = reject; + }); + if (afterReleasedSculpt(() => void run().then(resolveSave, rejectSave))) return saved; +} + export async function saveCurrentScene() { - finishReleasedSculpt(); + const pending = waitForReleasedSculpt(saveCurrentScene); + if (pending) return pending; if (useEditor.getState().driveFile) { if (!(await driveAutosave.flush())) useDrive.setState({ dialogOpen: true }); return; @@ -31,7 +42,8 @@ export async function saveCurrentScene() { } export async function downloadCurrentScene() { - finishReleasedSculpt(); + const pending = waitForReleasedSculpt(downloadCurrentScene); + if (pending) return pending; const state = useEditor.getState(); if (state.busy) return; const { revision } = state; @@ -304,8 +316,8 @@ export function editorCommands(context: CommandContext = {}) { export: command( 'Export assembly…', () => { - finishReleasedSculpt(); - state.setModal('export'); + const open = () => useEditor.getState().setModal('export'); + if (!afterReleasedSculpt(open)) open(); }, !!state.scene.parts.length, 'export', @@ -332,7 +344,7 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { - finishReleasedSculpt(); + if (afterReleasedSculpt(() => executeEditorCommand(id, context))) return; const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/store.ts b/src/core/store.ts index bba045c..bdef1a9 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -2134,7 +2134,7 @@ export const useEditor = create((set, get) => ({ focusRequest: { id: 0, all: true }, measurement: [], select: (id, additive = false) => { - finishReleasedSculpt(); + if (afterReleasedSculpt(() => get().select(id, additive))) return; set((state) => ({ selected: id ? additive @@ -2248,7 +2248,7 @@ export const useEditor = create((set, get) => ({ })), closeContextMenu: () => set({ contextMenu: null }), setTool: (tool) => { - finishReleasedSculpt(); + if (afterReleasedSculpt(() => get().setTool(tool))) return; const state = get(); if (tool === 'warp' && state.tool === 'warp' && state.warp) set({ navigationMode: null, pivotPicking: false }); @@ -2442,12 +2442,14 @@ export const useEditor = create((set, get) => ({ })), }); }, - setNavigationMode: (navigationMode) => + setNavigationMode: (navigationMode) => { + if (afterReleasedSculpt(() => get().setNavigationMode(navigationMode))) return; set(() => ({ navigationMode, pivotPicking: false, painting: false, - })), + })); + }, centerOrbit: () => { const state = get(); if (!state.scene.parts.some((part) => part.visible && state.selected.includes(part.id))) { @@ -3530,6 +3532,7 @@ export const useEditor = create((set, get) => ({ return true; }, changeSculptMask: (operation) => { + if (afterReleasedSculpt(() => get().changeSculptMask(operation))) return; const state = get(); const { sculpt } = state; const part = sculpt && state.scene.parts.find((candidate) => candidate.id === sculpt.partId); @@ -4960,12 +4963,10 @@ export const useEditor = create((set, get) => ({ return next === state.scene.name ? {} : changed(state, { ...state.scene, name: next }); }), undo: () => { - finishReleasedSculpt(); - moveHistory('undo'); + if (!afterReleasedSculpt(() => get().undo())) moveHistory('undo'); }, redo: () => { - finishReleasedSculpt(); - moveHistory('redo'); + if (!afterReleasedSculpt(() => get().redo())) moveHistory('redo'); }, setView: (patch) => { if (patch.orbitSelection !== undefined) saveOrbitPreference(patch.orbitSelection); @@ -5000,14 +5001,14 @@ useEditor.subscribe((state, previous) => { recordNotification(state.toast.message, state.toast.kind); }); -let finishSculptStroke: (() => void) | null = null; +let finishSculptStroke: ((action: () => void) => boolean) | null = null; export function useSculptStrokeFinisher(finish: typeof finishSculptStroke) { finishSculptStroke = finish; } -export function finishReleasedSculpt() { - finishSculptStroke?.(); +export function afterReleasedSculpt(action: () => void): boolean { + return finishSculptStroke?.(action) ?? false; } let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 2569878..813e84c 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -1,6 +1,7 @@ import { useEffect, useRef } from 'react'; import { joinLiveSession } from '../core/live'; import { + afterReleasedSculpt, committedScene, chosenRefinePoint, brushingRefine, @@ -188,7 +189,11 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { event.preventDefault(); state.endPaintStroke(); orbitKey = event.code || keyName(event.key); - useEditor.setState({ temporaryOrbit: true }); + const held = orbitKey; + const orbit = () => { + if (orbitKey === held) useEditor.setState({ temporaryOrbit: true }); + }; + if (!afterReleasedSculpt(orbit)) orbit(); return; } const key = event.key.toLowerCase(); @@ -295,7 +300,7 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { return; } if (state.tool === 'sculpt') { - state.cancelSculptStroke(); + if (!afterReleasedSculpt(() => {})) state.cancelSculptStroke(); return; } // Otherwise Escape leaves the tool, as it does for Warp. diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 9ae2940..d03e0b3 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -115,6 +115,56 @@ test('commits a released stroke before a tool change in the same frame', async ( expect((await mesh(page)).peak).toBeGreaterThan(before.peak); }); +test('queues another press and mask changes while a released stroke finishes', async ({ page }) => { + await openSculpt(page); + const first = await screen(page, [-1, 0, 2]); + const second = await screen(page, [1, 0, 2]); + await page.evaluate( + ({ first, second }) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + // Force the released-stroke path regardless of the test machine's speed. + performance.now = () => (elapsed += 8); + try { + for (const point of [first, second]) { + const pen = { + pointerId: 24, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + clientX: point.x, + clientY: point.y, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + } + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + const invert = Array.from(document.querySelectorAll('button')).find( + (button) => button.textContent?.trim() === 'Invert mask', + ); + if (!invert) throw new Error('Missing Invert mask button'); + invert.click(); + } finally { + performance.now = now; + } + }, + { first, second }, + ); + await expect + .poll(() => + inStore(page, (state) => { + const past = state.sculpt?.past ?? []; + return { + strokes: past.filter((step) => step.before.geometry !== step.after.geometry).length, + mask: state.sculpt?.mask?.every((weight) => weight === 1), + }; + }), + ) + .toEqual({ strokes: 2, mask: true }); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From 8b5e9517e46b4215159a183fd1f2145503952c7c Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Mon, 23 Nov 2026 22:17:51 -0800 Subject: [PATCH 28/40] (fix) Preserve released sculpt work across editor actions --- src/components/SculptPointer.tsx | 10 ++++ src/components/Viewport.tsx | 6 +- src/core/commands.ts | 17 +++++- src/core/store.ts | 7 ++- src/hooks/useWorkbench.ts | 6 +- tests/e2e/sculpt.spec.ts | 96 ++++++++++++++++++++++++++++++++ 6 files changed, 132 insertions(+), 10 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index b08d1de..4d2c441 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -81,6 +81,13 @@ interface Stroke { applied: Sample | null; } +const sculptPreviews = new WeakMap(); + +export function restoreSculptPreview(mesh: Mesh) { + const preview = sculptPreviews.get(mesh); + if (preview) mesh.geometry = preview; +} + export function SculptPointer() { const get = useThree((s) => s.get); const invalidate = useThree((s) => s.invalidate); @@ -408,6 +415,7 @@ export function SculptPointer() { if (active.controls) active.controls.enabled = active.controlsEnabled; if (!active.released && canvas.hasPointerCapture(active.id)) canvas.releasePointerCapture(active.id); + sculptPreviews.delete(active.own); if (active.own.geometry === active.draft.geometry) active.own.geometry = active.before; overlay.visible = false; if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; @@ -641,6 +649,7 @@ export function SculptPointer() { work: null, }; if (controls) controls.enabled = false; + sculptPreviews.set(own, draft.geometry); own.geometry = draft.geometry; hover = event; schedule(); @@ -720,6 +729,7 @@ export function SculptPointer() { if (event.key !== 'Escape' || !stroke) return; event.preventDefault(); event.stopImmediatePropagation(); + if (queuedPointer) cancel(queuedPointer.down); if (!stroke.released) detach(false); }; const blur = () => { diff --git a/src/components/Viewport.tsx b/src/components/Viewport.tsx index ea6909d..7a5658f 100644 --- a/src/components/Viewport.tsx +++ b/src/components/Viewport.tsx @@ -71,7 +71,7 @@ import { FreeTransformController, FreeTransformPrompt } from './FreeTransform'; import { CombinedTransform } from './CombinedTransform'; import { ManagedTransformControls } from './ManagedTransformControls'; import { WarpOverlay, shownWarpPreview } from './WarpOverlay'; -import { SculptPointer } from './SculptPointer'; +import { restoreSculptPreview, SculptPointer } from './SculptPointer'; import { beginWarpStroke, endingWarpStroke, WarpStrokeController } from './WarpStroke'; import { beginRefinePaint, @@ -211,6 +211,10 @@ const PartMesh = memo(function PartMesh({ (proxy?.source === part.geometry && shouldDrawProxy(detail, moving, headset, precision) ? proxy.geometry : part.geometry); + useLayoutEffect(() => { + const mesh = partMeshes.get(part.id); + if (mesh) restoreSculptPreview(mesh); + }); const [brushHit, setBrushHit] = useState(null); const register = useCallback( (mesh: Mesh | null) => { diff --git a/src/core/commands.ts b/src/core/commands.ts index 31b1fdd..8ecc93d 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -343,8 +343,21 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; -export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { - if (afterReleasedSculpt(() => executeEditorCommand(id, context))) return; +export function executeEditorCommand( + id: CommandId, + context: CommandContext = {}, + deferred = false, +) { + if (afterReleasedSculpt(() => executeEditorCommand(id, context, true))) return; + const { busy, sceneEpoch } = useEditor.getState(); + if (deferred && busy) { + const unsubscribe = useEditor.subscribe((state) => { + if (state.busy && state.sceneEpoch === sceneEpoch) return; + unsubscribe(); + if (state.sceneEpoch === sceneEpoch) executeEditorCommand(id, context, true); + }); + return; + } const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/store.ts b/src/core/store.ts index bdef1a9..2a28f38 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -4755,7 +4755,8 @@ export const useEditor = create((set, get) => ({ ? { scene: { ...state.scene, parts } } : changed(state, { ...state.scene, parts }, checkpoint); }), - patchParts: (ids, patch, checkpoint = true) => + patchParts: (ids, patch, checkpoint = true) => { + if (afterReleasedSculpt(() => get().patchParts(ids, patch, checkpoint))) return; set((state) => { const keys = Object.keys(patch) as (keyof Part)[]; const differs = (part: Part) => @@ -4769,8 +4770,10 @@ export const useEditor = create((set, get) => ({ }, checkpoint, ); - }), + }); + }, setDisplayColor: (ids, color, checkpoint = true) => { + if (afterReleasedSculpt(() => get().setDisplayColor(ids, color, checkpoint))) return; set((state) => { const targets = new Set(ids); if ( diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 813e84c..9d71a23 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -348,11 +348,7 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { }; const up = (event: KeyboardEvent) => { if (event.key === 'Shift') useEditor.setState({ precision: false }); - if ( - useEditor.getState().temporaryOrbit && - orbitKey !== null && - (event.code || keyName(event.key)) === orbitKey - ) { + if (orbitKey !== null && (event.code || keyName(event.key)) === orbitKey) { event.preventDefault(); orbitKey = null; useEditor.setState({ temporaryOrbit: false }); diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index d03e0b3..8c19ed2 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -165,6 +165,102 @@ test('queues another press and mask changes while a released stroke finishes', a .toEqual({ strokes: 2, mask: true }); }); +test('cancels a held queued press and preserves the released stroke through part edits', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (point) => { + const storeUrl = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!; + const { useEditor } = await import(storeUrl); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 24, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + const press = () => + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + const release = () => canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + try { + press(); + release(); + press(); + document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + release(); + for (const event of ['keydown', 'keyup']) { + document.body.dispatchEvent( + new KeyboardEvent(event, { key: ' ', code: 'Space', bubbles: true }), + ); + } + useEditor.getState().patchParts(['block'], { name: 'Renamed after release' }); + } finally { + performance.now = now; + } + }, point); + await expect + .poll(() => + inStore(page, (state) => [ + state.sculpt?.past.length, + state.temporaryOrbit, + state.scene.parts[0].name, + ]), + ) + .toEqual([1, false, 'Renamed after release']); +}); + +test('runs a queued undo after saving a released stroke', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect.poll(() => inStore(page, (state) => state.sculpt?.future.length)).toBe(1); + expect(await mesh(page)).toEqual(before); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From 7492ee76873978d93faa581707f0101ff9c75777 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 09:52:53 -0800 Subject: [PATCH 29/40] (fix) Restore committed mesh after sculpt cancellation --- src/components/SculptPointer.tsx | 7 +++--- tests/e2e/sculpt.spec.ts | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 4d2c441..4403c7c 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -63,7 +63,6 @@ interface Stroke { epoch: number; revision: number; own: Mesh; - before: BufferGeometry; draft: SculptMesh; settings: SculptureSettings; controls: { enabled: boolean } | null; @@ -416,7 +415,10 @@ export function SculptPointer() { if (!active.released && canvas.hasPointerCapture(active.id)) canvas.releasePointerCapture(active.id); sculptPreviews.delete(active.own); - if (active.own.geometry === active.draft.geometry) active.own.geometry = active.before; + if (active.own.geometry === active.draft.geometry) { + const part = useEditor.getState().scene.parts.find(({ id }) => id === active.target.id); + active.own.geometry = part?.geometry ?? active.target.geometry; + } overlay.visible = false; if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; if (accept && active.changed) { @@ -620,7 +622,6 @@ export function SculptPointer() { epoch: state.sceneEpoch, revision: sculpt.revision, own, - before: own.geometry, draft, controls, controlsEnabled: controls?.enabled ?? false, diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 8c19ed2..ffa8704 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -219,6 +219,48 @@ test('cancels a held queued press and preserves the released stroke through part .toEqual([1, false, 'Renamed after release']); }); +test('restores the committed mesh when a replayed preview is cancelled', async ({ page }) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + const pen = { + clientX: point.x, + clientY: point.y, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + try { + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 40, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', { ...pen, pointerId: 40 })); + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 41, buttons: 1 })); + } finally { + performance.now = now; + } + }, point); + const previewState = () => + page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { partMeshes } = await import( + urls.find((url) => /\/src\/xr\/part-meshes\.ts/.test(url))! + ); + const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); + const state = useEditor.getState(); + return { + strokes: state.sculpt?.past.length, + committed: partMeshes.get('block').geometry === state.scene.parts[0].geometry, + }; + }); + await expect.poll(previewState).toEqual({ strokes: 1, committed: false }); + await page.keyboard.press('Escape'); + await expect.poll(previewState).toEqual({ strokes: 1, committed: true }); +}); + test('runs a queued undo after saving a released stroke', async ({ page }) => { await openSculpt(page); const before = await mesh(page); From d86695bf34888e3bdcd0a7d1fe1ba04e71ca0718 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 10:16:56 -0800 Subject: [PATCH 30/40] (fix) Preserve the order of actions queued after sculpting --- src/components/SculptPointer.tsx | 16 ++++++++-- src/core/commands.ts | 17 ++-------- src/core/store.ts | 1 + tests/e2e/sculpt.spec.ts | 53 +++++++++++++++++++++++++++++++- 4 files changed, 69 insertions(+), 18 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 4403c7c..dad0b3c 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -143,6 +143,7 @@ export function SculptPointer() { let stroke: Stroke | null = null; let disposed = false; const afterStroke: (() => void)[] = []; + let runningAction = false; let queuedPointer: { down: PointerEvent; partId: string; @@ -454,7 +455,7 @@ export function SculptPointer() { ); active.work?.return(false); active.draft.geometry.dispose(); - for (const action of afterStroke.splice(0)) action(); + flushActions(); prepare(); refresh(); }; @@ -525,15 +526,26 @@ export function SculptPointer() { if (active.released && !active.work && !active.path.pending) detach(true); }; const defer = (action: () => void) => { - if (!stroke?.released) return false; + if (!stroke?.released && (runningAction || !afterStroke.length)) return false; afterStroke.push(action); return true; }; + const flushActions = () => { + if (runningAction) return; + runningAction = true; + try { + while (afterStroke.length && !stroke?.released && !useEditor.getState().busy) + afterStroke.shift()!(); + } finally { + runningAction = false; + } + }; const schedule = () => { if (frame) return; frame = requestAnimationFrame(() => { frame = 0; if (stroke) drain(stroke, performance.now() + 6); + flushActions(); if (stroke && (stroke.work || stroke.path.pending)) schedule(); refresh(); }); diff --git a/src/core/commands.ts b/src/core/commands.ts index 8ecc93d..31b1fdd 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -343,21 +343,8 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; -export function executeEditorCommand( - id: CommandId, - context: CommandContext = {}, - deferred = false, -) { - if (afterReleasedSculpt(() => executeEditorCommand(id, context, true))) return; - const { busy, sceneEpoch } = useEditor.getState(); - if (deferred && busy) { - const unsubscribe = useEditor.subscribe((state) => { - if (state.busy && state.sceneEpoch === sceneEpoch) return; - unsubscribe(); - if (state.sceneEpoch === sceneEpoch) executeEditorCommand(id, context, true); - }); - return; - } +export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { + if (afterReleasedSculpt(() => executeEditorCommand(id, context))) return; const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/store.ts b/src/core/store.ts index 2a28f38..476cd1a 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -4972,6 +4972,7 @@ export const useEditor = create((set, get) => ({ if (!afterReleasedSculpt(() => get().redo())) moveHistory('redo'); }, setView: (patch) => { + if (patch.explode !== undefined && afterReleasedSculpt(() => get().setView(patch))) return; if (patch.orbitSelection !== undefined) saveOrbitPreference(patch.orbitSelection); if (patch.partColors !== undefined) savePartColorMode(patch.partColors); if (patch.clip) { diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index ffa8704..529e5be 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -204,6 +204,7 @@ test('cancels a held queued press and preserves the released stroke through part ); } useEditor.getState().patchParts(['block'], { name: 'Renamed after release' }); + useEditor.getState().setView({ explode: true }); } finally { performance.now = now; } @@ -214,9 +215,10 @@ test('cancels a held queued press and preserves the released stroke through part state.sculpt?.past.length, state.temporaryOrbit, state.scene.parts[0].name, + state.view.explode, ]), ) - .toEqual([1, false, 'Renamed after release']); + .toEqual([1, false, 'Renamed after release', true]); }); test('restores the committed mesh when a replayed preview is cancelled', async ({ page }) => { @@ -303,6 +305,55 @@ test('runs a queued undo after saving a released stroke', async ({ page }) => { expect(await mesh(page)).toEqual(before); }); +test('keeps Undo ahead of a mask edit queued behind Save', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + const invert = Array.from(document.querySelectorAll('button')).find( + (button) => button.textContent?.trim() === 'Invert mask', + ); + if (!invert) throw new Error('Missing Invert mask button'); + invert.click(); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect + .poll(() => inStore(page, (state) => state.sculpt?.mask?.every((weight) => weight === 1))) + .toBe(true); + expect(await mesh(page)).toEqual(before); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From a443aaf04213828bca4246a1163ca808ecdcab75 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 10:26:56 -0800 Subject: [PATCH 31/40] (fix) Keep queued sculpt actions across tool switches --- src/components/SculptPointer.tsx | 55 ++++++++++++-------------------- src/core/store.ts | 32 ++++++++++++++++--- tests/e2e/sculpt.spec.ts | 49 ++++++++++++++++++++++++++-- 3 files changed, 94 insertions(+), 42 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index dad0b3c..ec19064 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -19,7 +19,12 @@ import { acceleratedRaycast } from 'three-mesh-bvh'; import { clearSculptIncidence, SculptMesh, type SculptDab } from '../core/sculpt-mesh'; import { triangleCount } from '../core/geometry'; import { workerIndexTriangles } from '../core/spatial-index'; -import { useEditor, useSculptStrokeFinisher } from '../core/store'; +import { + afterReleasedSculpt, + flushSculptActions, + setSculptCompletionGate, + useEditor, +} from '../core/store'; import type { Part, SculptureSettings } from '../core/types'; import { partMeshes } from '../xr/part-meshes'; import { SculptPath, type SculptSample as Sample } from '../core/sculpt-path'; @@ -142,8 +147,6 @@ export function SculptPointer() { let idleWeights: Float32Array | null = null; let stroke: Stroke | null = null; let disposed = false; - const afterStroke: (() => void)[] = []; - let runningAction = false; let queuedPointer: { down: PointerEvent; partId: string; @@ -455,7 +458,7 @@ export function SculptPointer() { ); active.work?.return(false); active.draft.geometry.dispose(); - flushActions(); + flushSculptActions(); prepare(); refresh(); }; @@ -525,27 +528,11 @@ export function SculptPointer() { } while ((active.work || active.path.pending) && performance.now() < until); if (active.released && !active.work && !active.path.pending) detach(true); }; - const defer = (action: () => void) => { - if (!stroke?.released && (runningAction || !afterStroke.length)) return false; - afterStroke.push(action); - return true; - }; - const flushActions = () => { - if (runningAction) return; - runningAction = true; - try { - while (afterStroke.length && !stroke?.released && !useEditor.getState().busy) - afterStroke.shift()!(); - } finally { - runningAction = false; - } - }; const schedule = () => { if (frame) return; frame = requestAnimationFrame(() => { frame = 0; if (stroke) drain(stroke, performance.now() + 6); - flushActions(); if (stroke && (stroke.work || stroke.path.pending)) schedule(); refresh(); }); @@ -557,7 +544,7 @@ export function SculptPointer() { /* The pointer may have ended before the queued press is replayed. */ } }; - const down = (event: PointerEvent, ended = false) => { + const down = (event: PointerEvent, ended = false, replayed = false) => { const state = useEditor.getState(); const sculpt = state.sculpt; if (stroke && !stroke.released) { @@ -579,20 +566,19 @@ export function SculptPointer() { event.metaKey ) return; - if (stroke?.released) { + if (queuedPointer && !replayed) return; + const gesture = { + down: event, + partId: sculpt.partId, + epoch: state.sceneEpoch, + moves: [], + cancelled: false, + }; + if (afterReleasedSculpt(() => replay(gesture))) { event.preventDefault(); event.stopImmediatePropagation(); - if (queuedPointer) return; - const gesture = { - down: event, - partId: sculpt.partId, - epoch: state.sceneEpoch, - moves: [], - cancelled: false, - }; queuedPointer = gesture; capture(event); - defer(() => replay(gesture)); return; } const target = state.scene.parts.find((part) => part.id === sculpt.partId); @@ -717,7 +703,6 @@ export function SculptPointer() { if (stroke) schedule(); }; const replay = (gesture: NonNullable) => { - if (defer(() => replay(gesture))) return; if (queuedPointer === gesture) queuedPointer = null; const state = useEditor.getState(); if ( @@ -727,7 +712,7 @@ export function SculptPointer() { state.sculpt?.partId !== gesture.partId ) return; - down(gesture.down, !!gesture.up); + down(gesture.down, !!gesture.up, true); for (const event of gesture.moves) move(event, true); if (gesture.up) release(gesture.up, true); }; @@ -781,7 +766,7 @@ export function SculptPointer() { schedule(); }); prepare(); - useSculptStrokeFinisher(defer); + setSculptCompletionGate(() => !!stroke?.released); canvas.addEventListener('pointerdown', down, true); canvas.addEventListener('lostpointercapture', cancel); canvas.addEventListener('pointerleave', leave); @@ -794,7 +779,7 @@ export function SculptPointer() { return () => { disposed = true; unsubscribe(); - useSculptStrokeFinisher(null); + setSculptCompletionGate(null); canvas.removeEventListener('pointerdown', down, true); canvas.removeEventListener('lostpointercapture', cancel); canvas.removeEventListener('pointerleave', leave); diff --git a/src/core/store.ts b/src/core/store.ts index 476cd1a..79b2955 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -5005,16 +5005,38 @@ useEditor.subscribe((state, previous) => { recordNotification(state.toast.message, state.toast.kind); }); -let finishSculptStroke: ((action: () => void) => boolean) | null = null; - -export function useSculptStrokeFinisher(finish: typeof finishSculptStroke) { - finishSculptStroke = finish; +// Editor commands can outlive the viewport tool that queued them. +let sculptIsFinishing: (() => boolean) | null = null; +const afterSculptActions: (() => void)[] = []; +let runningSculptAction = false; + +export function setSculptCompletionGate(gate: typeof sculptIsFinishing) { + sculptIsFinishing = gate; + if (!gate && afterSculptActions.length) queueMicrotask(flushSculptActions); } export function afterReleasedSculpt(action: () => void): boolean { - return finishSculptStroke?.(action) ?? false; + if (!sculptIsFinishing?.() && (runningSculptAction || !afterSculptActions.length)) return false; + afterSculptActions.push(action); + return true; +} + +export function flushSculptActions() { + if (runningSculptAction) return; + runningSculptAction = true; + try { + while (afterSculptActions.length && !sculptIsFinishing?.() && !useEditor.getState().busy) { + afterSculptActions.shift()!(); + } + } finally { + runningSculptAction = false; + } } +useEditor.subscribe((state, previous) => { + if (previous.busy && !state.busy && afterSculptActions.length) queueMicrotask(flushSculptActions); +}); + let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; export function useSharedSculptQueueGuard(guard: typeof sharedSculptQueueGuard) { diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 529e5be..9fd7e77 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -204,7 +204,7 @@ test('cancels a held queued press and preserves the released stroke through part ); } useEditor.getState().patchParts(['block'], { name: 'Renamed after release' }); - useEditor.getState().setView({ explode: true }); + useEditor.getState().setView({ explode: 50 }); } finally { performance.now = now; } @@ -218,7 +218,7 @@ test('cancels a held queued press and preserves the released stroke through part state.view.explode, ]), ) - .toEqual([1, false, 'Renamed after release', true]); + .toEqual([1, false, 'Renamed after release', 50]); }); test('restores the committed mesh when a replayed preview is cancelled', async ({ page }) => { @@ -354,6 +354,51 @@ test('keeps Undo ahead of a mask edit queued behind Save', async ({ page }) => { expect(await mesh(page)).toEqual(before); }); +test('preserves Undo behind Save after leaving Sculpt', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + useEditor.getState().setTool('select'); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect.poll(() => inStore(page, (state) => state.tool)).toBe('select'); + await expect.poll(() => mesh(page)).toEqual(before); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From 531066c24fdbde36d1605ca758e90d1d7766110a Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 11:17:26 -0800 Subject: [PATCH 32/40] (fix) Preserve queued sculpt cancellation and transform baselines --- src/components/SculptPointer.tsx | 4 +- src/core/store.ts | 1 + tests/e2e/sculpt.spec.ts | 97 ++++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 2 deletions(-) diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index ec19064..a756983 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -724,11 +724,11 @@ export function SculptPointer() { if (stroke?.id === event.pointerId && !stroke.released) detach(false); }; const escape = (event: KeyboardEvent) => { - if (event.key !== 'Escape' || !stroke) return; + if (event.key !== 'Escape' || (!stroke && !queuedPointer)) return; event.preventDefault(); event.stopImmediatePropagation(); if (queuedPointer) cancel(queuedPointer.down); - if (!stroke.released) detach(false); + if (stroke && !stroke.released) detach(false); }; const blur = () => { hover = null; diff --git a/src/core/store.ts b/src/core/store.ts index 79b2955..cfea59b 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -4551,6 +4551,7 @@ export const useEditor = create((set, get) => ({ }), ), beginFreeTransform: (mode) => { + if (afterReleasedSculpt(() => get().beginFreeTransform(mode))) return false; const state = get(); if (state.busy || state.modal || state.freeTransform) return false; const selection = transformSelection( diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 9fd7e77..10a845d 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -396,9 +396,106 @@ test('preserves Undo behind Save after leaving Sculpt', async ({ page }) => { }, point); await downloading; await expect.poll(() => inStore(page, (state) => state.tool)).toBe('select'); + await expect.poll(() => inStore(page, (state) => state.future.length)).toBe(1); await expect.poll(() => mesh(page)).toEqual(before); }); +test('cancels a held press queued behind a busy save after the released stroke detaches', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor, afterReleasedSculpt } = await import( + urls.find((url) => /\/src\/core\/store\.ts/.test(url))! + ); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + performance.now = () => (elapsed += 8); + try { + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 40, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', { ...pen, pointerId: 40 })); + afterReleasedSculpt(() => useEditor.getState().setBusy('Preparing scene file…')); + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 41, buttons: 1 })); + } finally { + performance.now = now; + } + }, point); + await expect + .poll(() => inStore(page, (state) => [state.busy, state.sculpt?.past.length])) + .toEqual(['Preparing scene file…', 1]); + await page.keyboard.press('Escape'); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor, afterReleasedSculpt } = await import( + urls.find((url) => /\/src\/core\/store\.ts/.test(url))! + ); + document.querySelector('canvas')!.dispatchEvent( + new PointerEvent('pointerup', { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 41, + isPrimary: true, + bubbles: true, + }), + ); + afterReleasedSculpt(() => + useEditor.getState().patchParts(['block'], { name: 'Queue settled' }), + ); + useEditor.getState().setBusy(null); + }, point); + await expect + .poll(() => inStore(page, (state) => [state.scene.parts[0].name, state.sculpt?.past.length])) + .toEqual(['Queue settled', 1]); +}); + +test('takes the free-transform baseline after a released stroke commits', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const canvas = document.querySelector('canvas')!; + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 40, + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + useEditor.getState().beginFreeTransform('translate'); + } finally { + performance.now = now; + } + }, point); + await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(true); + await expect.poll(async () => (await mesh(page)).triangles).toBeGreaterThan(before.triangles); + const sculpted = await mesh(page); + await page.keyboard.press('Escape'); + await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(false); + expect(await mesh(page)).toEqual(sculpted); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From 38bab614271fbb54395a1bb986394e639d1839d5 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 11:44:13 -0800 Subject: [PATCH 33/40] (fix) Keep queued sculpt actions out of free transform previews --- src/core/store.ts | 12 +++++- tests/e2e/sculpt.spec.ts | 93 +++++++++++++++++++++++++--------------- 2 files changed, 68 insertions(+), 37 deletions(-) diff --git a/src/core/store.ts b/src/core/store.ts index cfea59b..943a033 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -5011,6 +5011,9 @@ let sculptIsFinishing: (() => boolean) | null = null; const afterSculptActions: (() => void)[] = []; let runningSculptAction = false; +// A Free Transform preview owns its baseline until the user confirms or cancels it. +const blocksSculptActions = (state: EditorState) => !!(state.busy || state.freeTransform); + export function setSculptCompletionGate(gate: typeof sculptIsFinishing) { sculptIsFinishing = gate; if (!gate && afterSculptActions.length) queueMicrotask(flushSculptActions); @@ -5026,7 +5029,11 @@ export function flushSculptActions() { if (runningSculptAction) return; runningSculptAction = true; try { - while (afterSculptActions.length && !sculptIsFinishing?.() && !useEditor.getState().busy) { + while ( + afterSculptActions.length && + !sculptIsFinishing?.() && + !blocksSculptActions(useEditor.getState()) + ) { afterSculptActions.shift()!(); } } finally { @@ -5035,7 +5042,8 @@ export function flushSculptActions() { } useEditor.subscribe((state, previous) => { - if (previous.busy && !state.busy && afterSculptActions.length) queueMicrotask(flushSculptActions); + if (afterSculptActions.length && blocksSculptActions(previous) && !blocksSculptActions(state)) + queueMicrotask(flushSculptActions); }); let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 10a845d..6674fb6 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -460,41 +460,64 @@ test('cancels a held press queued behind a busy save after the released stroke d .toEqual(['Queue settled', 1]); }); -test('takes the free-transform baseline after a released stroke commits', async ({ page }) => { - await openSculpt(page); - const before = await mesh(page); - const point = await screen(page, [1, 0, 2]); - await page.evaluate(async (point) => { - const urls = performance.getEntriesByType('resource').map((entry) => entry.name); - const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); - const now = performance.now.bind(performance); - let elapsed = now(); - performance.now = () => (elapsed += 8); - try { - const canvas = document.querySelector('canvas')!; - const pen = { - clientX: point.x, - clientY: point.y, - pointerType: 'pen', - pointerId: 40, - isPrimary: true, - pressure: 0.8, - bubbles: true, - }; - canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); - canvas.dispatchEvent(new PointerEvent('pointerup', pen)); - useEditor.getState().beginFreeTransform('translate'); - } finally { - performance.now = now; - } - }, point); - await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(true); - await expect.poll(async () => (await mesh(page)).triangles).toBeGreaterThan(before.triangles); - const sculpted = await mesh(page); - await page.keyboard.press('Escape'); - await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(false); - expect(await mesh(page)).toEqual(sculpted); -}); +for (const queueUndo of [false, true]) { + test( + queueUndo + ? 'runs Undo after Free Transform closes when both follow a released stroke' + : 'takes the free-transform baseline after a released stroke commits', + async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate( + ({ point, queueUndo }) => { + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const canvas = document.querySelector('canvas')!; + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 40, + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + window.dispatchEvent( + new KeyboardEvent('keydown', { key: 'G', code: 'KeyG', shiftKey: true }), + ); + if (queueUndo) + window.dispatchEvent( + new KeyboardEvent('keydown', { key: 'z', code: 'KeyZ', ctrlKey: true }), + ); + } finally { + performance.now = now; + } + }, + { point, queueUndo }, + ); + await expect(page.locator('.free-transform-prompt')).toBeVisible(); + const sculpted = await mesh(page); + expect(sculpted.triangles).toBeGreaterThan(before.triangles); + await page.keyboard.press('Escape'); + await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(false); + if (queueUndo) { + await expect.poll(() => mesh(page)).toEqual(before); + expect(await inStore(page, (state) => [state.past.length, state.future.length])).toEqual([ + 0, 1, + ]); + await page.keyboard.press('ControlOrMeta+Shift+Z'); + await expect.poll(() => mesh(page)).toEqual(sculpted); + } else { + expect(await mesh(page)).toEqual(sculpted); + } + }, + ); +} test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { From b504093715b78a07f61fba98a1c9acc883c3bb63 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 12:02:06 -0800 Subject: [PATCH 34/40] (fix) Invalidate stale sculpt commands and transform previews --- src/components/FreeTransform.tsx | 17 +++-- src/components/SculptPointer.tsx | 7 +- src/core/commands.ts | 12 ++- src/core/live.ts | 11 ++- src/core/store.ts | 29 +++++--- tests/e2e/helpers/sculpt.ts | 37 ++++++++++ tests/e2e/mcp.spec.ts | 76 +++++++++++++++++++ tests/e2e/sculpt.spec.ts | 122 +++++++++++++++++++++++-------- 8 files changed, 257 insertions(+), 54 deletions(-) create mode 100644 tests/e2e/helpers/sculpt.ts diff --git a/src/components/FreeTransform.tsx b/src/components/FreeTransform.tsx index 0d7fb0f..4ac4eaf 100644 --- a/src/components/FreeTransform.tsx +++ b/src/components/FreeTransform.tsx @@ -10,7 +10,7 @@ import { useEditor } from '../core/store'; /** Own the entire confirm click so it never also selects a part or starts camera orbit. */ export function FreeTransformController() { const { camera, gl, invalidate } = useThree(); - const baseline = useEditor((s) => s.freeTransform?.baseline); + const sessionId = useEditor((s) => s.freeTransform?.id); const pointer = useRef<{ x: number; y: number } | null>(null); const suppress = useRef(null); const update = useRef<((event?: PointerEvent) => void) | null>(null); @@ -65,7 +65,7 @@ export function FreeTransformController() { useEffect(() => { const start = useEditor.getState(); const session = start.freeTransform; - if (!session || !baseline) return; + if (!sessionId || session?.id !== sessionId) return; const selection = transformSelection(start, session.mode); const rect = gl.domElement.getBoundingClientRect(); const motion = new FreeTransformMotion(camera, selection.pivot, rect.width, rect.height); @@ -81,7 +81,7 @@ export function FreeTransformController() { const apply = () => { const state = useEditor.getState(), current = state.freeTransform; - if (current?.baseline !== baseline) return; + if (current?.id !== sessionId) return; const step = session.mode === 'translate' ? state.view.snapStep : state.view.rotationSnapStep; state.previewFreeTransform( motion.patches( @@ -108,7 +108,7 @@ export function FreeTransformController() { if (event.isComposing) return; const state = useEditor.getState(), current = state.freeTransform; - if (current?.baseline !== baseline) return; + if (current?.id !== sessionId) return; event.preventDefault(); event.stopImmediatePropagation(); if (event.key === 'Shift') { @@ -138,7 +138,10 @@ export function FreeTransformController() { const up = (event: KeyboardEvent) => { if (event.key === 'Shift') fine = false; }; - const cancel = () => useEditor.getState().finishFreeTransform(false); + const cancel = () => { + const state = useEditor.getState(); + if (state.freeTransform?.id === sessionId) state.finishFreeTransform(false); + }; const visibility = () => { if (document.hidden) cancel(); }; @@ -156,10 +159,10 @@ export function FreeTransformController() { window.removeEventListener('pointercancel', cancel); window.removeEventListener('resize', cancel); document.removeEventListener('visibilitychange', visibility); - if (useEditor.getState().freeTransform?.baseline === baseline) cancel(); + cancel(); invalidate(); }; - }, [baseline, camera, gl.domElement, invalidate]); + }, [sessionId, camera, gl.domElement, invalidate]); return null; } diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index a756983..35ff4c9 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -21,6 +21,7 @@ import { triangleCount } from '../core/geometry'; import { workerIndexTriangles } from '../core/spatial-index'; import { afterReleasedSculpt, + cancelQueuedSculptActions, flushSculptActions, setSculptCompletionGate, useEditor, @@ -425,6 +426,7 @@ export function SculptPointer() { } overlay.visible = false; if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; + let refused = !accept && active.released; if (accept && active.changed) { const geometry = active.draft.finish(); const grew = @@ -446,8 +448,10 @@ export function SculptPointer() { geometry, mask: mask?.some((value) => value > 0) ? mask : null, }) - ) + ) { geometry?.dispose(); + refused = true; + } } if (accept && active.draft.detailLimited) useEditor @@ -458,6 +462,7 @@ export function SculptPointer() { ); active.work?.return(false); active.draft.geometry.dispose(); + if (refused) cancelQueuedSculptActions('history'); flushSculptActions(); prepare(); refresh(); diff --git a/src/core/commands.ts b/src/core/commands.ts index 31b1fdd..14a7ad4 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -28,7 +28,10 @@ function waitForReleasedSculpt(run: () => Promise) { resolveSave = resolve; rejectSave = reject; }); - if (afterReleasedSculpt(() => void run().then(resolveSave, rejectSave))) return saved; + if ( + afterReleasedSculpt(() => void run().then(resolveSave, rejectSave), { onCancel: resolveSave }) + ) + return saved; } export async function saveCurrentScene() { @@ -344,7 +347,12 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { - if (afterReleasedSculpt(() => executeEditorCommand(id, context))) return; + if ( + afterReleasedSculpt(() => executeEditorCommand(id, context), { + history: id === 'undo' || id === 'redo', + }) + ) + return; const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/live.ts b/src/core/live.ts index a3fb563..99cf18c 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -3,6 +3,7 @@ import { uid } from './geometry'; import { geometryBytes } from './history-budget'; import { appendGeometry, parseSceneDocument, readGeometry, validateLayout } from './scene-file'; import { + cancelQueuedSculptActions, committedScene, liveHost, restoreSculptAfterRefusal, @@ -241,9 +242,12 @@ export function joinLiveSession() { if (!replacing && (first || replaced)) { dirtyEdit = null; edits.length = 0; - // A released stroke still draining belongs to the previous scene. - if (replaced && useEditor.getState().sculpt) - useEditor.setState({ tool: 'select', sculpt: null }); + if (replaced) { + // Pending history and editor actions belong to the previous scene. + requests.length = 0; + cancelQueuedSculptActions(); + if (useEditor.getState().sculpt) useEditor.setState({ tool: 'select', sculpt: null }); + } } else { const optimistic = acceptedSculpt?.edit ?? (activeSculptObserved ? null : activeEdit); const pending = optimistic ? [optimistic, ...unsent] : unsent; @@ -313,6 +317,7 @@ export function joinLiveSession() { const { sculpt } = useEditor.getState(); // Queued history requests refer to the discarded optimistic scene. requests.length = 0; + cancelQueuedSculptActions('history'); stopSharedSculptHistory(true); edits.length = 0; dirtyEdit = null; diff --git a/src/core/store.ts b/src/core/store.ts index 943a033..b550bd3 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -249,6 +249,7 @@ const historyLimit = 40; const gestureBudget = 12; interface FreeTransform { + id: string; mode: FreeTransformMode; axis: TransformAxis; baseline: SceneDocument; @@ -4569,7 +4570,7 @@ export const useEditor = create((set, get) => ({ : undefined; if (!warp) state.setTool(mode); set({ - freeTransform: { mode, axis: null, baseline: get().scene, patches: [], warp }, + freeTransform: { id: uid(), mode, axis: null, baseline: get().scene, patches: [], warp }, contextMenu: null, temporaryOrbit: false, }); @@ -4614,7 +4615,7 @@ export const useEditor = create((set, get) => ({ true, ); set((state) => { - if (state.freeTransform?.baseline !== session.baseline) return {}; + if (state.freeTransform?.id !== session.id) return {}; const differs = state.scene.parts.some((part, i) => { const before = session.baseline.parts[i]; return ( @@ -4967,10 +4968,10 @@ export const useEditor = create((set, get) => ({ return next === state.scene.name ? {} : changed(state, { ...state.scene, name: next }); }), undo: () => { - if (!afterReleasedSculpt(() => get().undo())) moveHistory('undo'); + if (!afterReleasedSculpt(() => get().undo(), { history: true })) moveHistory('undo'); }, redo: () => { - if (!afterReleasedSculpt(() => get().redo())) moveHistory('redo'); + if (!afterReleasedSculpt(() => get().redo(), { history: true })) moveHistory('redo'); }, setView: (patch) => { if (patch.explode !== undefined && afterReleasedSculpt(() => get().setView(patch))) return; @@ -5008,7 +5009,8 @@ useEditor.subscribe((state, previous) => { // Editor commands can outlive the viewport tool that queued them. let sculptIsFinishing: (() => boolean) | null = null; -const afterSculptActions: (() => void)[] = []; +type SculptActionOptions = { history?: boolean; onCancel?: () => void }; +const afterSculptActions: (SculptActionOptions & { run: () => void })[] = []; let runningSculptAction = false; // A Free Transform preview owns its baseline until the user confirms or cancels it. @@ -5019,12 +5021,19 @@ export function setSculptCompletionGate(gate: typeof sculptIsFinishing) { if (!gate && afterSculptActions.length) queueMicrotask(flushSculptActions); } -export function afterReleasedSculpt(action: () => void): boolean { +export function afterReleasedSculpt(run: () => void, options: SculptActionOptions = {}): boolean { if (!sculptIsFinishing?.() && (runningSculptAction || !afterSculptActions.length)) return false; - afterSculptActions.push(action); + afterSculptActions.push({ run, ...options }); return true; } +export function cancelQueuedSculptActions(scope: 'all' | 'history' = 'all') { + for (const action of afterSculptActions.splice(0)) { + if (scope === 'history' && !action.history) afterSculptActions.push(action); + else action.onCancel?.(); + } +} + export function flushSculptActions() { if (runningSculptAction) return; runningSculptAction = true; @@ -5034,7 +5043,7 @@ export function flushSculptActions() { !sculptIsFinishing?.() && !blocksSculptActions(useEditor.getState()) ) { - afterSculptActions.shift()!(); + afterSculptActions.shift()!.run(); } } finally { runningSculptAction = false; @@ -5042,7 +5051,9 @@ export function flushSculptActions() { } useEditor.subscribe((state, previous) => { - if (afterSculptActions.length && blocksSculptActions(previous) && !blocksSculptActions(state)) + if (!afterSculptActions.length) return; + if (state.sceneEpoch !== previous.sceneEpoch) cancelQueuedSculptActions(); + else if (blocksSculptActions(previous) && !blocksSculptActions(state)) queueMicrotask(flushSculptActions); }); diff --git a/tests/e2e/helpers/sculpt.ts b/tests/e2e/helpers/sculpt.ts new file mode 100644 index 0000000..cbb8864 --- /dev/null +++ b/tests/e2e/helpers/sculpt.ts @@ -0,0 +1,37 @@ +import type { Page } from '@playwright/test'; + +type Shortcut = Pick; + +/** Dispatch shortcuts in the same task as a pen lift, with stroke work left for the next frame. */ +export async function queueAfterPenRelease( + page: Page, + point: { x: number; y: number }, + shortcuts: Shortcut[], +) { + await page.evaluate( + ({ point, shortcuts }) => { + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const canvas = document.querySelector('canvas')!; + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 40, + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + for (const shortcut of shortcuts) + window.dispatchEvent(new KeyboardEvent('keydown', shortcut)); + } finally { + performance.now = now; + } + }, + { point, shortcuts }, + ); +} diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 6e152b4..a54c802 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -9,6 +9,7 @@ import { expect, test } from '@playwright/test'; import type { Page } from '@playwright/test'; import { BoxGeometry, Mesh } from 'three'; import { STLExporter } from 'three/addons/exporters/STLExporter.js'; +import { queueAfterPenRelease } from './helpers/sculpt'; // These drive the bundle a client would really start, over real stdio, with the real app. let folder: string; @@ -467,6 +468,81 @@ test('refusing an ordinary shared edit discards its queued undo', async ({ page expect(undoRequests).toEqual([]); }); +for (const replaceScene of [false, true]) { + test( + replaceScene + ? 'discards commands from a queued preview when the shared scene is replaced' + : 'discards the queued Undo when a shared stroke refusal closes a preview', + async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + const originalName = 'Untitled assembly'; + await expect(title).toHaveText(originalName); + const acceptedName = 'Accepted assembly name'; + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(acceptedName); + await field.press('Enter'); + await expect(page.getByRole('button', { name: /^Undo \((⌘|Ctrl)\+Z\)$/ })).toBeEnabled(); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const canvas = (await page.locator('canvas').boundingBox())!; + const point = { x: canvas.x + canvas.width / 2 + 8, y: canvas.y + canvas.height / 2 - 7 }; + + let rejectStroke = () => {}; + const held = new Promise((resolve) => { + rejectStroke = resolve; + }); + const edit = /\/live\/edit$/; + await page.route(edit, async (route) => { + await held; + await route.fulfill({ status: 409, json: { error: 'Stroke refused for this test.' } }); + }); + let undoRequests = 0; + page.on('request', (request) => { + if (request.url().endsWith('/live/undo')) undoRequests++; + }); + const submitted = page.waitForRequest(edit); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'z', code: 'KeyZ', ctrlKey: true }, + { key: 'F1', code: 'F1' }, + ]); + expect((await submitted).postDataJSON().sculpt).toBeTruthy(); + const prompt = page.locator('.free-transform-prompt'); + const help = page.getByRole('dialog', { name: 'A workbench that gets out of your way.' }); + await expect(prompt).toBeVisible(); + if (replaceScene) { + await call('new_scene', { name: 'Replacement', discard_unsaved: true }); + await expect(title).toHaveText('Replacement'); + await expect(prompt).toHaveCount(0); + } + rejectStroke(); + await expect(page.getByText(/stroke refused for this test/i)).toBeVisible(); + await expect(prompt).toHaveCount(0); + if (replaceScene) { + await expect(help).toHaveCount(0); + expect(undoRequests).toBe(0); + } else { + // A later non-history command still runs after the refused stroke rolls back. + await expect(help).toBeVisible(); + await expect(title).toHaveText(acceptedName); + expect(undoRequests).toBe(0); + await help.getByRole('button', { name: 'Close dialog', exact: true }).click(); + await page.keyboard.press('ControlOrMeta+z'); + await expect(title).toHaveText(originalName); + expect(undoRequests).toBe(1); + } + }, + ); +} + test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ page, }) => { diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts index 6674fb6..3744d77 100644 --- a/tests/e2e/sculpt.spec.ts +++ b/tests/e2e/sculpt.spec.ts @@ -1,7 +1,8 @@ import { expect, test, type Page } from '@playwright/test'; import { BoxGeometry, PlaneGeometry } from 'three'; import { serializeGeometry } from '../../src/core/geometry'; -import { fixture, inStore, openScene, screen } from './helpers/refine'; +import { fixture, inEditor, inStore, openScene, screen } from './helpers/refine'; +import { queueAfterPenRelease } from './helpers/sculpt'; import { failOnBrowserErrors } from './helpers/warp-grid'; import { readSavedScene } from './saved-scene'; @@ -469,37 +470,10 @@ for (const queueUndo of [false, true]) { await openSculpt(page); const before = await mesh(page); const point = await screen(page, [1, 0, 2]); - await page.evaluate( - ({ point, queueUndo }) => { - const now = performance.now.bind(performance); - let elapsed = now(); - performance.now = () => (elapsed += 8); - try { - const canvas = document.querySelector('canvas')!; - const pen = { - clientX: point.x, - clientY: point.y, - pointerType: 'pen', - pointerId: 40, - isPrimary: true, - pressure: 0.8, - bubbles: true, - }; - canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); - canvas.dispatchEvent(new PointerEvent('pointerup', pen)); - window.dispatchEvent( - new KeyboardEvent('keydown', { key: 'G', code: 'KeyG', shiftKey: true }), - ); - if (queueUndo) - window.dispatchEvent( - new KeyboardEvent('keydown', { key: 'z', code: 'KeyZ', ctrlKey: true }), - ); - } finally { - performance.now = now; - } - }, - { point, queueUndo }, - ); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + ...(queueUndo ? [{ key: 'z', code: 'KeyZ', ctrlKey: true }] : []), + ]); await expect(page.locator('.free-transform-prompt')).toBeVisible(); const sculpted = await mesh(page); expect(sculpted.triangles).toBeGreaterThan(before.triangles); @@ -519,6 +493,90 @@ for (const queueUndo of [false, true]) { ); } +test('starts a fresh rotation preview after cancelling a queued move on the same mesh', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + const pose = () => + inStore(page, (state) => { + const { position, quaternion } = state.scene.parts[0]; + return { position, quaternion }; + }); + const before = await pose(); + const prompt = page.locator('.free-transform-prompt'); + await page.mouse.move(point.x, point.y); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'R', code: 'KeyR', shiftKey: true }, + ]); + await expect(prompt).toContainText('Free move'); + await page.mouse.move(point.x + 40, point.y + 15); + await expect.poll(pose).not.toEqual(before); + await page.keyboard.press('Escape'); + await expect(prompt).toContainText('Free rotation'); + expect(await pose()).toEqual(before); + await page.mouse.move(point.x + 65, point.y + 30); + await expect.poll(async () => (await pose()).quaternion).not.toEqual(before.quaternion); + await page.keyboard.press('Escape'); + await expect(prompt).toHaveCount(0); + expect(await pose()).toEqual(before); +}); + +test('discards queued commands when a new scene replaces a free-transform preview', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'E', code: 'KeyE', shiftKey: true, ctrlKey: true }, + ]); + const prompt = page.locator('.free-transform-prompt'); + await expect(prompt).toBeVisible(); + await inEditor(page, ({ useEditor }) => { + const state = useEditor.getState(); + state.setScene({ ...state.scene, name: 'Replacement' }); + }); + await expect(prompt).toHaveCount(0); + expect(await inStore(page, (state) => [state.scene.name, state.modal])).toEqual([ + 'Replacement', + null, + ]); +}); + +test('discards queued Undo if a scene update interrupts the released stroke before commit', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await inEditor(page, ({ useEditor }) => { + useEditor.getState().renameScene('Earlier edit'); + const interrupt = (event: KeyboardEvent) => { + if (event.code !== 'Pause') return; + window.removeEventListener('keydown', interrupt); + const state = useEditor.getState(); + state.receiveScene({ + ...state.scene, + parts: [{ ...state.scene.parts[0], position: [2, 0, 0] }], + }); + }; + window.addEventListener('keydown', interrupt); + }); + await queueAfterPenRelease(page, point, [ + { key: 'z', code: 'KeyZ', ctrlKey: true }, + { key: 'Pause', code: 'Pause' }, + ]); + expect( + await inStore(page, (state) => [ + state.scene.name, + state.scene.parts[0].position, + state.past.length, + state.future.length, + ]), + ).toEqual(['Earlier edit', [2, 0, 0], 1, 0]); +}); + test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { await openSculpt(page, { ...block, From 15f408585ef794aa7e916d6c79a0c1cfb1fa3de9 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 12:19:27 -0800 Subject: [PATCH 35/40] (fix) Keep shared sculpt edits bound to their scene --- mcp/document.ts | 9 +- mcp/live.ts | 7 +- src/components/SculptPointer.tsx | 7 +- src/core/live.ts | 114 +++++++++++++---- tests/e2e/helpers/sculpt.ts | 17 ++- tests/e2e/mcp.spec.ts | 205 +++++++++++++++++++++++++++++-- 6 files changed, 317 insertions(+), 42 deletions(-) diff --git a/mcp/document.ts b/mcp/document.ts index 12af4d0..73c81be 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -27,6 +27,7 @@ export interface Edit { checkpoint: boolean; /** Starts the scene over, as opening a file does. */ replace?: boolean; + replacementId?: string; sculpt?: SculptTarget; } @@ -55,6 +56,8 @@ export class SharedDocument { version = 0; /** Counts scene replacements. Edits made before one no longer apply. */ epoch = 0; + /** Identifies the browser edit that started this epoch, if any. */ + replacementId?: string; private readonly versions = new Map(); private readonly log = new Map(); private readonly histories = new Map(); @@ -76,10 +79,11 @@ export class SharedDocument { } /** Starts over from a scene that nobody can undo, such as a file just opened. */ - replace(scene: SceneDocument, author = agent, saved = true) { + replace(scene: SceneDocument, author = agent, saved = true, replacementId?: string) { useEditor.getState().setScene(scene); if (!saved) useEditor.setState({ savedRevision: -1 }); this.epoch++; + this.replacementId = replacementId; this.versions.clear(); this.log.clear(); this.histories.clear(); @@ -97,7 +101,8 @@ export class SharedDocument { apply(author: string, edit: Edit) { if (edit.replace) { - this.replace(edit.scene, author, false); + if (edit.replacementId && this.replacementId === edit.replacementId) return this.version; + this.replace(edit.scene, author, false, edit.replacementId); return this.version; } if (edit.epoch !== this.epoch) diff --git a/mcp/live.ts b/mcp/live.ts index 9efe9ef..c83a25c 100644 --- a/mcp/live.ts +++ b/mcp/live.ts @@ -302,7 +302,7 @@ export class LiveView { } private message() { - const { scene, version, epoch } = this.document; + const { scene, version, epoch, replacementId } = this.document; const geometries: Record = {}; for (const { geometry } of scene.parts) { let layout = this.layouts.get(geometry); @@ -315,6 +315,7 @@ export class LiveView { return `event: scene\ndata: ${JSON.stringify({ version, epoch, + replacementId, scene: sharedScene(scene), geometries, history: this.document.historyCounts(), @@ -426,6 +427,10 @@ export class LiveView { scene, checkpoint: body.checkpoint !== false, replace: body.replace === true, + replacementId: + typeof body.replacementId === 'string' && /^[\w-]{1,64}$/.test(body.replacementId) + ? body.replacementId + : undefined, sculpt: body.sculpt, }); this.reply(response, 200, { version }); diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx index 35ff4c9..acf2a9b 100644 --- a/src/components/SculptPointer.tsx +++ b/src/components/SculptPointer.tsx @@ -462,8 +462,11 @@ export function SculptPointer() { ); active.work?.return(false); active.draft.geometry.dispose(); - if (refused) cancelQueuedSculptActions('history'); - flushSculptActions(); + if (refused) { + cancelQueuedSculptActions('history'); + // A shared update can interrupt this stroke from inside the store's subscribers. + queueMicrotask(flushSculptActions); + } else flushSculptActions(); prepare(); refresh(); }; diff --git a/src/core/live.ts b/src/core/live.ts index 99cf18c..bb2819a 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -21,7 +21,7 @@ interface OrdinaryEdit { before: SceneDocument; scene: SceneDocument; checkpoint: boolean; - replace: boolean; + replacementId?: string; } interface SculptEdit { @@ -31,6 +31,15 @@ interface SculptEdit { type QueuedEdit = OrdinaryEdit | SculptEdit; +interface ActiveEdit { + edit: QueuedEdit; + epoch: number; + sceneEpoch: number; +} + +const replacementIdOf = (edit: QueuedEdit | null | undefined) => + edit && !('sculpt' in edit) ? edit.replacementId : undefined; + interface HistoryRequest { direction: 'undo' | 'redo'; sculpt: number | null; @@ -38,7 +47,7 @@ interface HistoryRequest { function applyQueuedEdit(scene: SceneDocument, edit: QueuedEdit): SceneDocument { if (!('sculpt' in edit)) - return edit.replace ? edit.scene : mergeScenes(edit.before, edit.scene, scene); + return edit.replacementId ? edit.scene : mergeScenes(edit.before, edit.scene, scene); const { sculpt, geometry } = edit; return { ...scene, @@ -53,6 +62,7 @@ function applyQueuedEdit(scene: SceneDocument, edit: QueuedEdit): SceneDocument interface Message { version: number; epoch: number; + replacementId?: string; scene: unknown; geometries: Record; history: Record; @@ -104,7 +114,12 @@ export function joinLiveSession() { const edits: QueuedEdit[] = []; const requests: HistoryRequest[] = []; /** The last scene the server sent. Unsent changes here are relative to it. */ - let confirmed: { version: number; epoch: number; scene: SceneDocument } | null = null; + let confirmed: { + version: number; + epoch: number; + replacementId?: string; + scene: SceneDocument; + } | null = null; let latest: Message | null = null; let streamGeneration = 0; let receiving = false; @@ -114,9 +129,10 @@ export function joinLiveSession() { let closed = false; let viewMoved = false; let dirtyEdit: OrdinaryEdit | null = null; - let activeEdit: QueuedEdit | null = null; + let activeEdit: ActiveEdit | null = null; let activeSculptObserved = false; let acceptedSculpt: { edit: SculptEdit; version: number; epoch: number } | null = null; + let acceptedReplacement: { edit: OrdinaryEdit; version: number } | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; let awaitedHistory: { version: number; sculpt: number | null } | null = null; @@ -124,10 +140,14 @@ export function joinLiveSession() { const notify = (message: string, kind: 'error' | 'info' = 'error') => useEditor.getState().notify(message, kind); - const show = (scene: SceneDocument) => { + const show = (scene: SceneDocument, replace = false) => { + const state = useEditor.getState(); + const local = committedScene(state); + const next = keepUnchanged(local, scene); + if (!replace && next === local) return; applyingRemote = true; try { - useEditor.getState().receiveScene(keepUnchanged(useEditor.getState().scene, scene)); + state.receiveScene(replace && next === state.scene ? { ...next } : next); } finally { applyingRemote = false; } @@ -137,7 +157,7 @@ export function joinLiveSession() { useSharedSculptQueueGuard((geometry) => { if (!connected) return false; - const queued = [activeEdit, acceptedSculpt?.edit, ...edits].flatMap((edit) => + const queued = [activeEdit?.edit, acceptedSculpt?.edit, ...edits].flatMap((edit) => edit && 'sculpt' in edit ? [edit.geometry] : [], ); return queued.length < 40 && geometryBytes([...queued, geometry]) <= sculptHistoryBytes; @@ -178,7 +198,10 @@ export function joinLiveSession() { const replace = state.sceneEpoch !== previous.sceneEpoch; if (replace) { edits.length = 0; + requests.length = 0; dirtyEdit = null; + acceptedSculpt = null; + acceptedReplacement = null; } // Accumulate only ordinary edits, each relative to what this action actually changed. // In particular, an optimistic sculpt mesh in both scenes must not enter this batch. @@ -189,7 +212,7 @@ export function joinLiveSession() { ? mergeScenes(before, scene, dirtyEdit.scene) : scene, checkpoint: replace || !!dirtyEdit?.checkpoint || state.past !== previous.past, - replace: replace || !!dirtyEdit?.replace, + replacementId: replace ? uid() : dirtyEdit?.replacementId, }; } void pump(); @@ -218,12 +241,29 @@ export function joinLiveSession() { return geometry; }); for (const key of Object.keys(message.geometries)) known.add(key); - const local = committedScene(useEditor.getState()); + const state = useEditor.getState(); + const local = committedScene(state); const first = !confirmed; const replaced = !!confirmed && message.epoch !== confirmed.epoch; + const active = + activeEdit && + activeEdit.sceneEpoch === state.sceneEpoch && + activeEdit.epoch === confirmed?.epoch + ? activeEdit.edit + : null; + const acknowledgesReplacement = (edit: QueuedEdit | null | undefined) => + !!message.replacementId && replacementIdOf(edit) === message.replacementId; + const acknowledgedRetry = edits.findIndex(acknowledgesReplacement); + if (acknowledgedRetry >= 0) edits.splice(acknowledgedRetry, 1); + const ownReplacement = + acknowledgesReplacement(active) || + acknowledgesReplacement(acceptedReplacement?.edit) || + acknowledgedRetry >= 0; + if (acceptedReplacement && message.version >= acceptedReplacement.version) + acceptedReplacement = null; const unsent = unsentEdits(); - if (activeEdit && 'sculpt' in activeEdit) { - const { sculpt, geometry } = activeEdit; + if (!replaced && active && 'sculpt' in active) { + const { sculpt, geometry } = active; if ( scene.parts.some( (part) => part.id === sculpt.partId && part.geometry.uuid === geometry.uuid, @@ -236,10 +276,11 @@ export function joinLiveSession() { (message.epoch !== acceptedSculpt.epoch || message.version >= acceptedSculpt.version) ) acceptedSculpt = null; - const replacing = unsent.some((edit) => !('sculpt' in edit) && edit.replace); + const replacing = !!acceptedReplacement || unsent.some(replacementIdOf); + const changedScene = !replacing && (first || (replaced && !ownReplacement)); let next = scene; // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. - if (!replacing && (first || replaced)) { + if (changedScene) { dirtyEdit = null; edits.length = 0; if (replaced) { @@ -249,11 +290,19 @@ export function joinLiveSession() { if (useEditor.getState().sculpt) useEditor.setState({ tool: 'select', sculpt: null }); } } else { - const optimistic = acceptedSculpt?.edit ?? (activeSculptObserved ? null : activeEdit); + const optimistic = + acceptedSculpt?.edit ?? + acceptedReplacement?.edit ?? + (replaced || activeSculptObserved ? null : active); const pending = optimistic ? [optimistic, ...unsent] : unsent; next = pending.reduce(applyQueuedEdit, scene); } - confirmed = { version: message.version, epoch: message.epoch, scene }; + confirmed = { + version: message.version, + epoch: message.epoch, + replacementId: message.replacementId, + scene, + }; const [undo, redo] = message.history[client] ?? [0, 0]; if (!connected) { connected = true; @@ -261,12 +310,12 @@ export function joinLiveSession() { } useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); const before = new Set(local.parts.map((part) => part.id)); - show(next); + show(next, changedScene && replaced); if (awaitedHistory && message.version >= awaitedHistory.version) { stopSharedSculptHistory(true, awaitedHistory.sculpt); awaitedHistory = null; } - if (!replacing && (first || replaced)) useEditor.getState().settleWarp(true); + if (changedScene) useEditor.getState().settleWarp(true); const shown = useEditor.getState().scene; if (first) useEditor.getState().markSaved(useEditor.getState().revision); // Keep a growing model in view, until the person watching takes over the camera. @@ -346,11 +395,18 @@ export function joinLiveSession() { const base = confirmed!; const sculpt = 'sculpt' in edit ? edit.sculpt : undefined; const checkpoint = 'sculpt' in edit || edit.checkpoint; - const replace = !('sculpt' in edit) && edit.replace; - activeEdit = edit; + const replacementId = replacementIdOf(edit); + const sceneEpoch = useEditor.getState().sceneEpoch; + const replacementObserved = () => !!replacementId && confirmed?.replacementId === replacementId; + const stillApplies = () => + !closed && + useEditor.getState().sceneEpoch === sceneEpoch && + (confirmed?.epoch === base.epoch || replacementObserved()); + activeEdit = { edit, epoch: base.epoch, sceneEpoch }; activeSculptObserved = false; if (!sculpt) useEditor.getState().submitWarp(); try { + if (replacementObserved()) return; if ('sculpt' in edit) { const target = base.scene.parts.find((part) => part.id === edit.sculpt.partId); // A request can succeed even when the connection drops before its response arrives. @@ -368,26 +424,36 @@ export function joinLiveSession() { known.add(key); meshes.set(key, geometry); } + if (!stillApplies()) return; const response = await post('live/edit', { client, base: base.version, epoch: base.epoch, checkpoint, - replace, + replace: !!replacementId, + replacementId, sculpt, scene: sharedScene(scene), }); if (response.ok) { awaited = ((await response.json()) as { version: number }).version; - if (!sculpt) useEditor.getState().settleWarp(true, true); - else if (!closed && confirmed && confirmed.version >= awaited) { + if (!stillApplies()) return; + if (!('sculpt' in edit)) { + if (replacementId && confirmed && confirmed.version < awaited) + acceptedReplacement = { edit, version: awaited }; + useEditor.getState().settleWarp(true, true); + } else if (confirmed && confirmed.version >= awaited) { // The stream can skip the accepted mesh or show it before the HTTP response arrives. show(unsentEdits().reduce(applyQueuedEdit, confirmed.scene)); - } else if ('sculpt' in edit && !activeSculptObserved && confirmed?.epoch === base.epoch) { + } else if (!activeSculptObserved && confirmed?.epoch === base.epoch) { acceptedSculpt = { edit, version: awaited, epoch: base.epoch }; } - } else refused(await errorOf(response)); + } else { + const reason = await errorOf(response); + if (stillApplies()) refused(reason); + } } catch (error) { + if (!stillApplies() || replacementObserved()) return; if (error instanceof Refusal) refused(error.message); else { // Retry an interrupted request unless the stream already confirmed the stroke. diff --git a/tests/e2e/helpers/sculpt.ts b/tests/e2e/helpers/sculpt.ts index cbb8864..265e99b 100644 --- a/tests/e2e/helpers/sculpt.ts +++ b/tests/e2e/helpers/sculpt.ts @@ -7,9 +7,10 @@ export async function queueAfterPenRelease( page: Page, point: { x: number; y: number }, shortcuts: Shortcut[], + options: { end?: { x: number; y: number }; releaseClockOn?: string } = {}, ) { await page.evaluate( - ({ point, shortcuts }) => { + ({ point, shortcuts, options }) => { const now = performance.now.bind(performance); let elapsed = now(); performance.now = () => (elapsed += 8); @@ -25,13 +26,21 @@ export async function queueAfterPenRelease( bubbles: true, }; canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); - canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + const end = options.end ? { ...pen, clientX: options.end.x, clientY: options.end.y } : pen; + if (options.end) + canvas.dispatchEvent(new PointerEvent('pointermove', { ...end, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', end)); for (const shortcut of shortcuts) window.dispatchEvent(new KeyboardEvent('keydown', shortcut)); } finally { - performance.now = now; + const restore = () => { + performance.now = now; + }; + if (options.releaseClockOn) + window.addEventListener(options.releaseClockOn, restore, { once: true }); + else restore(); } }, - { point, shortcuts }, + { point, shortcuts, options }, ); } diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index a54c802..3abc54c 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -9,7 +9,9 @@ import { expect, test } from '@playwright/test'; import type { Page } from '@playwright/test'; import { BoxGeometry, Mesh } from 'three'; import { STLExporter } from 'three/addons/exporters/STLExporter.js'; +import { serializeGeometry } from '../../src/core/geometry'; import { queueAfterPenRelease } from './helpers/sculpt'; +import { readSavedScene } from './saved-scene'; // These drive the bundle a client would really start, over real stdio, with the real app. let folder: string; @@ -483,10 +485,13 @@ for (const replaceScene of [false, true]) { const originalName = 'Untitled assembly'; await expect(title).toHaveText(originalName); const acceptedName = 'Accepted assembly name'; - await title.click(); - const field = page.getByRole('textbox', { name: 'Assembly name' }); - await field.fill(acceptedName); - await field.press('Enter'); + const rename = async (name: string) => { + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + await rename(acceptedName); await expect(page.getByRole('button', { name: /^Undo \((⌘|Ctrl)\+Z\)$/ })).toBeEnabled(); await page.locator(part('Sculpt block')).click(); await page.keyboard.press('1'); @@ -501,6 +506,7 @@ for (const replaceScene of [false, true]) { }); const edit = /\/live\/edit$/; await page.route(edit, async (route) => { + if (!route.request().postDataJSON().sculpt) return route.continue(); await held; await route.fulfill({ status: 409, json: { error: 'Stroke refused for this test.' } }); }); @@ -522,14 +528,23 @@ for (const replaceScene of [false, true]) { await call('new_scene', { name: 'Replacement', discard_unsaved: true }); await expect(title).toHaveText('Replacement'); await expect(prompt).toHaveCount(0); - } - rejectStroke(); - await expect(page.getByText(/stroke refused for this test/i)).toBeVisible(); - await expect(prompt).toHaveCount(0); - if (replaceScene) { + const renamed = page.waitForResponse( + (response) => + edit.test(response.url()) && + response.request().postDataJSON().scene.name === 'Newer rename', + { timeout: 8000 }, + ); + await rename('Newer rename'); + await expect(title).toHaveText('Newer rename'); + rejectStroke(); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Newer rename'); await expect(help).toHaveCount(0); expect(undoRequests).toBe(0); } else { + rejectStroke(); + await expect(page.getByText(/stroke refused for this test/i)).toBeVisible(); + await expect(prompt).toHaveCount(0); // A later non-history command still runs after the refused stroke rolls back. await expect(help).toBeVisible(); await expect(title).toHaveText(acceptedName); @@ -543,6 +558,178 @@ for (const replaceScene of [false, true]) { ); } +test('publishes Delete queued behind a stroke interrupted by a shared pose update', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('0.12'); + await radius.press('Enter'); + const box = (await page.locator('canvas').boundingBox())!; + const start = { x: box.x + box.width / 2 - 55, y: box.y + box.height / 2 - 7 }; + const edit = page.waitForResponse( + (response) => + response.url().endsWith('/live/edit') && !response.request().postDataJSON().sculpt, + { timeout: 5000 }, + ); + await queueAfterPenRelease(page, start, [{ key: 'Delete', code: 'Delete' }], { + end: { x: start.x + 140, y: start.y }, + releaseClockOn: 'resume-sculpt-clock', + }); + try { + await call('update_parts', { updates: [{ id: 'block', translate: [2, 0, 0] }] }); + await expect(page.locator(part('Sculpt block'))).toHaveCount(0); + expect((await edit).ok()).toBe(true); + expect((await call('get_scene')).parts).toHaveLength(0); + } finally { + await page.evaluate(() => window.dispatchEvent(new Event('resume-sculpt-clock'))); + } +}); + +for (const holdResponse of [false, true]) { + test(`keeps a stroke and queued Save when the tab receives its own replacement ${holdResponse ? 'before' : 'after'} HTTP success`, async ({ + page, + }) => { + await page.addInitScript(() => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + const { version } = JSON.parse(event.data); + const { dataset } = document.documentElement; + dataset.sharedVersion = String(version); + if (dataset.holdShared === '1') { + event.stopImmediatePropagation(); + window.addEventListener( + 'release-shared-scene', + () => this.dispatchEvent(new MessageEvent('scene', { data: event.data })), + { once: true }, + ); + } + }); + } + }; + }); + await call('add_parts', { + parts: [{ id: 'old', name: 'Old block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await expect(page.locator(part('Old block'))).toBeVisible(); + const geometry = new BoxGeometry(10, 8, 6); + const openedScene = { + format: 'kitbasher', + version: 1, + units: 'mm', + name: 'Opened scene', + joints: [], + parts: [ + { + id: 'new', + name: 'New block', + geometry: serializeGeometry(geometry), + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#cccccc', + visible: true, + locked: false, + source: 'block', + }, + ], + }; + let submit = () => {}; + let reply = () => {}; + const submitted = new Promise((resolve) => { + submit = resolve; + }); + const answered = new Promise((resolve) => { + reply = resolve; + }); + const edit = /\/live\/edit$/; + let replacementVersion = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().replace) return route.continue(); + await submitted; + const response = await route.fetch(); + replacementVersion = (await response.json()).version; + if (holdResponse) await answered; + await route.fulfill({ response }); + }); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'opened.kitbash', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(openedScene)), + }); + const opening = page.waitForRequest( + (request) => edit.test(request.url()) && request.postDataJSON().replace, + ); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + const original = await opening; + await page.locator(part('New block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const box = (await page.locator('canvas').boundingBox())!; + await queueAfterPenRelease( + page, + { x: box.x + box.width / 2 + 8, y: box.y + box.height / 2 - 7 }, + [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 's', code: 'KeyS', ctrlKey: true }, + ], + ); + const prompt = page.locator('.free-transform-prompt'); + await expect(prompt).toBeVisible(); + const response = page.waitForResponse((result) => result.request() === original); + const acceptedStroke = page + .waitForResponse( + (result) => edit.test(result.url()) && !!result.request().postDataJSON().sculpt, + { timeout: 8000 }, + ) + .catch(() => null); + if (!holdResponse) + await page.evaluate(() => { + document.documentElement.dataset.holdShared = '1'; + }); + submit(); + if (!holdResponse) expect((await response).ok()).toBe(true); + await expect.poll(() => replacementVersion).toBeGreaterThan(0); + await expect(page.locator('html')).toHaveAttribute( + 'data-shared-version', + String(replacementVersion), + ); + if (holdResponse) { + reply(); + expect((await response).ok()).toBe(true); + } else { + await page.evaluate(() => { + delete document.documentElement.dataset.holdShared; + window.dispatchEvent(new Event('release-shared-scene')); + }); + } + expect((await acceptedStroke)?.ok()).toBe(true); + await expect(prompt).toBeVisible(); + const download = page.waitForEvent('download'); + await page.keyboard.press('Escape'); + const saved = await download; + const { scene } = await readSavedScene((await saved.path())!); + expect(scene.name).toBe('Opened scene'); + const sculpted = scene.parts[0].geometry; + expect(sculpted.index?.count ?? sculpted.getAttribute('position').count).toBeGreaterThan(36); + geometry.dispose(); + }); +} + test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ page, }) => { From 279bc380d484972259857809adbf47156869e61e Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 12:32:40 -0800 Subject: [PATCH 36/40] (fix) Keep stale Open requests from replacing newer shared scenes --- mcp/document.ts | 7 ++-- src/core/live.ts | 24 ++++++++--- tests/e2e/mcp.spec.ts | 96 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 114 insertions(+), 13 deletions(-) diff --git a/mcp/document.ts b/mcp/document.ts index 73c81be..1dba8ab 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -100,13 +100,14 @@ export class SharedDocument { } apply(author: string, edit: Edit) { + if (edit.replace && edit.replacementId && this.replacementId === edit.replacementId) + return this.version; + if ((!edit.replace || edit.replacementId) && edit.epoch !== this.epoch) + throw new EditConflict('The scene was replaced while this change was being made.'); if (edit.replace) { - if (edit.replacementId && this.replacementId === edit.replacementId) return this.version; this.replace(edit.scene, author, false, edit.replacementId); return this.version; } - if (edit.epoch !== this.epoch) - throw new EditConflict('The scene was replaced while this change was being made.'); const base = this.versions.get(edit.base); if (!base) throw new EditConflict('This change was made on a version of the scene that is too old.'); diff --git a/src/core/live.ts b/src/core/live.ts index bb2819a..990cc9e 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -22,6 +22,8 @@ interface OrdinaryEdit { scene: SceneDocument; checkpoint: boolean; replacementId?: string; + /** A retried Open must keep the epoch it was first submitted against. */ + replacementEpoch?: number; } interface SculptEdit { @@ -276,7 +278,14 @@ export function joinLiveSession() { (message.epoch !== acceptedSculpt.epoch || message.version >= acceptedSculpt.version) ) acceptedSculpt = null; - const replacing = !!acceptedReplacement || unsent.some(replacementIdOf); + const replacing = + !!acceptedReplacement || + unsent.some( + (edit) => + !('sculpt' in edit) && + edit.replacementId && + (edit.replacementEpoch ?? message.epoch) === message.epoch, + ); const changedScene = !replacing && (first || (replaced && !ownReplacement)); let next = scene; // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. @@ -395,7 +404,9 @@ export function joinLiveSession() { const base = confirmed!; const sculpt = 'sculpt' in edit ? edit.sculpt : undefined; const checkpoint = 'sculpt' in edit || edit.checkpoint; - const replacementId = replacementIdOf(edit); + const replacement = !('sculpt' in edit) && edit.replacementId ? edit : null; + const replacementId = replacement?.replacementId; + const epoch = replacement?.replacementEpoch ?? base.epoch; const sceneEpoch = useEditor.getState().sceneEpoch; const replacementObserved = () => !!replacementId && confirmed?.replacementId === replacementId; const stillApplies = () => @@ -406,7 +417,7 @@ export function joinLiveSession() { activeSculptObserved = false; if (!sculpt) useEditor.getState().submitWarp(); try { - if (replacementObserved()) return; + if (replacementObserved() || epoch !== base.epoch) return; if ('sculpt' in edit) { const target = base.scene.parts.find((part) => part.id === edit.sculpt.partId); // A request can succeed even when the connection drops before its response arrives. @@ -428,7 +439,7 @@ export function joinLiveSession() { const response = await post('live/edit', { client, base: base.version, - epoch: base.epoch, + epoch, checkpoint, replace: !!replacementId, replacementId, @@ -450,14 +461,15 @@ export function joinLiveSession() { } } else { const reason = await errorOf(response); - if (stillApplies()) refused(reason); + if (stillApplies() && !replacementObserved()) refused(reason); } } catch (error) { if (!stillApplies() || replacementObserved()) return; if (error instanceof Refusal) refused(error.message); else { // Retry an interrupted request unless the stream already confirmed the stroke. - if (!activeSculptObserved) edits.unshift(edit); + if (!activeSculptObserved) + edits.unshift(replacement ? { ...replacement, replacementEpoch: epoch } : edit); if (!sculpt) useEditor.getState().retryWarp(); lost(); } diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 3abc54c..fee1e66 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -594,10 +594,11 @@ test('publishes Delete queued behind a stroke interrupted by a shared pose updat } }); -for (const holdResponse of [false, true]) { - test(`keeps a stroke and queued Save when the tab receives its own replacement ${holdResponse ? 'before' : 'after'} HTTP success`, async ({ +for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error'] as const) { + test(`keeps a stroke and queued Save when acknowledging a replacement with ${replyOrder}`, async ({ page, }) => { + const holdResponse = replyOrder !== 'HTTP first'; await page.addInitScript(() => { const NativeEventSource = window.EventSource; window.EventSource = class extends NativeEventSource { @@ -663,7 +664,9 @@ for (const holdResponse of [false, true]) { const response = await route.fetch(); replacementVersion = (await response.json()).version; if (holdResponse) await answered; - await route.fulfill({ response }); + if (replyOrder === 'stream then HTTP error') + await route.fulfill({ status: 502, json: { error: 'Replacement response was lost.' } }); + else await route.fulfill({ response }); }); await page.getByLabel('Open Kitbasher scene').setInputFiles({ name: 'opened.kitbash', @@ -710,7 +713,7 @@ for (const holdResponse of [false, true]) { ); if (holdResponse) { reply(); - expect((await response).ok()).toBe(true); + expect((await response).status()).toBe(replyOrder === 'stream then HTTP error' ? 502 : 200); } else { await page.evaluate(() => { delete document.documentElement.dataset.holdShared; @@ -730,6 +733,91 @@ for (const holdResponse of [false, true]) { }); } +for (const loseReply of [false, true]) { + test( + loseReply + ? 'preserves the newer shared scene after a replacement loses both acknowledgments' + : 'rejects an in-flight Open after another editor replaces the shared scene', + async ({ page }) => { + const openedName = 'Opened by this tab'; + if (loseReply) + await page.addInitScript((name) => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + if (JSON.parse(event.data).scene.name === name) event.stopImmediatePropagation(); + }); + } + }; + }, openedName); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + await expect(title).toHaveText('Untitled assembly'); + + let resume = () => {}; + const held = new Promise((resolve) => { + resume = resolve; + }); + const edit = /\/live\/edit$/; + let replacements = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().replace || ++replacements !== 1) + return route.continue(); + if (loseReply) { + const response = await route.fetch(); + expect(response.ok()).toBe(true); + await route.abort('connectionreset'); + } else { + await held; + await route.continue(); + } + }); + const submitted = page.waitForRequest(edit); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'opened.kitbash', + mimeType: 'application/json', + buffer: Buffer.from( + JSON.stringify({ + format: 'kitbasher', + version: 1, + units: 'mm', + name: openedName, + parts: [], + joints: [], + }), + ), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + const request = await submitted; + if (loseReply) { + await expect(page.getByText(/Agent disconnected/)).toBeVisible(); + expect((await call('get_scene')).name).toBe(openedName); + } + const newer = 'Newer shared scene'; + await call('new_scene', { name: newer, discard_unsaved: true }); + await expect(title).toHaveText(newer); + if (!loseReply) { + const response = page.waitForResponse((result) => result.request() === request); + resume(); + expect((await response).status()).toBe(409); + } + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill('Edit on the newer scene'); + const renamed = page.waitForResponse( + (result) => edit.test(result.url()) && !result.request().postDataJSON().replace, + ); + await field.press('Enter'); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Edit on the newer scene'); + expect(replacements).toBe(1); + }, + ); +} + test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ page, }) => { From ff7f25e70cb883bffedc754f62d7eec3519ae788 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 12:48:12 -0800 Subject: [PATCH 37/40] (fix) Recover shared sculpt edits after ambiguous responses --- src/core/live.ts | 119 ++++++++++++++++++--------- tests/e2e/mcp.spec.ts | 185 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 242 insertions(+), 62 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 990cc9e..c5d1990 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -22,7 +22,7 @@ interface OrdinaryEdit { scene: SceneDocument; checkpoint: boolean; replacementId?: string; - /** A retried Open must keep the epoch it was first submitted against. */ + /** The shared epoch the user opened this scene from. */ replacementEpoch?: number; } @@ -109,7 +109,8 @@ const errorOf = async (response: Response) => */ export function joinLiveSession() { const client = tabId(); - const source = new EventSource('live/events'); + let source: EventSource; + let streamRetry: number | undefined; const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); @@ -135,6 +136,7 @@ export function joinLiveSession() { let activeSculptObserved = false; let acceptedSculpt: { edit: SculptEdit; version: number; epoch: number } | null = null; let acceptedReplacement: { edit: OrdinaryEdit; version: number } | null = null; + let submittedReplacement: { id: string; epoch: number } | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; let awaitedHistory: { version: number; sculpt: number | null } | null = null; @@ -215,6 +217,7 @@ export function joinLiveSession() { : scene, checkpoint: replace || !!dirtyEdit?.checkpoint || state.past !== previous.past, replacementId: replace ? uid() : dirtyEdit?.replacementId, + replacementEpoch: replace ? confirmed.epoch : dirtyEdit?.replacementEpoch, }; } void pump(); @@ -264,6 +267,19 @@ export function joinLiveSession() { if (acceptedReplacement && message.version >= acceptedReplacement.version) acceptedReplacement = null; const unsent = unsentEdits(); + if (submittedReplacement && message.epoch !== submittedReplacement.epoch) { + // A second Open in this tab can be queued while its previous Open is still being confirmed. + if (message.replacementId === submittedReplacement.id) { + for (const edit of unsent) + if ( + !('sculpt' in edit) && + edit.replacementId && + edit.replacementEpoch === submittedReplacement.epoch + ) + edit.replacementEpoch = message.epoch; + } + submittedReplacement = null; + } if (!replaced && active && 'sculpt' in active) { const { sculpt, geometry } = active; if ( @@ -282,9 +298,7 @@ export function joinLiveSession() { !!acceptedReplacement || unsent.some( (edit) => - !('sculpt' in edit) && - edit.replacementId && - (edit.replacementEpoch ?? message.epoch) === message.epoch, + !('sculpt' in edit) && edit.replacementId && edit.replacementEpoch === message.epoch, ); const changedScene = !replacing && (first || (replaced && !ownReplacement)); let next = scene; @@ -313,6 +327,8 @@ export function joinLiveSession() { scene, }; const [undo, redo] = message.history[client] ?? [0, 0]; + window.clearTimeout(streamRetry); + streamRetry = undefined; if (!connected) { connected = true; useSharedHistory(history); @@ -371,17 +387,18 @@ export function joinLiveSession() { }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ - const refused = (reason?: string) => { + const refused = (reason?: string, replacement = false) => { const { sculpt } = useEditor.getState(); // Queued history requests refer to the discarded optimistic scene. requests.length = 0; - cancelQueuedSculptActions('history'); + cancelQueuedSculptActions(replacement ? 'all' : 'history'); stopSharedSculptHistory(true); edits.length = 0; dirtyEdit = null; if (confirmed) { - show(confirmed.scene); - restoreSculptAfterRefusal(confirmed.scene, sculpt); + if (replacement && sculpt) useEditor.setState({ tool: 'select', sculpt: null }); + show(confirmed.scene, replacement); + if (!replacement) restoreSculptAfterRefusal(confirmed.scene, sculpt); } notify( `Your last change was undone because it could not be combined with ${other}'s.${reason ? ` ${reason}` : ''}`, @@ -399,6 +416,18 @@ export function joinLiveSession() { useEditor.setState({ liveStatus: 'disconnected', sharedHistory: null, past: [], future: [] }); }; + const refreshStream = () => { + lost(); + window.clearTimeout(streamRetry); + streamRetry = window.setTimeout(() => { + streamRetry = undefined; + source.close(); + streamGeneration++; + latest = null; + openStream(); + }, 300); + }; + const sendEdit = async (edit: QueuedEdit) => { // Keep the submitted draft separate from any warp applied while this edit is in flight. const base = confirmed!; @@ -413,6 +442,21 @@ export function joinLiveSession() { !closed && useEditor.getState().sceneEpoch === sceneEpoch && (confirmed?.epoch === base.epoch || replacementObserved()); + const observed = () => activeSculptObserved || replacementObserved(); + const rejectEdit = (reason?: string) => { + if (observed()) return; + if (submittedReplacement?.id === replacementId && replacementId) submittedReplacement = null; + if (stillApplies()) refused(reason, !!replacement); + }; + const recoverEdit = () => { + if (closed || observed() || confirmed?.epoch !== epoch) return; + if (stillApplies()) { + edits.unshift(edit); + if (!sculpt) useEditor.getState().retryWarp(); + } else if (!replacementId || submittedReplacement?.id !== replacementId) return; + if (replacement || sculpt) refreshStream(); + else lost(); + }; activeEdit = { edit, epoch: base.epoch, sceneEpoch }; activeSculptObserved = false; if (!sculpt) useEditor.getState().submitWarp(); @@ -436,6 +480,7 @@ export function joinLiveSession() { meshes.set(key, geometry); } if (!stillApplies()) return; + if (replacementId) submittedReplacement = { id: replacementId, epoch }; const response = await post('live/edit', { client, base: base.version, @@ -450,7 +495,7 @@ export function joinLiveSession() { awaited = ((await response.json()) as { version: number }).version; if (!stillApplies()) return; if (!('sculpt' in edit)) { - if (replacementId && confirmed && confirmed.version < awaited) + if (replacementId && !replacementObserved() && confirmed && confirmed.version < awaited) acceptedReplacement = { edit, version: awaited }; useEditor.getState().settleWarp(true, true); } else if (confirmed && confirmed.version >= awaited) { @@ -459,20 +504,11 @@ export function joinLiveSession() { } else if (!activeSculptObserved && confirmed?.epoch === base.epoch) { acceptedSculpt = { edit, version: awaited, epoch: base.epoch }; } - } else { - const reason = await errorOf(response); - if (stillApplies() && !replacementObserved()) refused(reason); - } + } else if ((replacement || sculpt) && response.status >= 500) recoverEdit(); + else rejectEdit(await errorOf(response)); } catch (error) { - if (!stillApplies() || replacementObserved()) return; - if (error instanceof Refusal) refused(error.message); - else { - // Retry an interrupted request unless the stream already confirmed the stroke. - if (!activeSculptObserved) - edits.unshift(replacement ? { ...replacement, replacementEpoch: epoch } : edit); - if (!sculpt) useEditor.getState().retryWarp(); - lost(); - } + if (error instanceof Refusal) rejectEdit(error.message); + else recoverEdit(); } finally { activeEdit = null; } @@ -545,24 +581,33 @@ export function joinLiveSession() { window.addEventListener('pointerdown', markViewMoved, { capture: true, once: true }); window.addEventListener('wheel', markViewMoved, { capture: true, once: true, passive: true }); - source.addEventListener('scene', (event) => { - latest = JSON.parse((event as MessageEvent).data); - void receive(); - }); - // Sent only to tabs on the computer that holds the scene: how another device joins it. - source.addEventListener('share', (event) => - useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }), - ); - // EventSource keeps retrying, so a server that is only briefly unreachable reconnects by itself. - source.onerror = () => { - streamGeneration++; - latest = null; - lost(); - }; + function openStream() { + const stream = new EventSource('live/events'); + source = stream; + stream.addEventListener('scene', (event) => { + if (closed || source !== stream) return; + latest = JSON.parse((event as MessageEvent).data); + void receive(); + }); + // Sent only to tabs on the computer that holds the scene: how another device joins it. + stream.addEventListener('share', (event) => { + if (!closed && source === stream) + useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }); + }); + // EventSource reconnects automatically when the event stream itself fails. + stream.onerror = () => { + if (closed || source !== stream) return; + streamGeneration++; + latest = null; + lost(); + }; + } + openStream(); useEditor.setState({ liveStatus: 'connecting' }); return () => { closed = true; + window.clearTimeout(streamRetry); source.close(); unsubscribe(); useSharedSculptQueueGuard(null); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index fee1e66..2eba9a6 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -594,21 +594,29 @@ test('publishes Delete queued behind a stroke interrupted by a shared pose updat } }); -for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error'] as const) { - test(`keeps a stroke and queued Save when acknowledging a replacement with ${replyOrder}`, async ({ - page, - }) => { - const holdResponse = replyOrder !== 'HTTP first'; +for (const replyOrder of [ + 'HTTP first', + 'stream first', + 'stream then HTTP error', + 'HTTP error then refreshed stream', + 'HTTP rejection', +] as const) { + test(`keeps sculpt and Save scoped to the right scene with ${replyOrder}`, async ({ page }) => { + const holdResponse = replyOrder.startsWith('stream'); + const httpError = replyOrder.includes('HTTP error'); + const rejected = replyOrder === 'HTTP rejection'; await page.addInitScript(() => { const NativeEventSource = window.EventSource; + let connections = 0; window.EventSource = class extends NativeEventSource { constructor(url: string | URL, init?: EventSourceInit) { super(url, init); + const initialStream = ++connections === 1; this.addEventListener('scene', (event) => { const { version } = JSON.parse(event.data); const { dataset } = document.documentElement; dataset.sharedVersion = String(version); - if (dataset.holdShared === '1') { + if (initialStream && dataset.holdShared === '1') { event.stopImmediatePropagation(); window.addEventListener( 'release-shared-scene', @@ -661,10 +669,15 @@ for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error' await page.route(edit, async (route) => { if (!route.request().postDataJSON().replace) return route.continue(); await submitted; + if (rejected) + return route.fulfill({ + status: 409, + json: { error: 'Replacement refused for this test.' }, + }); const response = await route.fetch(); replacementVersion = (await response.json()).version; if (holdResponse) await answered; - if (replyOrder === 'stream then HTTP error') + if (httpError) await route.fulfill({ status: 502, json: { error: 'Replacement response was lost.' } }); else await route.fulfill({ response }); }); @@ -694,6 +707,16 @@ for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error' const prompt = page.locator('.free-transform-prompt'); await expect(prompt).toBeVisible(); const response = page.waitForResponse((result) => result.request() === original); + if (rejected) { + const download = page.waitForEvent('download', { timeout: 1500 }).catch(() => null); + submit(); + expect((await response).status()).toBe(409); + await expect(page.locator(part('Old block'))).toBeVisible(); + await expect(prompt).toHaveCount(0); + expect(await download).toBeNull(); + geometry.dispose(); + return; + } const acceptedStroke = page .waitForResponse( (result) => edit.test(result.url()) && !!result.request().postDataJSON().sculpt, @@ -705,7 +728,7 @@ for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error' document.documentElement.dataset.holdShared = '1'; }); submit(); - if (!holdResponse) expect((await response).ok()).toBe(true); + if (!holdResponse) expect((await response).status()).toBe(httpError ? 502 : 200); await expect.poll(() => replacementVersion).toBeGreaterThan(0); await expect(page.locator('html')).toHaveAttribute( 'data-shared-version', @@ -713,8 +736,8 @@ for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error' ); if (holdResponse) { reply(); - expect((await response).status()).toBe(replyOrder === 'stream then HTTP error' ? 502 : 200); - } else { + expect((await response).status()).toBe(httpError ? 502 : 200); + } else if (!httpError) { await page.evaluate(() => { delete document.documentElement.dataset.holdShared; window.dispatchEvent(new Event('release-shared-scene')); @@ -733,6 +756,17 @@ for (const replyOrder of ['HTTP first', 'stream first', 'stream then HTTP error' }); } +async function openBlankSceneInTab(page: Page, name: string) { + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'opened.kitbash', + mimeType: 'application/json', + buffer: Buffer.from( + JSON.stringify({ format: 'kitbasher', version: 1, units: 'mm', name, parts: [], joints: [] }), + ), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); +} + for (const loseReply of [false, true]) { test( loseReply @@ -776,21 +810,7 @@ for (const loseReply of [false, true]) { } }); const submitted = page.waitForRequest(edit); - await page.getByLabel('Open Kitbasher scene').setInputFiles({ - name: 'opened.kitbash', - mimeType: 'application/json', - buffer: Buffer.from( - JSON.stringify({ - format: 'kitbasher', - version: 1, - units: 'mm', - name: openedName, - parts: [], - joints: [], - }), - ), - }); - await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await openBlankSceneInTab(page, openedName); const request = await submitted; if (loseReply) { await expect(page.getByText(/Agent disconnected/)).toBeVisible(); @@ -818,6 +838,121 @@ for (const loseReply of [false, true]) { ); } +for (const fromSameTab of [false, true]) { + test( + fromSameTab + ? 'advances a queued second Open when this tab’s first Open is acknowledged' + : 'discards an unsent Open when another editor replaces its starting scene', + async ({ page }) => { + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + await expect(title).toHaveText('Untitled assembly'); + const rename = async (name: string) => { + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + let resume = () => {}; + const held = new Promise((resolve) => { + resume = resolve; + }); + const edit = /\/live\/edit$/; + const requests: { replace: boolean; epoch: number }[] = []; + await page.route(edit, async (route) => { + requests.push(route.request().postDataJSON()); + if (requests.length === 1) await held; + await route.continue(); + }); + const first = page.waitForRequest(edit); + if (fromSameTab) await openBlankSceneInTab(page, 'First Open'); + else await rename('Pending rename'); + await first; + await openBlankSceneInTab(page, 'Queued Open'); + await expect(title).toHaveText('Queued Open'); + if (fromSameTab) { + resume(); + await expect.poll(async () => (await call('get_scene')).name).toBe('Queued Open'); + expect(requests.map(({ epoch }) => epoch)).toEqual([ + requests[0].epoch, + requests[0].epoch + 1, + ]); + } else { + await call('new_scene', { name: 'Remote Open', discard_unsaved: true }); + await expect(title).toHaveText('Remote Open'); + resume(); + const renamed = page.waitForResponse( + (result) => + edit.test(result.url()) && result.request().postDataJSON().scene.name === 'Newer edit', + ); + await rename('Newer edit'); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Newer edit'); + expect(requests.some(({ replace }) => replace)).toBe(false); + } + }, + ); +} + +for (const dropResponse of [false, true]) { + test(`publishes the next shared stroke after a stream-confirmed stroke gets a ${dropResponse ? 'connection reset' : '502'}`, async ({ + page, + }) => { + await page.addInitScript(() => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + document.documentElement.dataset.sharedVersion = String(JSON.parse(event.data).version); + }); + } + }; + }); + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const box = (await page.locator('canvas').boundingBox())!; + const point = { x: box.x + box.width / 2 + 8, y: box.y + box.height / 2 - 7 }; + let settle = () => {}; + const held = new Promise((resolve) => { + settle = resolve; + }); + const edit = /\/live\/edit$/; + let firstVersion = 0; + let strokes = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().sculpt || ++strokes !== 1) return route.continue(); + const response = await route.fetch(); + expect(response.ok()).toBe(true); + firstVersion = (await response.json()).version; + await held; + if (dropResponse) await route.abort('connectionreset'); + else await route.fulfill({ status: 502, json: { error: 'Stroke response was lost.' } }); + }); + await page.mouse.click(point.x, point.y); + await expect.poll(() => firstVersion).toBeGreaterThan(0); + await expect(page.locator('html')).toHaveAttribute('data-shared-version', String(firstVersion)); + await page.mouse.click(point.x + 18, point.y); + const next = page.waitForResponse( + (result) => + edit.test(result.url()) && result.ok() && !!result.request().postDataJSON().sculpt, + { timeout: 8000 }, + ); + settle(); + expect((await next).ok()).toBe(true); + expect(strokes).toBe(2); + await expect(page.getByText('Shared with agent')).toBeVisible(); + }); +} + test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ page, }) => { From 29df023bb33eb2634a51305d31af447609023ba6 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 13:04:32 -0800 Subject: [PATCH 38/40] (fix) Retry shared mesh uploads and ignore stale recovery snapshots --- mcp/document.ts | 2 +- src/core/live.ts | 38 ++++++-- tests/e2e/mcp.spec.ts | 154 +++++++++++++++++++++++------- tests/unit/sculpt-session.test.ts | 10 +- 4 files changed, 160 insertions(+), 44 deletions(-) diff --git a/mcp/document.ts b/mcp/document.ts index 1dba8ab..eea99dd 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -116,11 +116,11 @@ export class SharedDocument { const target = edit.sculpt; const part = current.parts.find((part) => part.id === target.partId); const carved = edit.scene.parts.find((part) => part.id === target.partId); + if (part && carved && carved.geometry === part.geometry) return this.version; if (!part || !carved || !matchesSculptTarget(part, target)) throw new EditConflict( 'The sculpt target changed before the stroke reached the shared scene.', ); - if (carved.geometry === part.geometry) return this.version; const next = { ...current, parts: current.parts.map((candidate) => diff --git a/src/core/live.ts b/src/core/live.ts index c5d1990..e79c6d1 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -102,6 +102,9 @@ const post = (path: string, body: unknown) => const errorOf = async (response: Response) => ((await response.json().catch(() => ({}))) as { error?: string }).error; +const firstStreamRetry = 300; +const maxStreamRetry = 5000; + /** * Edits the scene an MCP server holds, alongside the agent and any other tabs. Changes made here * show at once and are sent in the background; the server combines them with everyone else's. @@ -109,8 +112,9 @@ const errorOf = async (response: Response) => */ export function joinLiveSession() { const client = tabId(); - let source: EventSource; + let source: EventSource | null = null; let streamRetry: number | undefined; + let streamRetryDelay = firstStreamRetry; const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); @@ -329,6 +333,7 @@ export function joinLiveSession() { const [undo, redo] = message.history[client] ?? [0, 0]; window.clearTimeout(streamRetry); streamRetry = undefined; + if (ownReplacement || changedScene || !unsent.length) streamRetryDelay = firstStreamRetry; if (!connected) { connected = true; useSharedHistory(history); @@ -382,8 +387,11 @@ export function joinLiveSession() { headers: { 'X-Kitbasher-Layout': JSON.stringify(layout) }, body: new Blob(body), }); - if (!response.ok) - throw new Refusal((await errorOf(response)) ?? `${host} could not take a mesh.`); + if (!response.ok) { + const reason = (await errorOf(response)) ?? `${host} could not take a mesh.`; + if (response.status >= 500) throw new Error(reason); + throw new Refusal(reason); + } }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ @@ -417,15 +425,18 @@ export function joinLiveSession() { }; const refreshStream = () => { + // The old stream may still have a snapshot from before the request was applied. + source?.close(); + source = null; + streamGeneration++; + latest = null; lost(); window.clearTimeout(streamRetry); streamRetry = window.setTimeout(() => { streamRetry = undefined; - source.close(); - streamGeneration++; - latest = null; openStream(); - }, 300); + }, streamRetryDelay); + streamRetryDelay = Math.min(streamRetryDelay * 2, maxStreamRetry); }; const sendEdit = async (edit: QueuedEdit) => { @@ -442,6 +453,7 @@ export function joinLiveSession() { !closed && useEditor.getState().sceneEpoch === sceneEpoch && (confirmed?.epoch === base.epoch || replacementObserved()); + let uploadingMesh = false; const observed = () => activeSculptObserved || replacementObserved(); const rejectEdit = (reason?: string) => { if (observed()) return; @@ -454,7 +466,7 @@ export function joinLiveSession() { edits.unshift(edit); if (!sculpt) useEditor.getState().retryWarp(); } else if (!replacementId || submittedReplacement?.id !== replacementId) return; - if (replacement || sculpt) refreshStream(); + if (replacement || sculpt || uploadingMesh) refreshStream(); else lost(); }; activeEdit = { edit, epoch: base.epoch, sceneEpoch }; @@ -465,7 +477,10 @@ export function joinLiveSession() { if ('sculpt' in edit) { const target = base.scene.parts.find((part) => part.id === edit.sculpt.partId); // A request can succeed even when the connection drops before its response arrives. - if (target?.geometry.uuid === edit.geometry.uuid) return; + if (target?.geometry.uuid === edit.geometry.uuid) { + streamRetryDelay = firstStreamRetry; + return; + } if (!matchesSculptTarget(target, edit.sculpt)) throw new Refusal( 'The sculpt target changed before the stroke reached the shared scene.', @@ -475,7 +490,9 @@ export function joinLiveSession() { for (const { geometry } of scene.parts) { const key = geometry.uuid; if (known.has(key)) continue; + uploadingMesh = true; await upload(key, geometry); + uploadingMesh = false; known.add(key); meshes.set(key, geometry); } @@ -493,6 +510,7 @@ export function joinLiveSession() { }); if (response.ok) { awaited = ((await response.json()) as { version: number }).version; + streamRetryDelay = firstStreamRetry; if (!stillApplies()) return; if (!('sculpt' in edit)) { if (replacementId && !replacementObserved() && confirmed && confirmed.version < awaited) @@ -608,7 +626,7 @@ export function joinLiveSession() { return () => { closed = true; window.clearTimeout(streamRetry); - source.close(); + source?.close(); unsubscribe(); useSharedSculptQueueGuard(null); useSharedHistory(null); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 2eba9a6..b6f3e9b 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -6,7 +6,7 @@ import { join } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { expect, test } from '@playwright/test'; -import type { Page } from '@playwright/test'; +import type { Page, Request } from '@playwright/test'; import { BoxGeometry, Mesh } from 'three'; import { STLExporter } from 'three/addons/exporters/STLExporter.js'; import { serializeGeometry } from '../../src/core/geometry'; @@ -594,17 +594,68 @@ test('publishes Delete queued behind a stroke interrupted by a shared pose updat } }); +const isMeshUpload = (request: Request) => + request.method() === 'POST' && /\/live\/geometry\/[^/]+$/.test(request.url()); + +async function failFirstMeshUpload(page: Page, held: Promise) { + const keys: string[] = []; + await page.route(/\/live\/geometry\//, async (route) => { + if (!isMeshUpload(route.request())) return route.continue(); + keys.push(route.request().url()); + if (keys.length !== 1) return route.continue(); + await held; + await route.fulfill({ status: 502, json: { error: 'The mesh upload response was lost.' } }); + }); + return keys; +} + +async function captureStaleSharedStream(page: Page) { + await page.addInitScript(() => { + const fetch = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await fetch(...args); + if (response.status === 502 && response.url.endsWith('/live/edit')) + window.setTimeout(() => window.dispatchEvent(new Event('replay-stale-scene')), 20); + return response; + }; + const NativeEventSource = window.EventSource; + let first = true; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + if (!first) return; + first = false; + let initial: string | null = null; + this.addEventListener('scene', (event) => { + initial ??= event.data; + if (event.data !== initial) event.stopImmediatePropagation(); + }); + window.addEventListener( + 'replay-stale-scene', + () => { + document.documentElement.dataset.replayedStaleScene = '1'; + this.dispatchEvent(new MessageEvent('scene', { data: initial })); + }, + { once: true }, + ); + } + }; + }); +} + for (const replyOrder of [ 'HTTP first', 'stream first', 'stream then HTTP error', 'HTTP error then refreshed stream', 'HTTP rejection', + 'mesh upload 502', ] as const) { test(`keeps sculpt and Save scoped to the right scene with ${replyOrder}`, async ({ page }) => { const holdResponse = replyOrder.startsWith('stream'); const httpError = replyOrder.includes('HTTP error'); const rejected = replyOrder === 'HTTP rejection'; + const uploadError = replyOrder === 'mesh upload 502'; await page.addInitScript(() => { const NativeEventSource = window.EventSource; let connections = 0; @@ -665,6 +716,7 @@ for (const replyOrder of [ reply = resolve; }); const edit = /\/live\/edit$/; + const uploads = uploadError ? await failFirstMeshUpload(page, submitted) : []; let replacementVersion = 0; await page.route(edit, async (route) => { if (!route.request().postDataJSON().replace) return route.continue(); @@ -687,7 +739,9 @@ for (const replyOrder of [ buffer: Buffer.from(JSON.stringify(openedScene)), }); const opening = page.waitForRequest( - (request) => edit.test(request.url()) && request.postDataJSON().replace, + uploadError + ? isMeshUpload + : (request) => edit.test(request.url()) && request.postDataJSON().replace, ); await page.getByRole('button', { name: 'Open scene', exact: true }).click(); const original = await opening; @@ -723,27 +777,27 @@ for (const replyOrder of [ { timeout: 8000 }, ) .catch(() => null); - if (!holdResponse) + if (!holdResponse && !uploadError) await page.evaluate(() => { document.documentElement.dataset.holdShared = '1'; }); submit(); - if (!holdResponse) expect((await response).status()).toBe(httpError ? 502 : 200); + if (!holdResponse) expect((await response).status()).toBe(httpError || uploadError ? 502 : 200); await expect.poll(() => replacementVersion).toBeGreaterThan(0); - await expect(page.locator('html')).toHaveAttribute( - 'data-shared-version', - String(replacementVersion), - ); + await expect + .poll(async () => Number(await page.locator('html').getAttribute('data-shared-version'))) + .toBeGreaterThanOrEqual(replacementVersion); if (holdResponse) { reply(); expect((await response).status()).toBe(httpError ? 502 : 200); - } else if (!httpError) { + } else if (!httpError && !uploadError) { await page.evaluate(() => { delete document.documentElement.dataset.holdShared; window.dispatchEvent(new Event('release-shared-scene')); }); } expect((await acceptedStroke)?.ok()).toBe(true); + if (uploadError) expect(uploads.slice(0, 2)).toEqual([uploads[0], uploads[0]]); await expect(prompt).toBeVisible(); const download = page.waitForEvent('download'); await page.keyboard.press('Escape'); @@ -838,12 +892,15 @@ for (const loseReply of [false, true]) { ); } -for (const fromSameTab of [false, true]) { +for (const firstEdit of ['remote', 'same tab', 'same tab with stale stream'] as const) { + const fromSameTab = firstEdit !== 'remote'; test( fromSameTab - ? 'advances a queued second Open when this tab’s first Open is acknowledged' + ? `advances a queued second Open when this tab’s first Open is acknowledged (${firstEdit})` : 'discards an unsent Open when another editor replaces its starting scene', async ({ page }) => { + const staleStream = firstEdit === 'same tab with stale stream'; + if (staleStream) await captureStaleSharedStream(page); const { url } = await call('open_live_view', { open_browser: false }); await page.goto(url); const title = page.getByTitle('Rename assembly'); @@ -862,7 +919,13 @@ for (const fromSameTab of [false, true]) { const requests: { replace: boolean; epoch: number }[] = []; await page.route(edit, async (route) => { requests.push(route.request().postDataJSON()); - if (requests.length === 1) await held; + if (requests.length === 1) { + await held; + if (staleStream) { + expect((await route.fetch()).ok()).toBe(true); + return route.fulfill({ status: 502, json: { error: 'Open response was lost.' } }); + } + } await route.continue(); }); const first = page.waitForRequest(edit); @@ -874,6 +937,8 @@ for (const fromSameTab of [false, true]) { if (fromSameTab) { resume(); await expect.poll(async () => (await call('get_scene')).name).toBe('Queued Open'); + if (staleStream) + await expect(page.locator('html')).toHaveAttribute('data-replayed-stale-scene', '1'); expect(requests.map(({ epoch }) => epoch)).toEqual([ requests[0].epoch, requests[0].epoch + 1, @@ -895,21 +960,30 @@ for (const fromSameTab of [false, true]) { ); } -for (const dropResponse of [false, true]) { - test(`publishes the next shared stroke after a stream-confirmed stroke gets a ${dropResponse ? 'connection reset' : '502'}`, async ({ - page, - }) => { - await page.addInitScript(() => { - const NativeEventSource = window.EventSource; - window.EventSource = class extends NativeEventSource { - constructor(url: string | URL, init?: EventSourceInit) { - super(url, init); - this.addEventListener('scene', (event) => { - document.documentElement.dataset.sharedVersion = String(JSON.parse(event.data).version); - }); - } - }; - }); +for (const failure of [ + 'late 502', + 'connection reset', + 'upload 502', + '502 with stale stream', +] as const) { + test(`publishes the next shared stroke after ${failure}`, async ({ page }) => { + const staleStream = failure === '502 with stale stream'; + const uploadError = failure === 'upload 502'; + if (staleStream) await captureStaleSharedStream(page); + else + await page.addInitScript(() => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + document.documentElement.dataset.sharedVersion = String( + JSON.parse(event.data).version, + ); + }); + } + }; + }); await call('add_parts', { parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], }); @@ -926,29 +1000,45 @@ for (const dropResponse of [false, true]) { settle = resolve; }); const edit = /\/live\/edit$/; + const uploads = uploadError ? await failFirstMeshUpload(page, held) : []; + const firstUpload = uploadError ? page.waitForRequest(isMeshUpload) : null; let firstVersion = 0; let strokes = 0; await page.route(edit, async (route) => { - if (!route.request().postDataJSON().sculpt || ++strokes !== 1) return route.continue(); + if (!route.request().postDataJSON().sculpt || ++strokes !== 1 || uploadError) + return route.continue(); const response = await route.fetch(); expect(response.ok()).toBe(true); firstVersion = (await response.json()).version; await held; - if (dropResponse) await route.abort('connectionreset'); + if (failure === 'connection reset') await route.abort('connectionreset'); else await route.fulfill({ status: 502, json: { error: 'Stroke response was lost.' } }); }); await page.mouse.click(point.x, point.y); - await expect.poll(() => firstVersion).toBeGreaterThan(0); - await expect(page.locator('html')).toHaveAttribute('data-shared-version', String(firstVersion)); + if (firstUpload) await firstUpload; + else { + await expect.poll(() => firstVersion).toBeGreaterThan(0); + if (!staleStream) + await expect(page.locator('html')).toHaveAttribute( + 'data-shared-version', + String(firstVersion), + ); + } await page.mouse.click(point.x + 18, point.y); const next = page.waitForResponse( (result) => - edit.test(result.url()) && result.ok() && !!result.request().postDataJSON().sculpt, + edit.test(result.url()) && + result.ok() && + !!result.request().postDataJSON().sculpt && + strokes >= 2, { timeout: 8000 }, ); settle(); expect((await next).ok()).toBe(true); + if (staleStream) + await expect(page.locator('html')).toHaveAttribute('data-replayed-stale-scene', '1'); expect(strokes).toBe(2); + if (uploadError) expect(uploads.slice(0, 2)).toEqual([uploads[0], uploads[0]]); await expect(page.getByText('Shared with agent')).toBeVisible(); }); } diff --git a/tests/unit/sculpt-session.test.ts b/tests/unit/sculpt-session.test.ts index 66a5e0b..b679390 100644 --- a/tests/unit/sculpt-session.test.ts +++ b/tests/unit/sculpt-session.test.ts @@ -197,7 +197,15 @@ describe('shared sculpt transactions', () => { document.apply('sculpt-tab', edit); expect(document.scene.name).toBe('Renamed'); expect(document.scene.parts[0].geometry).toBe(geometry); - expect(() => document.apply('sculpt-tab', edit)).toThrow(EditConflict); + const installed = document.version; + expect(document.apply('sculpt-tab', edit)).toBe(installed); + expect(document.counts('sculpt-tab').undo).toBe(1); + expect(() => + document.apply('sculpt-tab', { + ...edit, + scene: { ...scene, parts: [{ ...part, geometry: geometry.clone() }] }, + }), + ).toThrow(EditConflict); document.undo('sculpt-tab'); const base = document.version; document.apply('another-tab', { From 38b8d50a72efdc5ef148780b1b894a56370b1da2 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 13:15:29 -0800 Subject: [PATCH 39/40] (fix) Resume shared edits after event stream reconnect failures --- src/core/live.ts | 56 +++++++++++++++++++++++++++++++++---------- tests/e2e/mcp.spec.ts | 37 +++++++++++++++++++++++++++- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index e79c6d1..20cab72 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -115,6 +115,7 @@ export function joinLiveSession() { let source: EventSource | null = null; let streamRetry: number | undefined; let streamRetryDelay = firstStreamRetry; + let refreshingSnapshot = false; const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); @@ -129,6 +130,7 @@ export function joinLiveSession() { } | null = null; let latest: Message | null = null; let streamGeneration = 0; + let snapshotLoad: AbortController | null = null; let receiving = false; let pumping = false; let applyingRemote = false; @@ -163,6 +165,12 @@ export function joinLiveSession() { const unsentEdits = () => (dirtyEdit ? [...edits, dirtyEdit] : edits); + const invalidateSnapshot = () => { + streamGeneration++; + latest = null; + snapshotLoad?.abort(); + }; + useSharedSculptQueueGuard((geometry) => { if (!connected) return false; const queued = [activeEdit?.edit, acceptedSculpt?.edit, ...edits].flatMap((edit) => @@ -227,14 +235,17 @@ export function joinLiveSession() { void pump(); }); - const load = async (message: Message) => { + const load = async (message: Message, signal: AbortSignal) => { for (const [key, layout] of Object.entries(message.geometries)) { if (meshes.has(key)) continue; - const response = await fetch(`live/geometry/${encodeURIComponent(key)}`); - // The scene has already moved on from this mesh, and a newer message is on its way. - if (response.status === 404) return false; + const response = await fetch(`live/geometry/${encodeURIComponent(key)}`, { signal }).catch( + () => null, + ); + // The mesh may be temporarily unavailable or gone from the latest scene. + if (!response || response.status === 404 || response.status >= 500) return false; if (!response.ok) throw new Error(`${host} did not send a mesh.`); - const body = await response.blob(); + const body = await response.blob().catch(() => null); + if (!body) return false; validateLayout(layout, 0, body.size); const geometry = await readGeometry(body, layout); geometry.uuid = key; @@ -333,6 +344,7 @@ export function joinLiveSession() { const [undo, redo] = message.history[client] ?? [0, 0]; window.clearTimeout(streamRetry); streamRetry = undefined; + refreshingSnapshot = false; if (ownReplacement || changedScene || !unsent.length) streamRetryDelay = firstStreamRetry; if (!connected) { connected = true; @@ -366,11 +378,18 @@ export function joinLiveSession() { const message = latest; latest = null; const generation = streamGeneration; + const controller = new AbortController(); + snapshotLoad = controller; try { - if ((await load(message)) && !closed && generation === streamGeneration) apply(message); + const loaded = await load(message, controller.signal); + if (closed || generation !== streamGeneration) continue; + if (loaded) apply(message); + else if (!latest) refreshStream(); } catch (error) { if (!closed && generation === streamGeneration) notify(`The shared scene stopped updating. ${(error as Error).message}`); + } finally { + snapshotLoad = null; } } } finally { @@ -415,7 +434,7 @@ export function joinLiveSession() { }; const lost = () => { - if (closed) return; + if (closed || useEditor.getState().liveStatus === 'disconnected') return; connected = false; awaitedHistory = null; useSharedHistory(null); @@ -428,8 +447,8 @@ export function joinLiveSession() { // The old stream may still have a snapshot from before the request was applied. source?.close(); source = null; - streamGeneration++; - latest = null; + invalidateSnapshot(); + refreshingSnapshot = true; lost(); window.clearTimeout(streamRetry); streamRetry = window.setTimeout(() => { @@ -559,7 +578,19 @@ export function joinLiveSession() { } }; + const needsSnapshot = () => + !!( + refreshingSnapshot || + activeEdit || + dirtyEdit || + edits.length || + requests.length || + (confirmed && awaited > confirmed.version) + ); + const pump = async () => { + if (!closed && !connected && source?.readyState === EventSource.CLOSED && needsSnapshot()) + refreshStream(); if (pumping) return; pumping = true; try { @@ -612,12 +643,12 @@ export function joinLiveSession() { if (!closed && source === stream) useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }); }); - // EventSource reconnects automatically when the event stream itself fails. + // A native retry leaves the stream CONNECTING. A terminal error needs a new EventSource. stream.onerror = () => { if (closed || source !== stream) return; - streamGeneration++; - latest = null; + invalidateSnapshot(); lost(); + void pump(); }; } openStream(); @@ -627,6 +658,7 @@ export function joinLiveSession() { closed = true; window.clearTimeout(streamRetry); source?.close(); + invalidateSnapshot(); unsubscribe(); useSharedSculptQueueGuard(null); useSharedHistory(null); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index b6f3e9b..5c1a67d 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -643,6 +643,32 @@ async function captureStaleSharedStream(page: Page) { }); } +test('recovers a shared scene after a mesh download fails during initial sync', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Shared block', shapes: [{ type: 'box', size: [8, 6, 4] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + const attempts: string[] = []; + let streams = 0; + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 2) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); + await page.route(/\/live\/geometry\//, async (route) => { + if (route.request().method() !== 'GET') return route.continue(); + attempts.push(route.request().url()); + if (attempts.length !== 1) return route.continue(); + await route.fulfill({ status: 502, body: 'Mesh temporarily unavailable.' }); + }); + await page.goto(url); + await expect(page.locator(part('Shared block'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(attempts).toEqual([attempts[0], attempts[0]]); + expect(streams).toBe(3); +}); + for (const replyOrder of [ 'HTTP first', 'stream first', @@ -650,12 +676,20 @@ for (const replyOrder of [ 'HTTP error then refreshed stream', 'HTTP rejection', 'mesh upload 502', + 'mesh upload 502 followed by stream 502', ] as const) { test(`keeps sculpt and Save scoped to the right scene with ${replyOrder}`, async ({ page }) => { const holdResponse = replyOrder.startsWith('stream'); const httpError = replyOrder.includes('HTTP error'); const rejected = replyOrder === 'HTTP rejection'; - const uploadError = replyOrder === 'mesh upload 502'; + const uploadError = replyOrder.startsWith('mesh upload'); + const streamError = replyOrder === 'mesh upload 502 followed by stream 502'; + let streams = 0; + if (streamError) + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 2) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); await page.addInitScript(() => { const NativeEventSource = window.EventSource; let connections = 0; @@ -798,6 +832,7 @@ for (const replyOrder of [ } expect((await acceptedStroke)?.ok()).toBe(true); if (uploadError) expect(uploads.slice(0, 2)).toEqual([uploads[0], uploads[0]]); + if (streamError) expect(streams).toBe(3); await expect(prompt).toBeVisible(); const download = page.waitForEvent('download'); await page.keyboard.press('Escape'); From a48346039080111a153a2114909c1702799e7708 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 13:27:59 -0800 Subject: [PATCH 40/40] (fix) Reconnect shared scenes after terminal stream errors --- src/core/live.ts | 20 ++-------- tests/e2e/mcp.spec.ts | 87 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/src/core/live.ts b/src/core/live.ts index 20cab72..706b2c1 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -115,7 +115,6 @@ export function joinLiveSession() { let source: EventSource | null = null; let streamRetry: number | undefined; let streamRetryDelay = firstStreamRetry; - let refreshingSnapshot = false; const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); @@ -344,7 +343,6 @@ export function joinLiveSession() { const [undo, redo] = message.history[client] ?? [0, 0]; window.clearTimeout(streamRetry); streamRetry = undefined; - refreshingSnapshot = false; if (ownReplacement || changedScene || !unsent.length) streamRetryDelay = firstStreamRetry; if (!connected) { connected = true; @@ -448,7 +446,6 @@ export function joinLiveSession() { source?.close(); source = null; invalidateSnapshot(); - refreshingSnapshot = true; lost(); window.clearTimeout(streamRetry); streamRetry = window.setTimeout(() => { @@ -578,19 +575,7 @@ export function joinLiveSession() { } }; - const needsSnapshot = () => - !!( - refreshingSnapshot || - activeEdit || - dirtyEdit || - edits.length || - requests.length || - (confirmed && awaited > confirmed.version) - ); - const pump = async () => { - if (!closed && !connected && source?.readyState === EventSource.CLOSED && needsSnapshot()) - refreshStream(); if (pumping) return; pumping = true; try { @@ -646,9 +631,12 @@ export function joinLiveSession() { // A native retry leaves the stream CONNECTING. A terminal error needs a new EventSource. stream.onerror = () => { if (closed || source !== stream) return; + if (stream.readyState === EventSource.CLOSED) { + refreshStream(); + return; + } invalidateSnapshot(); lost(); - void pump(); }; } openStream(); diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 5c1a67d..7fd0473 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -669,6 +669,93 @@ test('recovers a shared scene after a mesh download fails during initial sync', expect(streams).toBe(3); }); +test('reconnects when the first shared event stream request returns 502', async ({ page }) => { + await call('add_parts', { parts: [model[0]] }); + const { url } = await call('open_live_view', { open_browser: false }); + let streams = 0; + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 1) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); + + await page.goto(url); + await expect(page.locator(part('Agent base'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(streams).toBe(2); +}); + +async function initialSceneEvent(url: string) { + const stream = new AbortController(); + try { + const response = await fetch(new URL('live/events', url), { + signal: AbortSignal.any([stream.signal, AbortSignal.timeout(5000)]), + }); + if (!response.ok || !response.body) throw new Error('Could not read the first scene event.'); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + let body = ''; + for (;;) { + const chunk = await reader.read(); + if (chunk.done) throw new Error('The stream ended before its first scene event.'); + body += chunk.value; + const end = body.indexOf('\n\n'); + if (end >= 0) return body.slice(0, end + 2); + } + } finally { + stream.abort(); + } +} + +for (const idle of [false, true]) { + test(`recovers a terminal native reconnect ${idle ? 'while idle' : 'while loading the first mesh'}`, async ({ + page, + }) => { + await call('new_scene', { name: 'Initial shared scene' }); + if (!idle) await call('add_parts', { parts: [model[0]] }); + const { url } = await call('open_live_view', { open_browser: false }); + const initial = await initialSceneEvent(url); + let streams = 0; + let firstMeshAborted = false; + const meshReads: string[] = []; + await page.route(/\/live\/events$/, async (route) => { + if (++streams === 1) + return route.fulfill({ contentType: 'text/event-stream', body: `retry: 100\n${initial}` }); + if (streams === 2) + return route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + return route.continue(); + }); + if (!idle) { + await page.route(/\/live\/geometry\//, async (route) => { + const request = route.request(); + if (request.method() !== 'GET') return route.continue(); + meshReads.push(request.url()); + if (meshReads.length !== 1) return route.continue(); + // The first response stays pending until the disconnect aborts the browser's fetch. + const failed = await page + .waitForEvent('requestfailed', { + predicate: (failed) => failed === request, + timeout: 3000, + }) + .catch(() => null); + firstMeshAborted = !!failed; + await route.abort().catch(() => {}); + }); + } + + await page.goto(url); + if (idle) { + await expect(page.getByText('Initial shared scene').first()).toBeVisible(); + await call('add_parts', { parts: [model[0]] }); + } + await expect(page.locator(part('Agent base'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(streams).toBe(3); + if (!idle) { + expect(firstMeshAborted).toBe(true); + expect(meshReads).toEqual([meshReads[0], meshReads[0]]); + } + }); +} + for (const replyOrder of [ 'HTTP first', 'stream first',