diff --git a/.gitignore b/.gitignore index 1f93e4f..945de90 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ node_modules/ # Next.js .next/ +.next-dev/ .next-export/ out/ build/ diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 03ded85..1a026b0 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -8,6 +8,10 @@ const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? " const nextConfig: NextConfig = { devIndicators: false, + // Keep the live development compiler isolated from `next build`. Sharing + // `.next` lets a production verification build invalidate chunks used by a + // running dev server, which also breaks API routes such as project snapshots. + distDir: isStaticExport ? ".next-export" : process.env.NODE_ENV === "development" ? ".next-dev" : ".next", allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins], env: { NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false", @@ -29,7 +33,6 @@ const nextConfig: NextConfig = { ...(isStaticExport ? { output: "export" as const, - distDir: ".next-export", trailingSlash: true, } : {}), diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index da4d7fb..4f76b80 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -2837,6 +2837,11 @@ button { cursor: default; } +.workplane-wrap.ruler-move-mode .three-workplane-host, +.workplane-wrap.ruler-move-mode .three-workplane-host:active { + cursor: default; +} + .workplane-wrap.modifier-edge-pick .three-workplane-host, .workplane-wrap.modifier-edge-pick .three-workplane-host:active { cursor: crosshair; @@ -2901,6 +2906,16 @@ button { transition: fill 120ms ease, stroke 120ms ease, filter 120ms ease; } +.ruler-overlay.move-mode .ruler-point { + cursor: grab; +} + +.ruler-overlay.move-mode .ruler-point:active { + cursor: grabbing; + fill: #dff7ff; + filter: drop-shadow(0 0 4px rgba(0, 143, 190, 0.4)); +} + .ruler-overlay.delete-mode .ruler-segment-group:hover .ruler-segment { stroke: #dc3f36; stroke-width: 3; @@ -2925,6 +2940,17 @@ button { pointer-events: none; } +.ruler-hover-edge { + fill: none; + stroke: #00aeea; + stroke-width: 4; + stroke-linecap: round; + stroke-linejoin: round; + vector-effect: non-scaling-stroke; + filter: drop-shadow(0 0 3px rgba(0, 174, 234, 0.48)); + pointer-events: none; +} + .ruler-label { position: absolute; z-index: 2; diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 76cbb41..e1fca10 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -3,6 +3,7 @@ import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; +import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; import { createLocalId } from "@/lib/localIds"; import { importExtensionSupported } from "@/lib/stlImport"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; @@ -34,10 +35,16 @@ type StoredDashboardProject = Partial & { type ProjectShapeCacheEntry = { revision: number; shapes: WorkplaneShape[]; + history: EditorHistoryEntry[]; + historyIndex: number; }; -type ProjectShapeRecord = ProjectShapeCacheEntry & { +type ProjectShapeRecord = { id: string; + revision: number; + shapes: WorkplaneShape[]; + history?: EditorHistoryEntry[]; + historyIndex?: number; updatedAt: number; }; @@ -57,6 +64,21 @@ function formatUpdated(timestamp: number) { return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(new Date(timestamp)); } +function projectShapeCacheEntry( + revision: number, + shapes: WorkplaneShape[], + history?: EditorHistoryEntry[], + historyIndex?: number, +): ProjectShapeCacheEntry { + const hydrated = hydrateEditorHistoryState(shapes, history, historyIndex); + return { + revision, + shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes, + history: hydrated.entries, + historyIndex: hydrated.index, + }; +} + function openProjectShapesDb() { return new Promise((resolve, reject) => { if (typeof window === "undefined" || !window.indexedDB) { @@ -91,7 +113,7 @@ async function loadProjectShapes(projectId: string) { }); } -async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], revision: number) { +async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry) { const database = await openProjectShapesDb(); return new Promise((resolve, reject) => { const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite"); @@ -102,10 +124,10 @@ async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], re }; existingRequest.onsuccess = () => { const existing = existingRequest.result as ProjectShapeRecord | undefined; - if (existing && existing.revision > revision) { + if (existing && existing.revision > entry.revision) { return; } - store.put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord); + store.put({ id: projectId, ...entry, updatedAt: Date.now() } satisfies ProjectShapeRecord); }; transaction.oncomplete = () => { database.close(); @@ -151,7 +173,7 @@ function readStoredProjects() { const revision = typeof project.revision === "number" ? project.revision : updatedAt; const designShapes = Array.isArray(project.designShapes) ? (project.designShapes as WorkplaneShape[]) : null; if (designShapes) { - legacyShapes[id] = { revision, shapes: designShapes }; + legacyShapes[id] = projectShapeCacheEntry(revision, designShapes); } return { id, @@ -272,7 +294,7 @@ export default function Home() { if (Object.keys(legacyShapes).length > 0) { setProjectShapesById(legacyShapes); Object.entries(legacyShapes).forEach(([projectId, entry]) => { - void saveProjectShapes(projectId, entry.shapes, entry.revision).catch(() => { + void saveProjectShapes(projectId, entry).catch(() => { setDashboardNotice("Could not migrate project shapes to larger storage"); }); }); @@ -348,12 +370,10 @@ export default function Home() { .then((record) => { if (canceled) return; const revision = activeProject.revision ?? record?.revision ?? Date.now(); + const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex); setProjectShapesById((current) => ({ ...current, - [activeProjectId]: { - revision, - shapes: record?.shapes ?? [], - }, + [activeProjectId]: entry, })); }) .catch((error) => { @@ -361,10 +381,7 @@ export default function Home() { setDashboardNotice(error instanceof Error ? error.message : "Could not load project shapes"); setProjectShapesById((current) => ({ ...current, - [activeProjectId]: { - revision: activeProject.revision ?? Date.now(), - shapes: [], - }, + [activeProjectId]: projectShapeCacheEntry(activeProject.revision ?? Date.now(), []), })); } }); @@ -449,9 +466,15 @@ export default function Home() { }); }, []); - const updateProjectShapes = useCallback((snapshot: { projectId: string; shapes: WorkplaneShape[] }) => { + const updateProjectShapes = useCallback((snapshot: { + projectId: string; + shapes: WorkplaneShape[]; + history: EditorHistoryEntry[]; + historyIndex: number; + }) => { const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1); nextProjectRevisionRef.current = revision; + const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex); setProjectShapesById((current) => { const existing = current[snapshot.projectId]; if (existing && existing.revision > revision) { @@ -459,12 +482,12 @@ export default function Home() { } return { ...current, - [snapshot.projectId]: { revision, shapes: snapshot.shapes }, + [snapshot.projectId]: entry, }; }); const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve(); - const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, snapshot.shapes, revision)); + const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, entry)); projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave; void queuedSave @@ -519,9 +542,9 @@ export default function Home() { const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length); setProjectShapesById((current) => ({ ...current, - [project.id]: { revision: project.revision ?? project.updatedAt, shapes: [] }, + [project.id]: projectShapeCacheEntry(project.revision ?? project.updatedAt, []), })); - void saveProjectShapes(project.id, [], project.revision ?? project.updatedAt).catch(() => { + void saveProjectShapes(project.id, projectShapeCacheEntry(project.revision ?? project.updatedAt, [])).catch(() => { setDashboardNotice("Could not prepare project shape storage"); }); setProjects((current) => [project, ...current]); @@ -542,10 +565,11 @@ export default function Home() { : importedShapeFromStl(file.name, await file.arrayBuffer()); const project = newProject(projectNameFromFileName(file.name), projects.length, 1); const revision = project.revision ?? project.updatedAt; - await saveProjectShapes(project.id, [shape], revision); + const entry = projectShapeCacheEntry(revision, [shape]); + await saveProjectShapes(project.id, entry); setProjectShapesById((current) => ({ ...current, - [project.id]: { revision, shapes: [shape] }, + [project.id]: entry, })); setDashboardNotice(`Imported ${file.name}`); setProjects((current) => [project, ...current]); @@ -674,6 +698,8 @@ export default function Home() {
[edge.id, edge])); const selected = new Set([startId]); const queue = [startId]; - const tolerance = 0.025; + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + edges.forEach((edge) => { + for (let index = 0; index + 2 < edge.points.length; index += 3) { + minX = Math.min(minX, edge.points[index]); + minY = Math.min(minY, edge.points[index + 1]); + minZ = Math.min(minZ, edge.points[index + 2]); + maxX = Math.max(maxX, edge.points[index]); + maxY = Math.max(maxY, edge.points[index + 1]); + maxZ = Math.max(maxZ, edge.points[index + 2]); + } + }); + const diagonal = [minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite) + ? Math.hypot(maxX - minX, maxY - minY, maxZ - minZ) + : 1; + const tolerance = Math.max(1e-6, Math.min(0.01, diagonal * 1e-5)); while (queue.length > 0) { const id = queue.shift() as number; const edge = edgeById.get(id); @@ -1218,7 +1241,7 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI } function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) { - return edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle; + return edge.display && edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle; } function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) { @@ -1296,17 +1319,29 @@ function shapeWithEdgeTreatmentRecord( }, ], edgeTreatmentHistory: [ - ...(before.edgeTreatmentHistory ?? []), + ...compactEdgeTreatmentHistory(before.edgeTreatmentHistory), { id: createLocalId("edge-history"), createdAt, feature, before: cloneWorkplaneShapeSnapshot(before), + appliedFrame: edgeTreatmentAppliedFrame(shape), }, ], }); } +function bakedEdgeTreatmentPreview(shape: WorkplaneShape, base: WorkplaneShape) { + if (!base.groupedShapes?.length) return shape; + return canonicalizeShape({ + ...shape, + groupedShapes: undefined, + groupedBaseWidth: undefined, + groupedBaseDepth: undefined, + groupedBaseHeight: undefined, + }); +} + function shapeCenterDistance(a: WorkplaneShape, b: WorkplaneShape) { const ax = a.x; const ay = (a.elevation ?? 0) + a.height / 2; @@ -1410,7 +1445,7 @@ function groupedShapeWithComponentEdgeTreatment( ...preview, edgeResizeMode: session.preserveEdgeSize ? "preserve" : "scale", edgeTreatments: base.edgeTreatments, - edgeTreatmentHistory: base.edgeTreatmentHistory, + edgeTreatmentHistory: base.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(base.edgeTreatmentHistory) : undefined, groupedBaseWidth: shapeWidth(preview), groupedBaseDepth: shapeDepth(preview), groupedBaseHeight: preview.height, @@ -1479,9 +1514,13 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[] ...rebuilt.group, id: shape.id, name: shape.name, + color: shape.color, hole: shape.hole || rebuilt.group.hole, locked: shape.locked, hidden: shape.hidden, + edgeResizeMode: shape.edgeResizeMode, + edgeTreatments: shape.edgeTreatments, + edgeTreatmentHistory: shape.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(shape.edgeTreatmentHistory) : undefined, }), label: restoredChild.label, }; @@ -1575,8 +1614,7 @@ function cylinderMesh(shape: WorkplaneShape, sides = 96, topRadiusScale = 1): Me } function sphereMesh(shape: WorkplaneShape): MeshData { - const lat = 12; - const lon = 32; + const { widthSegments: lon, heightSegments: lat } = sphereTessellation(shape.steps); const width = shapeWidth(shape); const depth = shapeDepth(shape); const height = shape.height; @@ -1869,7 +1907,7 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null { geometry.scale(width / 2, 1, depth / 2); break; case "sphere": - geometry = new THREE.SphereGeometry(1, Math.max(8, (shape.steps ?? 24) * 2), Math.max(6, shape.steps ?? 24)); + geometry = new THREE.SphereGeometry(1, sphereTessellation(shape.steps).widthSegments, sphereTessellation(shape.steps).heightSegments); geometry.scale(width / 2, height / 2, depth / 2); break; case "cone": { @@ -3725,9 +3763,10 @@ function primitiveManifoldForShape(runtime: ManifoldToplevel, shape: WorkplaneSh } if (shape.kind === "sphere") { + const { widthSegments } = sphereTessellation(shape.steps); return transformedPrimitiveManifold( runtime, - runtime.Manifold.sphere(1, shape.sides ?? 32), + runtime.Manifold.sphere(1, widthSegments), primitiveTransformMatrix(shape, new THREE.Vector3(width / 2, height / 2, depth / 2)), created, ); @@ -4938,62 +4977,10 @@ function readMcpEditorIdentity() { return identity; } -function projectShapesFingerprint(shapes: WorkplaneShape[]) { - return shapes - .map((shape, index) => - [ - compactShapeSummary(shape, index), - `id${shape.id}`, - `n${shape.name}`, - `clr${shape.color}`, - `txt${shape.text ?? ""}`, - `mesh${shape.importedMesh?.positions.length ?? 0}:${shape.importedMesh?.normals?.length ?? 0}`, - `cadFrame${shape.cadBrepFrame ? JSON.stringify({ - x: Number(shape.cadBrepFrame.x.toFixed(6)), - z: Number(shape.cadBrepFrame.z.toFixed(6)), - elevation: Number(shape.cadBrepFrame.elevation.toFixed(6)), - width: Number(shape.cadBrepFrame.width.toFixed(6)), - depth: Number(shape.cadBrepFrame.depth.toFixed(6)), - height: Number(shape.cadBrepFrame.height.toFixed(6)), - sourceTransform: shape.cadBrepFrame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null, - }) : ""}`, - `primitiveFrame${shape.cadPrimitiveFrame ? JSON.stringify({ - kind: shape.cadPrimitiveFrame.kind, - width: Number(shape.cadPrimitiveFrame.width.toFixed(6)), - depth: Number(shape.cadPrimitiveFrame.depth.toFixed(6)), - height: Number(shape.cadPrimitiveFrame.height.toFixed(6)), - frame: { - x: Number(shape.cadPrimitiveFrame.frame.x.toFixed(6)), - z: Number(shape.cadPrimitiveFrame.frame.z.toFixed(6)), - elevation: Number(shape.cadPrimitiveFrame.frame.elevation.toFixed(6)), - width: Number(shape.cadPrimitiveFrame.frame.width.toFixed(6)), - depth: Number(shape.cadPrimitiveFrame.frame.depth.toFixed(6)), - height: Number(shape.cadPrimitiveFrame.frame.height.toFixed(6)), - sourceTransform: shape.cadPrimitiveFrame.frame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null, - }, - }) : ""}`, - `sketch${shape.sketchProfile ? JSON.stringify({ - points: shape.sketchProfile.points, - segments: shape.sketchProfile.segments, - images: (shape.sketchProfile.images ?? []).map((image) => ({ - id: image.id, - name: image.name, - x: image.x, - z: image.z, - width: image.width, - depth: image.depth, - opacity: image.opacity, - lockAspect: image.lockAspect, - sourceLength: image.dataUrl.length, - })), - }) : ""}`, - ].join(","), - ) - .join(";"); -} - export function SketchForgeEditor({ initialShapes = [], + initialHistory, + initialHistoryIndex, initialSnap, initialWorkspace, onHome, @@ -5005,22 +4992,37 @@ export function SketchForgeEditor({ projectRevision = 0, }: { initialShapes?: WorkplaneShape[]; + initialHistory?: EditorHistoryEntry[]; + initialHistoryIndex?: number; initialSnap?: GridSize; initialWorkspace?: WorkplaneWorkspaceSettings; onHome?: () => void; - onProjectShapesChange?: (snapshot: { projectId: string; shapes: WorkplaneShape[] }) => void; + onProjectShapesChange?: (snapshot: { + projectId: string; + shapes: WorkplaneShape[]; + history: EditorHistoryEntry[]; + historyIndex: number; + }) => void; onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void; onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void; projectId?: string | null; projectName?: string; projectRevision?: number; } = {}) { - const [shapes, setShapes] = useState(() => initialShapes.map(canonicalizeShape)); + const initialSceneRef = useRef(null); + if (initialSceneRef.current === null) { + initialSceneRef.current = initialShapes.map(canonicalizeShape); + } + const initialHistoryStateRef = useRef(null); + if (initialHistoryStateRef.current === null) { + initialHistoryStateRef.current = hydrateEditorHistoryState(initialSceneRef.current, initialHistory, initialHistoryIndex); + } + const [shapes, setShapes] = useState(() => initialSceneRef.current as WorkplaneShape[]); const [selectedIds, setSelectedIds] = useState([]); const [clipboard, setClipboard] = useState([]); const [systemClipboardSupported, setSystemClipboardSupported] = useState(false); - const [history, setHistory] = useState([[]]); - const [historyIndex, setHistoryIndex] = useState(0); + const [history, setHistory] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).entries); + const [historyIndex, setHistoryIndex] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).index); const [placementElevation, setPlacementElevation] = useState(0); const [workspaceSettings, setWorkspaceSettings] = useState(() => normalizeWorkspaceSettings(initialWorkspace)); const [workplaneMode, setWorkplaneMode] = useState(false); @@ -5051,6 +5053,7 @@ export function SketchForgeEditor({ const noticeRef = useRef(notice); const projectInfoRef = useRef({ projectId: projectId ?? null, projectName }); const historyIndexRef = useRef(historyIndex); + const historyRef = useRef(history); const interactionHistoryStartRef = useRef(""); const interactionHistoryChangedRef = useRef(false); const interactionHistoryTimerRef = useRef(null); @@ -5061,6 +5064,8 @@ export function SketchForgeEditor({ const [sketchProfile, setSketchProfile] = useState(() => emptySketchProfile()); const [sketchHistory, setSketchHistory] = useState([emptySketchProfile()]); const [sketchHistoryIndex, setSketchHistoryIndex] = useState(0); + const sketchHistoryRef = useRef(sketchHistory); + const sketchHistoryIndexRef = useRef(sketchHistoryIndex); const [sketchActivePointId, setSketchActivePointId] = useState(null); const [sketchSelection, setSketchSelection] = useState(null); const [sketchMeasureStart, setSketchMeasureStart] = useState(null); @@ -5179,6 +5184,8 @@ export function SketchForgeEditor({ selectedEdgeIds: [], busy: false, prepared: true, + preview: null, + componentPreviews: [], error: message.selectableEdgeIds.length ? null : "No sharp manifold edges were found at this threshold", } : current); if (message.selectableEdgeIds.length) setNotice("Select highlighted edges, then adjust the preview"); @@ -5238,12 +5245,19 @@ export function SketchForgeEditor({ const invalidateCadModifierSession = useCallback(() => { const wasActive = cadModifierBaseShapeRef.current !== null; if (!wasActive) return false; + const hadInFlightRequest = cadModifierWatchdogRef.current !== null; clearCadModifierWatchdog(); const requestId = cadModifierRequestRef.current + 1; cadModifierRequestRef.current = requestId; cadModifierLatestPreviewRef.current = requestId; cadModifierPrepareRef.current = requestId; - cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest); + if (hadInFlightRequest) { + cadModifierWorkerRef.current?.terminate(); + cadModifierWorkerRef.current = null; + cadModifierWorkerRestartRef.current(); + } else { + cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest); + } cadModifierBaseShapeRef.current = null; cadModifierBaseFingerprintRef.current = ""; cadModifierSourcePartsRef.current = []; @@ -5303,6 +5317,14 @@ export function SketchForgeEditor({ useEffect(() => { selectedIdsRef.current = selectedIds; + const currentHistory = historyRef.current; + const currentIndex = Math.min(historyIndexRef.current, Math.max(0, currentHistory.length - 1)); + const currentEntry = currentHistory[currentIndex]; + if (currentEntry && currentEntry.selectedIds.join("\0") !== selectedIds.join("\0")) { + const updated = currentHistory.map((entry, index) => index === currentIndex ? { ...entry, selectedIds: [...selectedIds] } : entry); + historyRef.current = updated; + setHistory(updated); + } }, [selectedIds]); useEffect(() => { @@ -5321,6 +5343,18 @@ export function SketchForgeEditor({ historyIndexRef.current = historyIndex; }, [historyIndex]); + useEffect(() => { + historyRef.current = history; + }, [history]); + + useEffect(() => { + sketchHistoryRef.current = sketchHistory; + }, [sketchHistory]); + + useEffect(() => { + sketchHistoryIndexRef.current = sketchHistoryIndex; + }, [sketchHistoryIndex]); + useEffect(() => { edgeModifierRef.current = edgeModifier; }, [edgeModifier]); @@ -5351,7 +5385,7 @@ export function SketchForgeEditor({ ); const toggleModifierEdge = useCallback((id: number, singleEdge = false) => { setEdgeModifier((current) => { - if (!current) return current; + if (!current || current.busy) return current; const allowed = new Set(current.edges.filter((edge) => selectableCadModifierEdge(edge, current.sharpAngle)).map((edge) => edge.id)); if (!allowed.has(id)) return current; const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id]; @@ -5462,13 +5496,30 @@ export function SketchForgeEditor({ projectSyncTimerRef.current = window.setTimeout(() => { lastProjectShapesSyncRef.current = serialized; lastProjectShapesEchoRef.current = serialized; - onProjectShapesChange({ projectId, shapes: canonicalNext }); + onProjectShapesChange({ + projectId, + shapes: canonicalNext, + history: historyRef.current, + historyIndex: historyIndexRef.current, + }); projectSyncTimerRef.current = null; }, 120); }, [onProjectShapesChange, projectId], ); + const appendHistorySnapshot = useCallback((nextShapes: WorkplaneShape[], nextSelection: string[]) => { + const entry = editorHistoryEntry(nextShapes, nextSelection); + const result = appendEditorHistorySnapshot(historyRef.current, historyIndexRef.current, entry); + if (result.entries !== historyRef.current) { + historyRef.current = result.entries; + setHistory(result.entries); + } + historyIndexRef.current = result.index; + setHistoryIndex(result.index); + return result.changed; + }, []); + const finalizeInteractionHistory = useCallback(() => { const startFingerprint = interactionHistoryStartRef.current; const hadChanges = interactionHistoryChangedRef.current; @@ -5484,22 +5535,8 @@ export function SketchForgeEditor({ return; } - setHistory((current) => { - const historyIndex = Math.min(historyIndexRef.current, Math.max(0, current.length - 1)); - const trimmed = current.slice(0, historyIndex + 1); - const latestHistory = trimmed.at(-1) ?? []; - if (projectShapesFingerprint(latestHistory) === nextFingerprint) { - historyIndexRef.current = Math.max(0, trimmed.length - 1); - setHistoryIndex(historyIndexRef.current); - return trimmed; - } - - const nextHistory = [...trimmed, canonicalNext]; - historyIndexRef.current = nextHistory.length - 1; - setHistoryIndex(historyIndexRef.current); - return nextHistory; - }); - }, []); + appendHistorySnapshot(canonicalNext, selectedIdsRef.current); + }, [appendHistorySnapshot]); useEffect(() => { if (projectInteractionActive || !pendingProjectShapesRef.current) { @@ -5517,6 +5554,7 @@ export function SketchForgeEditor({ if (interactionHistoryTimerRef.current !== null) { window.clearTimeout(interactionHistoryTimerRef.current); interactionHistoryTimerRef.current = null; + finalizeInteractionHistory(); } if (!projectInteractionActiveRef.current) { interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current); @@ -5557,20 +5595,18 @@ export function SketchForgeEditor({ const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : []; const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id)); shapesRef.current = canonicalNext; + selectedIdsRef.current = validSelection; setShapes(canonicalNext); setSelectedIds(validSelection); - setHistory((current) => { - const trimmed = current.slice(0, historyIndex + 1); - historyIndexRef.current = trimmed.length; - setHistoryIndex(historyIndexRef.current); - return [...trimmed, canonicalNext]; - }); + const changed = appendHistorySnapshot(canonicalNext, validSelection); if (message) { setNotice(message); } - syncProjectShapes(canonicalNext); + if (changed) { + syncProjectShapes(canonicalNext); + } }, - [historyIndex, selectedIds, syncProjectShapes], + [appendHistorySnapshot, selectedIds, syncProjectShapes], ); const removeEdgeTreatment = useCallback(async (optionId: string) => { @@ -5587,32 +5623,46 @@ export function SketchForgeEditor({ setNotice("Choose an edge feature to remove"); return; } + const sourceFingerprint = projectShapesFingerprint([selectedShape]); + const sourceProjectId = projectInfoRef.current.projectId; const restored = await restoreEdgeTreatmentInShape(selectedShape, option.path, option.entryId); if (!restored) { setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove"); return; } + const currentTarget = shapesRef.current.find((shape) => shape.id === selectedShape.id); + if (projectInfoRef.current.projectId !== sourceProjectId || !currentTarget || projectShapesFingerprint([currentTarget]) !== sourceFingerprint) { + setNotice("The object changed while removing the edge feature; try again"); + return; + } invalidateCadModifierSession(); commitShapes( - shapes.map((shape) => shape.id === selectedShape.id ? restored.shape : shape), + shapesRef.current.map((shape) => shape.id === selectedShape.id ? restored.shape : shape), restored.shape.id, `Removed ${restored.label}`, ); setNotice(`Removed ${restored.label}`); - }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape, shapes]); + }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape]); const commitSketchProfile = useCallback( (next: SketchProfile, message?: string) => { const snapshot = cloneSketchProfile(next); + const current = sketchHistoryRef.current; + const currentIndex = Math.min(sketchHistoryIndexRef.current, Math.max(0, current.length - 1)); + const trimmed = current.slice(0, currentIndex + 1); + const latest = trimmed.at(-1); setSketchProfile(snapshot); - setSketchHistory((current) => { - const trimmed = current.slice(0, sketchHistoryIndex + 1); - return [...trimmed, cloneSketchProfile(snapshot)]; - }); - setSketchHistoryIndex(sketchHistoryIndex + 1); + if (latest && JSON.stringify(latest) === JSON.stringify(snapshot)) { + return; + } + const nextHistory = [...trimmed, cloneSketchProfile(snapshot)].slice(-MAX_SKETCH_HISTORY_ENTRIES); + sketchHistoryRef.current = nextHistory; + sketchHistoryIndexRef.current = nextHistory.length - 1; + setSketchHistory(nextHistory); + setSketchHistoryIndex(sketchHistoryIndexRef.current); if (message) setNotice(message); }, - [sketchHistoryIndex], + [], ); const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => { @@ -5621,7 +5671,10 @@ export function SketchForgeEditor({ setSketchActive(true); setSketchTool(profile?.segments.length ? "select" : "line"); setSketchProfile(initial); - setSketchHistory([cloneSketchProfile(initial)]); + const initialHistory = [cloneSketchProfile(initial)]; + sketchHistoryRef.current = initialHistory; + sketchHistoryIndexRef.current = 0; + setSketchHistory(initialHistory); setSketchHistoryIndex(0); setSketchActivePointId(null); setSketchSelection(null); @@ -5650,30 +5703,36 @@ export function SketchForgeEditor({ }, []); const sketchUndo = useCallback(() => { - if (sketchHistoryIndex <= 0) { + const currentHistory = sketchHistoryRef.current; + const currentIndex = sketchHistoryIndexRef.current; + if (currentIndex <= 0) { setNotice("Nothing to undo in this sketch"); return; } - const nextIndex = sketchHistoryIndex - 1; + const nextIndex = currentIndex - 1; + sketchHistoryIndexRef.current = nextIndex; setSketchHistoryIndex(nextIndex); - setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); + setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile())); setSketchActivePointId(null); setSketchSelection(null); setNotice("Sketch undo"); - }, [sketchHistory, sketchHistoryIndex]); + }, []); const sketchRedo = useCallback(() => { - if (sketchHistoryIndex >= sketchHistory.length - 1) { + const currentHistory = sketchHistoryRef.current; + const currentIndex = sketchHistoryIndexRef.current; + if (currentIndex >= currentHistory.length - 1) { setNotice("Nothing to redo in this sketch"); return; } - const nextIndex = sketchHistoryIndex + 1; + const nextIndex = currentIndex + 1; + sketchHistoryIndexRef.current = nextIndex; setSketchHistoryIndex(nextIndex); - setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); + setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile())); setSketchActivePointId(null); setSketchSelection(null); setNotice("Sketch redo"); - }, [sketchHistory, sketchHistoryIndex]); + }, []); const setActiveSketchTool = useCallback((tool: SketchTool) => { setSketchTool(tool); @@ -5999,7 +6058,11 @@ export function SketchForgeEditor({ lastProjectShapesEchoRef.current = null; return; } - if (lastProjectIdRef.current !== projectId) { + if (projectInteractionActiveRef.current) { + return; + } + const projectChanged = lastProjectIdRef.current !== projectId; + if (projectChanged) { lastProjectIdRef.current = projectId; lastProjectShapesSyncRef.current = ""; lastProjectShapesEchoRef.current = null; @@ -6007,28 +6070,30 @@ export function SketchForgeEditor({ const incoming = initialShapes.map(canonicalizeShape); const incomingSerialized = projectShapesFingerprint(incoming); // The parent echoes shapes after a local save; rehydrating that echo can reset active transform state. - if (lastProjectShapesEchoRef.current !== null && incomingSerialized === lastProjectShapesEchoRef.current) { + if (!projectChanged && lastProjectShapesEchoRef.current !== null && incomingSerialized === lastProjectShapesEchoRef.current) { lastProjectShapesSyncRef.current = incomingSerialized; return; } - if (projectInteractionActiveRef.current) { - return; - } lastProjectShapesSyncRef.current = incomingSerialized; if (projectSyncTimerRef.current !== null) { window.clearTimeout(projectSyncTimerRef.current); projectSyncTimerRef.current = null; } - if (incomingSerialized === projectShapesFingerprint(shapes)) { + if (!projectChanged && incomingSerialized === projectShapesFingerprint(shapes)) { return; } + const hydratedHistory = hydrateEditorHistoryState(incoming, initialHistory, initialHistoryIndex); projectHydratingRef.current = true; + shapesRef.current = incoming; + selectedIdsRef.current = []; + historyRef.current = hydratedHistory.entries; + historyIndexRef.current = hydratedHistory.index; setShapes(incoming); setSelectedIds([]); - setHistory([incoming]); - setHistoryIndex(0); + setHistory(hydratedHistory.entries); + setHistoryIndex(hydratedHistory.index); setNotice(incoming.length ? "Project synced" : "Ready"); - }, [initialShapes, projectId, projectRevision]); + }, [initialHistory, initialHistoryIndex, initialShapes, projectId, projectInteractionActive, projectRevision]); useEffect(() => { if (!projectId || !onProjectShapesChange) { @@ -6142,6 +6207,7 @@ export function SketchForgeEditor({ }, [hasSelection, selectedShapes]); const pasteShape = useCallback(async () => { + const sourceProjectId = projectInfoRef.current.projectId; const systemClipboard = await readSystemClipboard(); const sharedClipboard = readSharedClipboard(); const sourceClipboard = systemClipboard.length > 0 ? systemClipboard : sharedClipboard.length > 0 ? sharedClipboard : clipboard; @@ -6149,6 +6215,10 @@ export function SketchForgeEditor({ setNotice("SketchForge clipboard is empty"); return; } + if (projectInfoRef.current.projectId !== sourceProjectId) { + setNotice("Paste cancelled because the project changed"); + return; + } if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) { setClipboard(sourceClipboard); } @@ -6162,38 +6232,56 @@ export function SketchForgeEditor({ }, [clipboard, commitShapes]); const undo = useCallback(() => { + if (projectInteractionActiveRef.current) { + setNotice("Finish the current drag or transform before undoing"); + return; + } const modifierCancelled = invalidateCadModifierSession(); - if (historyIndex <= 0) { + const currentHistory = historyRef.current; + const currentIndex = historyIndexRef.current; + if (currentIndex <= 0) { setNotice(modifierCancelled ? "Edge modifier cancelled" : "Nothing to undo"); return; } - const nextIndex = historyIndex - 1; - const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); + const nextIndex = currentIndex - 1; + const entry = currentHistory[nextIndex]; + const nextShapes = (entry?.shapes ?? []).map(canonicalizeShape); + const nextSelection = (entry?.selectedIds ?? []).filter((id) => nextShapes.some((shape) => shape.id === id)); historyIndexRef.current = nextIndex; shapesRef.current = nextShapes; + selectedIdsRef.current = nextSelection; setHistoryIndex(nextIndex); setShapes(nextShapes); - setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); + setSelectedIds(nextSelection); syncProjectShapes(nextShapes); setNotice(modifierCancelled ? "Edge modifier cancelled · Undo" : "Undo"); - }, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); + }, [invalidateCadModifierSession, syncProjectShapes]); const redo = useCallback(() => { - if (historyIndex >= history.length - 1) { + if (projectInteractionActiveRef.current) { + setNotice("Finish the current drag or transform before redoing"); + return; + } + const currentHistory = historyRef.current; + const currentIndex = historyIndexRef.current; + if (currentIndex >= currentHistory.length - 1) { setNotice("Nothing to redo"); return; } const modifierCancelled = invalidateCadModifierSession(); - const nextIndex = historyIndex + 1; - const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); + const nextIndex = currentIndex + 1; + const entry = currentHistory[nextIndex]; + const nextShapes = (entry?.shapes ?? []).map(canonicalizeShape); + const nextSelection = (entry?.selectedIds ?? []).filter((id) => nextShapes.some((shape) => shape.id === id)); historyIndexRef.current = nextIndex; shapesRef.current = nextShapes; + selectedIdsRef.current = nextSelection; setHistoryIndex(nextIndex); setShapes(nextShapes); - setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); + setSelectedIds(nextSelection); syncProjectShapes(nextShapes); setNotice(modifierCancelled ? "Edge modifier cancelled · Redo" : "Redo"); - }, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); + }, [invalidateCadModifierSession, syncProjectShapes]); const toggleAlignMode = useCallback(() => { if (selectedShapes.length < 2) { @@ -6325,8 +6413,22 @@ export function SketchForgeEditor({ cadModifierRequestRef.current = requestId; return new Promise((resolve, reject) => { const timer = window.setTimeout(() => { - cadModifierPendingRef.current.delete(requestId); - reject(new Error("Timed out waiting for the CAD worker")); + if (!cadModifierPendingRef.current.has(requestId)) return; + const pendingRequests = [...cadModifierPendingRef.current.values()]; + cadModifierPendingRef.current.clear(); + pendingRequests.forEach((pending) => window.clearTimeout(pending.timer)); + cadModifierWorkerRef.current?.terminate(); + cadModifierWorkerRef.current = null; + const invalidationId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = invalidationId; + cadModifierLatestPreviewRef.current = invalidationId; + cadModifierPrepareRef.current = invalidationId; + cadModifierBaseShapeRef.current = null; + cadModifierBaseFingerprintRef.current = ""; + cadModifierSourcePartsRef.current = []; + setEdgeModifier(null); + cadModifierWorkerRestartRef.current(); + pendingRequests.forEach((pending) => pending.reject(new Error("Timed out waiting for the CAD worker; the worker was restarted"))); }, timeoutMs); cadModifierPendingRef.current.set(requestId, { resolve, reject, timer }); try { @@ -6349,6 +6451,7 @@ export function SketchForgeEditor({ setNotice(`Select one unlocked solid to ${kind}`); return; } + invalidateCadModifierSession(); const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape); const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape]; @@ -6416,7 +6519,7 @@ export function SketchForgeEditor({ } cadModifierPrepareRef.current = prepareRequestId; armCadModifierWatchdog(prepareRequestId, "prepare"); - }, [armCadModifierWatchdog, postCadModifierRequest, selectedShape, selectedShapes.length]); + }, [armCadModifierWatchdog, invalidateCadModifierSession, postCadModifierRequest, selectedShape, selectedShapes.length]); const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => { if (shape.locked || shape.hole) { @@ -6468,8 +6571,10 @@ export function SketchForgeEditor({ params: Record, ) => { invalidateCadModifierSession(); + const sourceFingerprint = projectShapesFingerprint([shape]); + const sourceProjectId = projectInfoRef.current.projectId; const kind: CadModifierKind = params.kind === "fillet" ? "fillet" : "chamfer"; - const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25))); + const sharpAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, mcpNumber(params.sharpAngle, 25))); const amount = Math.max(MIN_EDGE_MODIFIER_AMOUNT, mcpNumber(params.amount, 1)); const chamferAngle = Math.max(5, Math.min(85, mcpNumber(params.chamferAngle, 45))); const quality: CadModifierQuality = params.quality === "draft" || params.quality === "fine" ? params.quality : "standard"; @@ -6529,7 +6634,21 @@ export function SketchForgeEditor({ }; const createdAt = Date.now(); const groupedModifiedShape = groupedShapeWithComponentEdgeTreatment(shape, preview, sourceParts, session, feature, createdAt); - const modifiedShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(preview, shape, feature, preserveEdgeSize, createdAt); + const modifiedShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord( + bakedEdgeTreatmentPreview(preview, shape), + shape, + feature, + preserveEdgeSize, + createdAt, + ); + const currentTarget = shapesRef.current.find((candidate) => candidate.id === shape.id); + if ( + projectInfoRef.current.projectId !== sourceProjectId || + !currentTarget || + projectShapesFingerprint([currentTarget]) !== sourceFingerprint + ) { + throw new Error("The target object or project changed while the edge treatment was running; try again"); + } commitShapes( shapesRef.current.map((candidate) => candidate.id === shape.id ? modifiedShape : candidate), modifiedShape.id, @@ -6581,7 +6700,7 @@ export function SketchForgeEditor({ createdAt, ); const modifiedShape: WorkplaneShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord( - previewShape, + bakedEdgeTreatmentPreview(previewShape, base), base, feature, edgeModifier.preserveEdgeSize, @@ -6601,7 +6720,9 @@ export function SketchForgeEditor({ if (event.key === "Escape") { event.preventDefault(); cancelEdgeModifier(); - } else if (event.key === "Enter" && edgeModifier.preview && !edgeModifier.busy && !edgeModifier.error) { + } else if (event.key === "Enter" && edgeModifier.preview && edgeModifier.selectedEdgeIds.length > 0 && !edgeModifier.busy && !edgeModifier.error) { + const target = event.target instanceof HTMLElement ? event.target : null; + if (target?.closest("input, select, textarea, button, [contenteditable='true']")) return; event.preventDefault(); applyEdgeModifier(); } @@ -6787,20 +6908,26 @@ export function SketchForgeEditor({ return; } + const sourceFingerprint = projectShapesFingerprint(shapesRef.current); + const sourceProjectId = projectInfoRef.current.projectId; const result = await buildGroupedShapeFromSelection(selectedShapes); + if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(shapesRef.current) !== sourceFingerprint) { + setNotice("The scene changed while grouping; select the objects and try again"); + return; + } const { group } = result; if (!group) { if (result.consumed) { const selected = new Set(selectedIds); - commitShapes(shapes.filter((shape) => !selected.has(shape.id)), null, "Grouped: hole consumed solid"); + commitShapes(shapesRef.current.filter((shape) => !selected.has(shape.id)), null, "Grouped: hole consumed solid"); return; } setNotice(result.failureNotice); return; } const selected = new Set(selectedIds); - commitShapes([...shapes.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`); - }, [commitShapes, selectedIds, selectedShapes, shapes]); + commitShapes([...shapesRef.current.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`); + }, [commitShapes, selectedIds, selectedShapes]); const intersectSelected = useCallback(async () => { const groupable = selectedShapes.filter((shape) => !shape.locked); @@ -6811,14 +6938,20 @@ export function SketchForgeEditor({ return; } + const sourceFingerprint = projectShapesFingerprint(shapesRef.current); + const sourceProjectId = projectInfoRef.current.projectId; const result = await buildIntersectionShapeFromSelection(groupable); + if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(shapesRef.current) !== sourceFingerprint) { + setNotice("The scene changed while intersecting; select the objects and try again"); + return; + } if (!result.group && !result.empty) { setNotice(result.failureNotice); return; } const operandIds = new Set(groupable.map((shape) => shape.id)); - const remainingShapes = shapes.filter((shape) => !operandIds.has(shape.id)); + const remainingShapes = shapesRef.current.filter((shape) => !operandIds.has(shape.id)); if (result.empty) { commitShapes(remainingShapes, null, "Intersection is empty"); return; @@ -6829,7 +6962,7 @@ export function SketchForgeEditor({ return; } commitShapes([...remainingShapes, intersection], intersection.id, `Intersected ${groupable.length} shapes`); - }, [commitShapes, selectedShapes, shapes]); + }, [commitShapes, selectedShapes]); const ungroupSelected = useCallback(() => { const groups = selectedShapes.filter((shape) => shape.groupedShapes?.length); @@ -6929,7 +7062,17 @@ export function SketchForgeEditor({ const profile = defaultMcpSketchProfile(width, depth); const extruded = shapeFromSketchProfile(profile, height); if (!extruded) throw new Error("Could not create the sketch profile"); - shape = canonicalizeShape({ ...extruded, name, color, x, z, elevation, rotation: mcpNumber(params.rotation, 0) }); + shape = canonicalizeShape({ + ...extruded, + name, + color, + x, + z, + elevation, + rotation: mcpNumber(params.rotation, 0), + rotationX: mcpNumber(params.rotationX, 0), + rotationZ: mcpNumber(params.rotationZ, 0), + }); } else if (kind === "box" || kind === "cylinder") { shape = sceneShape({ name, @@ -6950,8 +7093,9 @@ export function SketchForgeEditor({ } else { throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch"); } - commitShapes([...currentShapes(), shape], shape.id, `${shape.name} added by MCP`); - return { object: mcpShapeSummary(shape) }; + const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape)); + commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`); + return { object: mcpShapeSummary(committedShape) }; } if (command.action === "import_mesh") { @@ -7016,6 +7160,9 @@ export function SketchForgeEditor({ if (!target) throw new Error("Object not found"); if (target.locked) throw new Error("Unlock the object before updating it"); const patch: ShapeUpdatePatch = {}; + const rotationWasRequested = [params.rotation, params.rotationX, params.rotationZ].some( + (value) => typeof value === "number" && Number.isFinite(value), + ); (["x", "z", "elevation", "width", "depth", "height", "size", "rotation", "rotationX", "rotationZ"] as const).forEach((key) => { if (typeof params[key] === "number" && Number.isFinite(params[key])) { patch[key] = params[key]; @@ -7029,7 +7176,8 @@ export function SketchForgeEditor({ const patched = { ...shape, ...cleanShapePatch(patch) }; const width = shapeWidth(patched); const depth = shapeDepth(patched); - return canonicalizeShape({ ...patched, size: Math.max(width, depth) }); + const canonical = canonicalizeShape({ ...patched, size: Math.max(width, depth) }); + return rotationWasRequested ? canonicalizeShape(bakeShapeTransformIntoMesh(canonical)) : canonical; }); const updated = nextShapes.find((shape) => shape.id === target.id) as WorkplaneShape; commitShapes(nextShapes, target.id, `${updated.name} updated by MCP`); @@ -7073,7 +7221,12 @@ export function SketchForgeEditor({ const groupable = currentShapes().filter((shape) => ids.has(shape.id)); if (groupable.length < 2) throw new Error("Select at least two objects to group"); if (groupable.some((shape) => shape.locked)) throw new Error("Unlock every selected object before grouping"); + const sourceFingerprint = projectShapesFingerprint(currentShapes()); + const sourceProjectId = projectInfoRef.current.projectId; const result = await buildGroupedShapeFromSelection(groupable); + if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(currentShapes()) !== sourceFingerprint) { + throw new Error("The scene changed while grouping; run the command again"); + } if (!result.group) { if (result.consumed) { commitShapes(currentShapes().filter((shape) => !ids.has(shape.id)), null, "MCP group consumed solid"); @@ -7109,7 +7262,12 @@ export function SketchForgeEditor({ if (operands.some((shape) => shape.locked)) { throw new Error("Unlock every boolean operand before cutting"); } + const sourceFingerprint = projectShapesFingerprint(currentShapes()); + const sourceProjectId = projectInfoRef.current.projectId; const result = await buildGroupedShapeFromSelection(operands); + if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(currentShapes()) !== sourceFingerprint) { + throw new Error("The scene changed while cutting; run the command again"); + } const remainingShapes = currentShapes().filter((shape) => !operandIds.has(shape.id)); if (result.consumed) { commitShapes(remainingShapes, null, "MCP cut consumed solid"); @@ -7136,7 +7294,7 @@ export function SketchForgeEditor({ const target = findShape(params.id); if (!target) throw new Error("Object not found"); invalidateCadModifierSession(); - const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25))); + const sharpAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, mcpNumber(params.sharpAngle, 25))); const { response } = await prepareCadModifierForMcp(target, sharpAngle); const selectableEdgeIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id); return { object: mcpShapeSummary(target), sharpAngle, selectableEdgeIds, edges: response.edges }; @@ -7551,6 +7709,7 @@ export function SketchForgeEditor({ return; } + const sourceProjectId = projectInfoRef.current.projectId; try { let nextShape: WorkplaneShape; if (isStep) { @@ -7562,12 +7721,16 @@ export function SketchForgeEditor({ } else { nextShape = importedShapeFromStl(file.name, await file.arrayBuffer()); } - commitShapes([...shapes, nextShape], nextShape.id, `Imported ${file.name}`); + if (projectInfoRef.current.projectId !== sourceProjectId) { + setNotice(`Import of ${file.name} cancelled because the project changed`); + return; + } + commitShapes([...shapesRef.current, nextShape], nextShape.id, `Imported ${file.name}`); setTopPanel(null); } catch (error) { setNotice(error instanceof Error ? error.message : `Could not import ${file.name}`); } - }, [commitShapes, shapes]); + }, [commitShapes]); const selectFiles = useCallback( (files: FileList | File[]) => { @@ -7820,8 +7983,8 @@ export function SketchForgeEditor({ setTopPanel(null); setMenuOpen(false); }} - canUndo={historyIndex > 0 || Boolean(edgeModifier)} - canRedo={historyIndex < history.length - 1} + canUndo={!projectInteractionActive && (historyIndex > 0 || Boolean(edgeModifier))} + canRedo={!projectInteractionActive && historyIndex < history.length - 1} canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))} canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} @@ -7989,7 +8152,7 @@ export function SketchForgeEditor({ onQualityChange={(quality) => setEdgeModifier((current) => current?.prepared ? { ...current, quality, preview: null, busy: true, error: null } : current)} onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => { if (!current?.prepared) return current; - const nextAngle = Math.max(1, Math.min(120, sharpAngle)); + const nextAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, sharpAngle)); const availableIds = new Set(current.edges .filter((edge) => selectableCadModifierEdge(edge, nextAngle)) .map((edge) => edge.id)); diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index ee3532b..2a46476 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -1,7 +1,7 @@ "use client"; -import { ChevronLeft, ChevronRight, Home, Minus, Plus, Ruler, X } from "lucide-react"; -import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react"; +import { ChevronLeft, ChevronRight, Home, Minus, MousePointer2, Plus, Ruler, X } from "lucide-react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react"; import * as THREE from "three"; import { Brush, Evaluator, HOLLOW_INTERSECTION } from "three-bvh-csg"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; @@ -17,9 +17,10 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays"; import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector"; import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; -import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; +import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings"; import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION } from "@/lib/workplaneGrid"; import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; +import { sphereTessellation } from "@/lib/sphereTessellation"; import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol"; import { TransformOverlay, @@ -252,32 +253,57 @@ type MarqueeState = { type RulerPoint = { id: string; x: number; + y: number; z: number; + attachment?: RulerAttachment; +}; + +type RulerAttachment = { + shapeId: string; + normalized: [number, number, number]; + kind?: "vertex" | "edge" | "surface"; + topologyKey?: string; +}; + +type RulerEdgeAttachment = { + key: string; + shapeId: string; + normalizedPoints: Array<[number, number, number]>; + topologyKey?: string; }; type RulerSegment = { id: string; startId: string; endId: string; + edge?: RulerEdgeAttachment; }; type RulerModel = { points: RulerPoint[]; segments: RulerSegment[]; startPointId: string | null; - hover: { x: number; z: number } | null; + hover: RulerCandidate | null; }; type RulerOverlayState = { points: Array; - segments: Array; - hover: { screenX: number; screenY: number } | null; + segments: Array; + hover: { screenX: number; screenY: number; edgeScreenPoints?: string } | null; }; type RulerCandidate = { x: number; + y: number; z: number; pointId?: string; + attachment?: RulerAttachment; + edge?: RulerEdgeAttachment; +}; + +type RulerPointDragState = { + pointId: string; + pointerId: number; }; type RotationHandleSide = "near" | "right" | "far" | "left"; @@ -517,6 +543,335 @@ function projectToScreen(point: THREE.Vector3, state: ThreeState) { }; } +function rulerShapeDimensions(object: THREE.Object3D) { + const dimensions = object.userData.rulerDimensions as [number, number, number] | undefined; + return dimensions ?? [1, 1, 1]; +} + +function rulerShapeTopologyKey(shape: WorkplaneShape): string { + const positions = shape.importedMesh?.positions ?? []; + const positionSample = positions.length > 0 + ? Array.from({ length: Math.min(12, positions.length) }, (_, index) => positions[Math.floor(index * (positions.length - 1) / Math.max(1, Math.min(12, positions.length) - 1))]?.toFixed(4) ?? "0").join(",") + : ""; + const brep = shape.cadBrep ?? ""; + const brepSample = brep.length > 0 + ? Array.from({ length: Math.min(8, brep.length) }, (_, index) => brep.charCodeAt(Math.floor(index * (brep.length - 1) / Math.max(1, Math.min(8, brep.length) - 1)))).join(",") + : ""; + return JSON.stringify({ + kind: shape.kind, + radius: shape.radius, + steps: shape.steps, + sides: shape.sides, + bevel: shape.bevel, + segments: shape.segments, + topRadius: shape.topRadius, + baseRadius: shape.baseRadius, + text: shape.text, + font: shape.font, + mesh: [positions.length, positionSample], + brep: [brep.length, brepSample], + treatments: shape.edgeTreatments, + children: shape.groupedShapes?.map((child) => [child.id, rulerShapeTopologyKey(child)]), + }); +} + +function rulerAttachmentWorld(state: ThreeState, attachment: RulerAttachment) { + const object = findShapeObject(state, attachment.shapeId); + if (!object) return null; + const dimensions = rulerShapeDimensions(object); + return object.localToWorld(new THREE.Vector3( + attachment.normalized[0] * dimensions[0], + attachment.normalized[1] * dimensions[1], + attachment.normalized[2] * dimensions[2], + )); +} + +function rulerAttachmentFromWorld(state: ThreeState, shapeId: string, world: THREE.Vector3, kind: RulerAttachment["kind"] = "surface"): RulerAttachment | null { + const object = findShapeObject(state, shapeId); + if (!object) return null; + const dimensions = rulerShapeDimensions(object); + const local = object.worldToLocal(world.clone()); + return { + shapeId, + kind, + topologyKey: object.userData.rulerTopologyKey as string | undefined, + normalized: [ + local.x / Math.max(0.001, dimensions[0]), + local.y / Math.max(0.001, dimensions[1]), + local.z / Math.max(0.001, dimensions[2]), + ], + }; +} + +function rulerPointWorld(state: ThreeState, point: Pick) { + return point.attachment ? rulerAttachmentWorld(state, point.attachment) ?? new THREE.Vector3(point.x, point.y, point.z) : new THREE.Vector3(point.x, point.y, point.z); +} + +function rulerEdgeWorldPoints(state: ThreeState, edge: RulerEdgeAttachment) { + return edge.normalizedPoints.flatMap((normalized) => { + const world = rulerAttachmentWorld(state, { shapeId: edge.shapeId, normalized }); + return world ? [world] : []; + }); +} + +function rulerPolylineLength(points: THREE.Vector3[]) { + let length = 0; + for (let index = 0; index + 1 < points.length; index += 1) length += points[index].distanceTo(points[index + 1]); + return length; +} + +function rulerPolylineMidpoint(points: THREE.Vector3[]) { + if (points.length === 0) return new THREE.Vector3(); + const half = rulerPolylineLength(points) / 2; + let traversed = 0; + for (let index = 0; index + 1 < points.length; index += 1) { + const length = points[index].distanceTo(points[index + 1]); + if (traversed + length >= half && length > 1e-9) return points[index].clone().lerp(points[index + 1], (half - traversed) / length); + traversed += length; + } + return points[points.length - 1].clone(); +} + +function rulerScreenPointList(points: THREE.Vector3[], state: ThreeState) { + return points.map((point) => { + const screen = projectToScreen(point, state); + return `${screen.x},${screen.y}`; + }).join(" "); +} + +function chainRulerLineSegments(segments: Array<[THREE.Vector3, THREE.Vector3]>) { + if (segments.length <= 1) return segments.map(([a, b]) => [a, b]); + const bounds = new THREE.Box3(); + segments.forEach(([a, b]) => { + bounds.expandByPoint(a); + bounds.expandByPoint(b); + }); + const tolerance = Math.max(1e-6, bounds.getSize(new THREE.Vector3()).length() * 1e-5); + const tangentLimit = Math.cos(THREE.MathUtils.degToRad(20)); + const unused = new Set(segments.map((_, index) => index)); + const paths: THREE.Vector3[][] = []; + + while (unused.size > 0) { + const firstIndex = unused.values().next().value as number; + unused.delete(firstIndex); + const path = [segments[firstIndex][0].clone(), segments[firstIndex][1].clone()]; + let extended = true; + while (extended) { + extended = false; + for (const index of unused) { + const [a, b] = segments[index]; + const end = path[path.length - 1]; + const endDirection = end.clone().sub(path[path.length - 2]).normalize(); + const endOther = a.distanceTo(end) <= tolerance ? b : b.distanceTo(end) <= tolerance ? a : null; + if (endOther && Math.abs(endDirection.dot(endOther.clone().sub(end).normalize())) >= tangentLimit) { + path.push(endOther.clone()); + unused.delete(index); + extended = true; + break; + } + const start = path[0]; + const startDirection = start.clone().sub(path[1]).normalize(); + const startOther = a.distanceTo(start) <= tolerance ? b : b.distanceTo(start) <= tolerance ? a : null; + if (startOther && Math.abs(startDirection.dot(startOther.clone().sub(start).normalize())) >= tangentLimit) { + path.unshift(startOther.clone()); + unused.delete(index); + extended = true; + break; + } + } + } + paths.push(path); + } + return paths; +} + +function rulerNormalizedLineSegments(state: ThreeState, shapeId: string) { + const object = findShapeObject(state, shapeId); + if (!object) return []; + object.updateWorldMatrix(true, true); + const dimensions = rulerShapeDimensions(object); + const normalizedFromWorld = (world: THREE.Vector3) => { + const local = object.worldToLocal(world.clone()); + return new THREE.Vector3( + local.x / Math.max(0.001, dimensions[0]), + local.y / Math.max(0.001, dimensions[1]), + local.z / Math.max(0.001, dimensions[2]), + ); + }; + const segments: Array<[THREE.Vector3, THREE.Vector3]> = []; + object.traverse((child) => { + if (!(child instanceof THREE.Line) || !child.visible) return; + const position = child.geometry.getAttribute("position"); + if (!position || position.count < 2) return; + const points: THREE.Vector3[] = []; + for (let index = 0; index < position.count; index += 1) { + points.push(normalizedFromWorld(new THREE.Vector3().fromBufferAttribute(position, index).applyMatrix4(child.matrixWorld))); + } + if ((child as THREE.LineSegments).isLineSegments) { + for (let index = 0; index + 1 < points.length; index += 2) segments.push([points[index], points[index + 1]]); + } else { + for (let index = 0; index + 1 < points.length; index += 1) segments.push([points[index], points[index + 1]]); + if ((child as THREE.LineLoop).isLineLoop && points.length > 2) segments.push([points[points.length - 1], points[0]]); + } + }); + return segments; +} + +function rulerPointToSegmentDistance(point: THREE.Vector3, start: THREE.Vector3, end: THREE.Vector3) { + const delta = end.clone().sub(start); + const lengthSq = delta.lengthSq(); + const amount = lengthSq > 1e-12 ? clamp(point.clone().sub(start).dot(delta) / lengthSq, 0, 1) : 0; + return point.distanceTo(start.clone().addScaledVector(delta, amount)); +} + +function rulerAttachmentMatchesTopology(state: ThreeState, attachment: RulerAttachment) { + const object = findShapeObject(state, attachment.shapeId); + if (!object) return false; + const currentTopologyKey = object.userData.rulerTopologyKey as string | undefined; + if (!attachment.topologyKey || attachment.topologyKey === currentTopologyKey || attachment.kind === "surface") return true; + const target = new THREE.Vector3(...attachment.normalized); + const segments = rulerNormalizedLineSegments(state, attachment.shapeId); + if (attachment.kind === "vertex") { + return segments.some(([start, end]) => start.distanceTo(target) <= 0.002 || end.distanceTo(target) <= 0.002); + } + return segments.some(([start, end]) => rulerPointToSegmentDistance(target, start, end) <= 0.002); +} + +function rulerEdgeMatchesTopology(state: ThreeState, edge: RulerEdgeAttachment) { + const object = findShapeObject(state, edge.shapeId); + if (!object) return false; + const currentTopologyKey = object.userData.rulerTopologyKey as string | undefined; + if (!edge.topologyKey || edge.topologyKey === currentTopologyKey) return true; + const segments = rulerNormalizedLineSegments(state, edge.shapeId); + if (segments.length === 0) return false; + const samples = edge.normalizedPoints.filter((_, index) => ( + index === 0 + || index === edge.normalizedPoints.length - 1 + || index % Math.max(1, Math.floor(edge.normalizedPoints.length / 8)) === 0 + )); + return samples.every((point) => { + const target = new THREE.Vector3(...point); + return segments.some(([start, end]) => rulerPointToSegmentDistance(target, start, end) <= 0.002); + }); +} + +function pickModelRulerCandidate(state: ThreeState, shapeIds: string[], clientX: number, clientY: number): RulerCandidate | null { + const rect = state.renderer.domElement.getBoundingClientRect(); + const pointerX = clientX - rect.left; + const pointerY = clientY - rect.top; + const targets = shapeIds.flatMap((id) => { + const object = findShapeObject(state, id); + return object ? [object] : []; + }); + if (targets.length === 0) return null; + + state.camera.updateMatrixWorld(); + targets.forEach((target) => target.updateWorldMatrix(true, true)); + const vertexCandidates: Array<{ distance: number; candidate: RulerCandidate }> = []; + const edgeCandidates: Array<{ distance: number; candidate: RulerCandidate }> = []; + + targets.forEach((target) => { + const shapeId = target.userData.shapeId as string; + target.traverse((child) => { + if (!(child instanceof THREE.Line) || !child.visible) return; + const position = child.geometry.getAttribute("position"); + if (!position || position.count < 2) return; + const paths: THREE.Vector3[][] = []; + if ((child as THREE.LineSegments).isLineSegments) { + const segments: Array<[THREE.Vector3, THREE.Vector3]> = []; + for (let index = 0; index + 1 < position.count; index += 2) { + segments.push([ + new THREE.Vector3().fromBufferAttribute(position, index).applyMatrix4(child.matrixWorld), + new THREE.Vector3().fromBufferAttribute(position, index + 1).applyMatrix4(child.matrixWorld), + ]); + } + paths.push(...chainRulerLineSegments(segments)); + } else { + const path: THREE.Vector3[] = []; + for (let index = 0; index < position.count; index += 1) path.push(new THREE.Vector3().fromBufferAttribute(position, index).applyMatrix4(child.matrixWorld)); + if ((child as THREE.LineLoop).isLineLoop && path.length > 2) path.push(path[0].clone()); + paths.push(path); + } + + paths.forEach((worldPoints, pathIndex) => { + if (worldPoints.length < 2) return; + const attachments = worldPoints.map((point) => rulerAttachmentFromWorld(state, shapeId, point, "edge")); + if (attachments.some((attachment) => !attachment)) return; + const normalizedPoints = attachments.map((attachment) => (attachment as RulerAttachment).normalized); + const edge: RulerEdgeAttachment = { + key: `${shapeId}:${child.uuid}:${pathIndex}`, + shapeId, + normalizedPoints, + topologyKey: target.userData.rulerTopologyKey as string | undefined, + }; + const endpointIndexes = worldPoints[0].distanceToSquared(worldPoints[worldPoints.length - 1]) < 1e-10 ? [0] : [0, worldPoints.length - 1]; + endpointIndexes.forEach((index) => { + const screen = projectToScreen(worldPoints[index], state); + const distance = Math.hypot(pointerX - screen.x, pointerY - screen.y); + if (distance <= 9) { + vertexCandidates.push({ + distance, + candidate: { + x: worldPoints[index].x, + y: worldPoints[index].y, + z: worldPoints[index].z, + attachment: { ...(attachments[index] as RulerAttachment), kind: "vertex" }, + }, + }); + } + }); + + for (let index = 0; index + 1 < worldPoints.length; index += 1) { + const aScreen = projectToScreen(worldPoints[index], state); + const bScreen = projectToScreen(worldPoints[index + 1], state); + const dx = bScreen.x - aScreen.x; + const dy = bScreen.y - aScreen.y; + const amount = dx * dx + dy * dy > 0.001 ? clamp(((pointerX - aScreen.x) * dx + (pointerY - aScreen.y) * dy) / (dx * dx + dy * dy), 0, 1) : 0; + const distance = Math.hypot(pointerX - (aScreen.x + dx * amount), pointerY - (aScreen.y + dy * amount)); + if (distance <= 12) { + const world = worldPoints[index].clone().lerp(worldPoints[index + 1], amount); + const normalizedA = normalizedPoints[index]; + const normalizedB = normalizedPoints[index + 1]; + edgeCandidates.push({ + distance, + candidate: { + x: world.x, + y: world.y, + z: world.z, + attachment: { + shapeId, + kind: "edge", + topologyKey: target.userData.rulerTopologyKey as string | undefined, + normalized: [ + normalizedA[0] + (normalizedB[0] - normalizedA[0]) * amount, + normalizedA[1] + (normalizedB[1] - normalizedA[1]) * amount, + normalizedA[2] + (normalizedB[2] - normalizedA[2]) * amount, + ], + }, + edge, + }, + }); + } + } + }); + }); + }); + + vertexCandidates.sort((a, b) => a.distance - b.distance); + edgeCandidates.sort((a, b) => a.distance - b.distance); + if (vertexCandidates[0]) return vertexCandidates[0].candidate; + if (edgeCandidates[0]) return edgeCandidates[0].candidate; + + state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; + state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; + state.raycaster.setFromCamera(state.pointer, state.camera); + const surfaceHit = state.raycaster.intersectObjects(targets, true).find((entry) => entry.object instanceof THREE.Mesh); + if (!surfaceHit) return null; + const shapeId = surfaceHit.object.userData.shapeId as string; + const attachment = rulerAttachmentFromWorld(state, shapeId, surfaceHit.point); + return attachment ? { x: surfaceHit.point.x, y: surfaceHit.point.y, z: surfaceHit.point.z, attachment } : null; +} + function distanceToScreenSegment(x: number, y: number, ax: number, ay: number, bx: number, by: number) { const dx = bx - ax; const dy = by - ay; @@ -571,7 +926,7 @@ function syncRulerOverlay( ) { const projectedPoints = new Map(); const points = model.points.map((point) => { - const screen = projectToScreen(new THREE.Vector3(point.x, 0.12, point.z), state); + const screen = projectToScreen(rulerPointWorld(state, point), state); const projected = { screenX: screen.x, screenY: screen.y }; projectedPoints.set(point.id, projected); return { ...point, ...projected }; @@ -584,6 +939,11 @@ function syncRulerOverlay( if (!start || !end || !startScreen || !endScreen) { return []; } + const startWorld = rulerPointWorld(state, start); + const endWorld = rulerPointWorld(state, end); + const attachedEdgePoints = segment.edge ? rulerEdgeWorldPoints(state, segment.edge) : []; + const worldPoints = attachedEdgePoints.length >= 2 ? attachedEdgePoints : [startWorld, endWorld]; + const labelScreen = projectToScreen(rulerPolylineMidpoint(worldPoints), state); return [ { ...segment, @@ -591,17 +951,24 @@ function syncRulerOverlay( y1: startScreen.screenY, x2: endScreen.screenX, y2: endScreen.screenY, - labelX: (startScreen.screenX + endScreen.screenX) / 2, - labelY: (startScreen.screenY + endScreen.screenY) / 2 - 18, - label: formatMeasure(Math.hypot(end.x - start.x, end.z - start.z), accuracy), + screenPoints: segment.edge && worldPoints.length >= 2 ? rulerScreenPointList(worldPoints, state) : undefined, + labelX: labelScreen.x, + labelY: labelScreen.y - 18, + label: formatMeasure(rulerPolylineLength(worldPoints), accuracy), }, ]; }); - const hoverScreen = model.hover ? projectToScreen(new THREE.Vector3(model.hover.x, 0.14, model.hover.z), state) : null; + const hoverWorld = model.hover ? rulerPointWorld(state, model.hover) : null; + const hoverScreen = hoverWorld ? projectToScreen(hoverWorld, state) : null; + const hoverEdgePoints = model.hover?.edge ? rulerEdgeWorldPoints(state, model.hover.edge) : []; const next: RulerOverlayState = { points, segments, - hover: hoverScreen ? { screenX: hoverScreen.x, screenY: hoverScreen.y } : null, + hover: hoverScreen ? { + screenX: hoverScreen.x, + screenY: hoverScreen.y, + edgeScreenPoints: hoverEdgePoints.length >= 2 ? rulerScreenPointList(hoverEdgePoints, state) : undefined, + } : null, }; const previous = overlayRef.current; const unchanged = @@ -614,10 +981,21 @@ function syncRulerOverlay( }) && previous.segments.every((segment, index) => { const candidate = next.segments[index]; - return segment.id === candidate.id && Math.abs(segment.labelX - candidate.labelX) < 0.2 && Math.abs(segment.labelY - candidate.labelY) < 0.2; + return segment.id === candidate.id + && segment.label === candidate.label + && segment.screenPoints === candidate.screenPoints + && Math.abs(segment.x1 - candidate.x1) < 0.2 + && Math.abs(segment.y1 - candidate.y1) < 0.2 + && Math.abs(segment.x2 - candidate.x2) < 0.2 + && Math.abs(segment.y2 - candidate.y2) < 0.2 + && Math.abs(segment.labelX - candidate.labelX) < 0.2 + && Math.abs(segment.labelY - candidate.labelY) < 0.2; }) && ((!previous.hover && !next.hover) || - (previous.hover && next.hover && Math.abs(previous.hover.screenX - next.hover.screenX) < 0.2 && Math.abs(previous.hover.screenY - next.hover.screenY) < 0.2)); + (previous.hover && next.hover + && previous.hover.edgeScreenPoints === next.hover.edgeScreenPoints + && Math.abs(previous.hover.screenX - next.hover.screenX) < 0.2 + && Math.abs(previous.hover.screenY - next.hover.screenY) < 0.2)); if (!unchanged) { overlayRef.current = next; setOverlay(next); @@ -629,30 +1007,45 @@ function RulerOverlay({ startPointId, active, deleteMode, + moveMode, onPointPointerDown, + onPointPointerMove, + onPointPointerUp, onSegmentPointerDown, }: { overlay: RulerOverlayState; startPointId: string | null; active: boolean; deleteMode: boolean; + moveMode: boolean; onPointPointerDown: (event: ReactPointerEvent, pointId: string) => void; - onSegmentPointerDown: (event: ReactPointerEvent, segmentId: string) => void; + onPointPointerMove: (event: ReactPointerEvent, pointId: string) => void; + onPointPointerUp: (event: ReactPointerEvent, pointId: string) => void; + onSegmentPointerDown: (event: ReactPointerEvent, segmentId: string) => void; }) { return ( -
+
{overlay.segments.map((segment) => ( @@ -1183,6 +1580,7 @@ export function WorkplaneViewport({ const [editingRotation, setEditingRotation] = useState(null); const [rulerMode, setRulerMode] = useState(false); const [rulerDeleteMode, setRulerDeleteMode] = useState(false); + const [rulerMoveMode, setRulerMoveMode] = useState(false); const [rulerToolsOpen, setRulerToolsOpen] = useState(false); const [cameraControlsCollapsed, setCameraControlsCollapsed] = useState(false); const [rulerModel, setRulerModel] = useState({ points: [], segments: [], startPointId: null, hover: null }); @@ -1202,12 +1600,15 @@ export function WorkplaneViewport({ const workspaceRef = useRef(workspace); const workspaceSettingsKeyRef = useRef(workspaceSettingsKey ?? null); const lastWorkspaceSettingsSyncRef = useRef(""); + const pendingWorkspaceHydrationFingerprintRef = useRef(null); const viewCubeRef = useRef(null); const transformOverlayRef = useRef(null); const alignOverlayRef = useRef(null); const mirrorOverlayRef = useRef(null); const rulerModeRef = useRef(false); const rulerDeleteModeRef = useRef(false); + const rulerMoveModeRef = useRef(false); + const rulerPointDragRef = useRef(null); const rulerModelRef = useRef(rulerModel); const rulerOverlayRef = useRef(null); const rulerIdRef = useRef(0); @@ -1260,7 +1661,7 @@ export function WorkplaneViewport({ } }, []); - useEffect(() => { + useLayoutEffect(() => { const nextKey = workspaceSettingsKey ?? null; if (workspaceSettingsKeyRef.current !== nextKey) { workspaceSettingsKeyRef.current = nextKey; @@ -1275,6 +1676,14 @@ export function WorkplaneViewport({ // new object references even when the values are unchanged, which previously // caused this effect and its callback effect to update each other indefinitely. lastWorkspaceSettingsSyncRef.current = nextFingerprint; + pendingWorkspaceHydrationFingerprintRef.current = nextFingerprint; + snapRef.current = nextSnap; + workspaceRef.current = nextWorkspace; + if (threeRef.current) { + rebuildWorkplane(threeRef.current, nextWorkspace); + constrainCamera(threeRef.current, nextWorkspace); + threeRef.current.needsRender = true; + } setSnap((current) => (current === nextSnap ? current : nextSnap)); setWorkspace((current) => ( workplaneSettingsFingerprint(current, nextSnap) === nextFingerprint ? current : nextWorkspace @@ -1285,6 +1694,11 @@ export function WorkplaneViewport({ const normalizedWorkspace = normalizeWorkspaceSettings(workspace); const normalizedSnap = normalizeSnapGrid(snap, DEFAULT_SNAP_GRID); const fingerprint = workplaneSettingsFingerprint(normalizedWorkspace, normalizedSnap); + const hydrationDecision = workspaceHydrationSyncDecision(pendingWorkspaceHydrationFingerprintRef.current, fingerprint); + pendingWorkspaceHydrationFingerprintRef.current = hydrationDecision.pendingFingerprint; + if (!hydrationDecision.shouldSync) { + return; + } if (lastWorkspaceSettingsSyncRef.current === fingerprint) { return; } @@ -1432,6 +1846,10 @@ export function WorkplaneViewport({ rulerDeleteModeRef.current = rulerDeleteMode; }, [rulerDeleteMode]); + useEffect(() => { + rulerMoveModeRef.current = rulerMoveMode; + }, [rulerMoveMode]); + useEffect(() => { rulerModelRef.current = rulerModel; if (threeRef.current) { @@ -1636,6 +2054,70 @@ export function WorkplaneViewport({ setRulerModel(next); }, []); + useEffect(() => { + const current = rulerModelRef.current; + const shapeById = new Map(shapes.map((shape) => [shape.id, shape])); + const shapeIds = new Set(shapeById.keys()); + const state = threeRef.current; + const removedPointIds = new Set(); + let metadataChanged = false; + const updatedPoints = current.points.map((point) => { + if (!point.attachment) return point; + const attachedShape = shapeById.get(point.attachment.shapeId); + if (!attachedShape || (state && !attachedShape.hidden && !rulerAttachmentMatchesTopology(state, point.attachment))) { + removedPointIds.add(point.id); + return point; + } + const object = state ? findShapeObject(state, point.attachment.shapeId) : null; + const topologyKey = object?.userData.rulerTopologyKey as string | undefined; + if (topologyKey && topologyKey !== point.attachment.topologyKey) { + metadataChanged = true; + return { ...point, attachment: { ...point.attachment, topologyKey } }; + } + return point; + }); + const invalidEdgeSegments = new Set(); + const updatedSegments = current.segments.map((segment) => { + if (!segment.edge) return segment; + const attachedShape = shapeById.get(segment.edge.shapeId); + if (!attachedShape || (state && !attachedShape.hidden && !rulerEdgeMatchesTopology(state, segment.edge))) { + invalidEdgeSegments.add(segment.id); + return segment; + } + const object = state ? findShapeObject(state, segment.edge.shapeId) : null; + const topologyKey = object?.userData.rulerTopologyKey as string | undefined; + if (topologyKey && topologyKey !== segment.edge.topologyKey) { + metadataChanged = true; + return { ...segment, edge: { ...segment.edge, topologyKey } }; + } + return segment; + }); + const provisionalSegments = updatedSegments.filter((segment) => ( + !removedPointIds.has(segment.startId) + && !removedPointIds.has(segment.endId) + && !invalidEdgeSegments.has(segment.id) + )); + current.segments.filter((segment) => invalidEdgeSegments.has(segment.id)).forEach((segment) => { + [segment.startId, segment.endId].forEach((pointId) => { + if (!provisionalSegments.some((candidate) => candidate.startId === pointId || candidate.endId === pointId)) removedPointIds.add(pointId); + }); + }); + const segments = provisionalSegments.filter((segment) => !removedPointIds.has(segment.startId) && !removedPointIds.has(segment.endId)); + const points = updatedPoints.filter((point) => !removedPointIds.has(point.id)); + const hoverRemoved = Boolean(current.hover?.attachment && ( + !shapeIds.has(current.hover.attachment.shapeId) + || (state && !shapeById.get(current.hover.attachment.shapeId)?.hidden && !rulerAttachmentMatchesTopology(state, current.hover.attachment)) + )); + if (removedPointIds.size === 0 && invalidEdgeSegments.size === 0 && !hoverRemoved && !metadataChanged) return; + if (rulerPointDragRef.current && removedPointIds.has(rulerPointDragRef.current.pointId)) rulerPointDragRef.current = null; + storeRulerModel({ + points, + segments, + startPointId: current.startPointId && !removedPointIds.has(current.startPointId) ? current.startPointId : null, + hover: hoverRemoved ? null : current.hover, + }); + }, [shapes, storeRulerModel]); + const setRulerActive = useCallback((active: boolean) => { rulerModeRef.current = active; setRulerMode(active); @@ -1646,28 +2128,17 @@ export function WorkplaneViewport({ }, [storeRulerModel]); const resolveRulerCandidate = useCallback( - (clientX: number, clientY: number): RulerCandidate | null => { + (clientX: number, clientY: number, ignoredPointId?: string): RulerCandidate | null => { const state = threeRef.current; - if (!state) { - return null; - } - const raw = toRawPlanePoint(clientX, clientY, state.dragPlane); - if (!raw) { - return null; - } - const step = snapStep(snapRef.current); - const bounds = workspaceRef.current; - const snapped = { - x: clamp(snapValue(raw.x, step), -bounds.width / 2, bounds.width / 2), - z: clamp(snapValue(raw.z, step), -bounds.depth / 2, bounds.depth / 2), - }; + if (!state) return null; const model = rulerModelRef.current; const rect = state.renderer.domElement.getBoundingClientRect(); const localX = clientX - rect.left; const localY = clientY - rect.top; const closestPoint = model.points.reduce<{ point: RulerPoint; distance: number } | null>((closest, point) => { - const screen = projectToScreen(new THREE.Vector3(point.x, 0.12, point.z), state); + if (point.id === ignoredPointId) return closest; + const screen = projectToScreen(rulerPointWorld(state, point), state); const distance = Math.hypot(screen.x - localX, screen.y - localY); if (distance <= 12 && (!closest || distance < closest.distance)) { return { point, distance }; @@ -1675,48 +2146,51 @@ export function WorkplaneViewport({ return closest; }, null); if (closestPoint) { - return { x: closestPoint.point.x, z: closestPoint.point.z, pointId: closestPoint.point.id }; + const world = rulerPointWorld(state, closestPoint.point); + return { x: world.x, y: world.y, z: world.z, pointId: closestPoint.point.id, attachment: closestPoint.point.attachment }; } - const closestSegment = model.segments.reduce<{ segment: RulerSegment; distance: number } | null>((closest, segment) => { + const closestSegment = model.segments.reduce<{ world: THREE.Vector3; distance: number } | null>((closest, segment) => { + if (segment.startId === ignoredPointId || segment.endId === ignoredPointId) return closest; const start = model.points.find((point) => point.id === segment.startId); const end = model.points.find((point) => point.id === segment.endId); - if (!start || !end) { - return closest; - } - const a = projectToScreen(new THREE.Vector3(start.x, 0.12, start.z), state); - const b = projectToScreen(new THREE.Vector3(end.x, 0.12, end.z), state); - const dx = b.x - a.x; - const dy = b.y - a.y; - const amount = dx * dx + dy * dy > 0.001 ? clamp(((localX - a.x) * dx + (localY - a.y) * dy) / (dx * dx + dy * dy), 0, 1) : 0; - const distance = Math.hypot(localX - (a.x + dx * amount), localY - (a.y + dy * amount)); - if (distance <= 10 && (!closest || distance < closest.distance)) { - return { segment, distance }; + if (!start || !end) return closest; + const edgePoints = segment.edge ? rulerEdgeWorldPoints(state, segment.edge) : []; + const worldPoints = edgePoints.length >= 2 ? edgePoints : [rulerPointWorld(state, start), rulerPointWorld(state, end)]; + for (let index = 0; index + 1 < worldPoints.length; index += 1) { + const a = projectToScreen(worldPoints[index], state); + const b = projectToScreen(worldPoints[index + 1], state); + const dx = b.x - a.x; + const dy = b.y - a.y; + const amount = dx * dx + dy * dy > 0.001 ? clamp(((localX - a.x) * dx + (localY - a.y) * dy) / (dx * dx + dy * dy), 0, 1) : 0; + const distance = Math.hypot(localX - (a.x + dx * amount), localY - (a.y + dy * amount)); + if (distance <= 10 && (!closest || distance < closest.distance)) { + closest = { world: worldPoints[index].clone().lerp(worldPoints[index + 1], amount), distance }; + } } return closest; }, null); if (closestSegment) { - const start = model.points.find((point) => point.id === closestSegment.segment.startId); - const end = model.points.find((point) => point.id === closestSegment.segment.endId); - if (start && end) { - const dx = end.x - start.x; - const dz = end.z - start.z; - const length = Math.hypot(dx, dz); - if (length > 0.001) { - const directionX = dx / length; - const directionZ = dz / length; - const rawAlong = clamp((raw.x - start.x) * directionX + (raw.z - start.z) * directionZ, 0, length); - const along = clamp(step > 0 ? snapValue(rawAlong, step) : rawAlong, 0, length); - const x = start.x + directionX * along; - const z = start.z + directionZ * along; - const existing = model.points.find((point) => Math.hypot(point.x - x, point.z - z) < 0.001); - return { x, z, pointId: existing?.id }; - } - } + const existing = model.points.find((point) => rulerPointWorld(state, point).distanceTo(closestSegment.world) < 0.001); + return { x: closestSegment.world.x, y: closestSegment.world.y, z: closestSegment.world.z, pointId: existing?.id }; } - const existing = model.points.find((point) => Math.hypot(point.x - snapped.x, point.z - snapped.z) < 0.001); + const selectedShapeIds = selectedIdsRef.current.filter((id) => shapesRef.current.some((shape) => shape.id === id && !shape.hidden)); + const targetShapeIds = selectedShapeIds.length > 0 ? selectedShapeIds : shapesRef.current.filter((shape) => !shape.hidden).map((shape) => shape.id); + const modelCandidate = pickModelRulerCandidate(state, targetShapeIds, clientX, clientY); + if (modelCandidate) return modelCandidate; + + const raw = toRawPlanePoint(clientX, clientY, state.dragPlane); + if (!raw) return null; + const step = snapStep(snapRef.current); + const bounds = workspaceRef.current; + const snapped = { + x: clamp(snapValue(raw.x, step), -bounds.width / 2, bounds.width / 2), + y: 0, + z: clamp(snapValue(raw.z, step), -bounds.depth / 2, bounds.depth / 2), + }; + const existing = model.points.find((point) => Math.hypot(point.x - snapped.x, point.y, point.z - snapped.z) < 0.001 && !point.attachment); return { ...snapped, pointId: existing?.id }; }, [toRawPlanePoint], @@ -1725,11 +2199,65 @@ export function WorkplaneViewport({ const selectRulerCandidate = useCallback( (candidate: RulerCandidate) => { const current = rulerModelRef.current; - const existing = candidate.pointId ? current.points.find((point) => point.id === candidate.pointId) : current.points.find((point) => Math.hypot(point.x - candidate.x, point.z - candidate.z) < 0.001); - const point = existing ?? { id: `ruler-point-${++rulerIdRef.current}`, x: candidate.x, z: candidate.z }; + const sameAttachment = (point: RulerPoint, attachment: RulerAttachment | undefined) => Boolean( + attachment + && point.attachment?.shapeId === attachment.shapeId + && Math.hypot( + point.attachment.normalized[0] - attachment.normalized[0], + point.attachment.normalized[1] - attachment.normalized[1], + point.attachment.normalized[2] - attachment.normalized[2], + ) < 1e-5, + ); + const findExisting = (value: Pick) => value.pointId + ? current.points.find((point) => point.id === value.pointId) + : current.points.find((point) => sameAttachment(point, value.attachment) || (!point.attachment && !value.attachment && Math.hypot(point.x - value.x, point.y - value.y, point.z - value.z) < 0.001)); + const makePoint = (value: Pick) => findExisting(value) ?? { + id: `ruler-point-${++rulerIdRef.current}`, + x: value.x, + y: value.y, + z: value.z, + attachment: value.attachment, + }; + + if (candidate.edge && !current.startPointId) { + const state = threeRef.current; + const worldPoints = state ? rulerEdgeWorldPoints(state, candidate.edge) : []; + if (worldPoints.length >= 2) { + const firstAttachment: RulerAttachment = { + shapeId: candidate.edge.shapeId, + normalized: candidate.edge.normalizedPoints[0], + kind: "vertex", + topologyKey: candidate.edge.topologyKey, + }; + const lastAttachment: RulerAttachment = { + shapeId: candidate.edge.shapeId, + normalized: candidate.edge.normalizedPoints[candidate.edge.normalizedPoints.length - 1], + kind: "vertex", + topologyKey: candidate.edge.topologyKey, + }; + const start = makePoint({ x: worldPoints[0].x, y: worldPoints[0].y, z: worldPoints[0].z, attachment: firstAttachment }); + const endWorld = worldPoints[worldPoints.length - 1]; + const end = makePoint({ x: endWorld.x, y: endWorld.y, z: endWorld.z, attachment: lastAttachment }); + const points = [...current.points]; + if (!points.some((point) => point.id === start.id)) points.push(start); + if (!points.some((point) => point.id === end.id)) points.push(end); + const duplicate = current.segments.some((segment) => segment.edge?.key === candidate.edge?.key); + const segments = duplicate ? current.segments : [...current.segments, { + id: `ruler-segment-${++rulerIdRef.current}`, + startId: start.id, + endId: end.id, + edge: candidate.edge, + }]; + storeRulerModel({ points, segments, startPointId: null, hover: null }); + return; + } + } + + const existing = findExisting(candidate); + const point = existing ?? makePoint(candidate); const points = existing ? current.points : [...current.points, point]; if (!current.startPointId) { - storeRulerModel({ ...current, points, startPointId: point.id, hover: { x: point.x, z: point.z } }); + storeRulerModel({ ...current, points, startPointId: point.id, hover: { x: point.x, y: point.y, z: point.z, attachment: point.attachment } }); return; } if (current.startPointId === point.id) { @@ -1756,8 +2284,10 @@ export function WorkplaneViewport({ } const candidate = resolveRulerCandidate(clientX, clientY); const current = rulerModelRef.current; - const hover = candidate ? { x: candidate.x, z: candidate.z } : null; - if ((!current.hover && !hover) || (current.hover && hover && Math.hypot(current.hover.x - hover.x, current.hover.z - hover.z) < 0.0001)) { + const hover = candidate; + if ((!current.hover && !hover) || (current.hover && hover + && current.hover.edge?.key === hover.edge?.key + && Math.hypot(current.hover.x - hover.x, current.hover.y - hover.y, current.hover.z - hover.z) < 0.0001)) { return; } storeRulerModel({ ...current, hover }); @@ -2346,6 +2876,12 @@ export function WorkplaneViewport({ return; } + if (rulerMoveModeRef.current) { + event.preventDefault(); + event.stopPropagation(); + return; + } + if (rulerModeRef.current) { event.preventDefault(); const candidate = resolveRulerCandidate(event.clientX, event.clientY); @@ -2599,6 +3135,7 @@ export function WorkplaneViewport({ updateRulerHover(event.clientX, event.clientY); return; } + if (rulerMoveModeRef.current) return; const transform = transformRef.current; if (transform) { updateTransform(event.clientX, event.clientY, event.shiftKey, event.altKey); @@ -2771,6 +3308,7 @@ export function WorkplaneViewport({ const handleDrop = useCallback( (event: DragEvent) => { event.preventDefault(); + if (rulerMoveModeRef.current) return; const raw = event.dataTransfer.getData("application/x-sketchforge-shape"); if (!raw) { return; @@ -2824,25 +3362,38 @@ export function WorkplaneViewport({ setRulerActive(false); rulerDeleteModeRef.current = false; setRulerDeleteMode(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); if (next) { onWorkplaneModeChange(false); - onSelectShape(null); } - }, [onSelectShape, onWorkplaneModeChange, rulerToolsOpen, setRulerActive]); + }, [onWorkplaneModeChange, rulerToolsOpen, setRulerActive]); const activateRulerAdd = useCallback(() => { rulerDeleteModeRef.current = false; setRulerDeleteMode(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); setRulerActive(true); onWorkplaneModeChange(false); - onSelectShape(null); - }, [onSelectShape, onWorkplaneModeChange, setRulerActive]); + }, [onWorkplaneModeChange, setRulerActive]); const activateRulerDelete = useCallback(() => { setRulerActive(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); rulerDeleteModeRef.current = true; setRulerDeleteMode(true); onWorkplaneModeChange(false); + }, [onWorkplaneModeChange, setRulerActive]); + + const activateRulerMove = useCallback(() => { + setRulerActive(false); + rulerDeleteModeRef.current = false; + setRulerDeleteMode(false); + rulerMoveModeRef.current = true; + setRulerMoveMode(true); + onWorkplaneModeChange(false); onSelectShape(null); }, [onSelectShape, onWorkplaneModeChange, setRulerActive]); @@ -2852,6 +3403,9 @@ export function WorkplaneViewport({ setRulerActive(false); rulerDeleteModeRef.current = false; setRulerDeleteMode(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); + rulerPointDragRef.current = null; }, [setRulerActive]); const handleRulerPointPointerDown = useCallback( @@ -2865,6 +3419,13 @@ export function WorkplaneViewport({ removeRulerPoint(pointId); return; } + if (rulerMoveModeRef.current) { + event.preventDefault(); + event.stopPropagation(); + event.currentTarget.setPointerCapture(event.pointerId); + rulerPointDragRef.current = { pointId, pointerId: event.pointerId }; + return; + } if (!rulerModeRef.current) { return; } @@ -2874,13 +3435,54 @@ export function WorkplaneViewport({ } event.preventDefault(); event.stopPropagation(); - selectRulerCandidate({ x: point.x, z: point.z, pointId }); + const state = threeRef.current; + const world = state ? rulerPointWorld(state, point) : new THREE.Vector3(point.x, point.y, point.z); + selectRulerCandidate({ x: world.x, y: world.y, z: world.z, pointId, attachment: point.attachment }); }, [removeRulerPoint, selectRulerCandidate], ); + const handleRulerPointPointerMove = useCallback( + (event: ReactPointerEvent, pointId: string) => { + const drag = rulerPointDragRef.current; + if (!rulerMoveModeRef.current || !drag || drag.pointId !== pointId || drag.pointerId !== event.pointerId) return; + event.preventDefault(); + event.stopPropagation(); + const candidate = resolveRulerCandidate(event.clientX, event.clientY, pointId); + if (!candidate) return; + const current = rulerModelRef.current; + storeRulerModel({ + ...current, + points: current.points.map((point) => point.id === pointId ? { + ...point, + x: candidate.x, + y: candidate.y, + z: candidate.z, + attachment: candidate.attachment, + } : point), + segments: current.segments.map((segment) => segment.startId === pointId || segment.endId === pointId ? { ...segment, edge: undefined } : segment), + hover: candidate, + }); + }, + [resolveRulerCandidate, storeRulerModel], + ); + + const handleRulerPointPointerUp = useCallback( + (event: ReactPointerEvent, pointId: string) => { + const drag = rulerPointDragRef.current; + if (!drag || drag.pointId !== pointId || drag.pointerId !== event.pointerId) return; + event.preventDefault(); + event.stopPropagation(); + if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); + rulerPointDragRef.current = null; + const current = rulerModelRef.current; + storeRulerModel({ ...current, hover: null }); + }, + [storeRulerModel], + ); + const handleRulerSegmentPointerDown = useCallback( - (event: ReactPointerEvent, segmentId: string) => { + (event: ReactPointerEvent, segmentId: string) => { if (event.button !== 0) { return; } @@ -2917,11 +3519,14 @@ export function WorkplaneViewport({ } const key = event.key.toLowerCase(); - if (event.key === "Escape" && (rulerToolsOpen || rulerModeRef.current || rulerDeleteModeRef.current)) { + if (event.key === "Escape" && (rulerToolsOpen || rulerModeRef.current || rulerDeleteModeRef.current || rulerMoveModeRef.current)) { event.preventDefault(); setRulerActive(false); rulerDeleteModeRef.current = false; setRulerDeleteMode(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); + rulerPointDragRef.current = null; setRulerToolsOpen(false); } else if (key === "f" || event.key === "Home") { event.preventDefault(); @@ -2987,6 +3592,9 @@ export function WorkplaneViewport({ + @@ -2997,7 +3605,7 @@ export function WorkplaneViewport({ )}
-
+
{marqueeRect ?
: null} - {transformOverlay && !alignMode && !mirrorMode && !rulerMode && !modifierActive ? ( + {transformOverlay && !alignMode && !mirrorMode && !rulerMode && !rulerDeleteMode && !rulerMoveMode && !modifierActive ? ( ) : null}
- {selectedShape && !modifierActive ? ( + {selectedShape && !modifierActive && !rulerMode && !rulerDeleteMode && !rulerMoveMode ? ( ) : null} @@ -4476,6 +5088,8 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe group.name = shape.name; group.userData.shapeId = shape.id; group.userData.showEdges = showEdges; + group.userData.rulerDimensions = [shapeWidth(shape), shape.height, shapeDepth(shape)] satisfies [number, number, number]; + group.userData.rulerTopologyKey = rulerShapeTopologyKey(shape); group.position.set(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); group.rotation.set( THREE.MathUtils.degToRad(shape.rotationX ?? 0), @@ -4536,9 +5150,11 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe case "cylinder": addMesh(group, new THREE.CylinderGeometry(1, 1, height, shape.sides ?? 96, shape.segments ?? 1), material, shape, undefined, undefined, new THREE.Vector3(width / 2, 1, depth / 2)); break; - case "sphere": - addMesh(group, new THREE.SphereGeometry(1, Math.max(8, (shape.steps ?? 24) * 2), Math.max(6, shape.steps ?? 24)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2)); + case "sphere": { + const { widthSegments, heightSegments } = sphereTessellation(shape.steps); + addMesh(group, new THREE.SphereGeometry(1, widthSegments, heightSegments), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2)); break; + } case "cone": addMesh( group, diff --git a/apps/web/src/components/workplane/EdgeModifierPanel.tsx b/apps/web/src/components/workplane/EdgeModifierPanel.tsx index 19c924a..dc6d25d 100644 --- a/apps/web/src/components/workplane/EdgeModifierPanel.tsx +++ b/apps/web/src/components/workplane/EdgeModifierPanel.tsx @@ -4,7 +4,7 @@ import { useEffect, useState, type CSSProperties } from "react"; import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react"; import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits"; import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes"; -import { edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime"; +import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime"; import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge"; const MIN_EDGE_MODIFIER_AMOUNT = 0.001; @@ -104,8 +104,12 @@ function EdgeModifierSlider({ onBlur={commitDraft} onKeyDown={(event) => { if (event.key === "Enter") { + event.preventDefault(); + event.stopPropagation(); event.currentTarget.blur(); } else if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep)); setEditing(false); } @@ -216,8 +220,8 @@ export function EdgeModifierPanel({
- - + +
{appliedFeatureCount > 0 ? ( @@ -260,27 +264,27 @@ export function EdgeModifierPanel({ step={EDGE_MODIFIER_AMOUNT_STEP} workspace={workspace} length - disabled={!prepared} + disabled={!prepared || busy} onChange={onAmountChange} /> - {kind === "chamfer" ? : null} + {kind === "chamfer" ? : null} - +