Improve editor history, CAD tools, and ruler workflows

This commit is contained in:
Formsmith
2026-07-14 09:43:37 +03:00
parent 20731043e4
commit 400c4bf86e
23 changed files with 1727 additions and 388 deletions
+1
View File
@@ -5,6 +5,7 @@ node_modules/
# Next.js # Next.js
.next/ .next/
.next-dev/
.next-export/ .next-export/
out/ out/
build/ build/
+4 -1
View File
@@ -8,6 +8,10 @@ const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
devIndicators: false, 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], allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins],
env: { env: {
NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false", NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false",
@@ -29,7 +33,6 @@ const nextConfig: NextConfig = {
...(isStaticExport ...(isStaticExport
? { ? {
output: "export" as const, output: "export" as const,
distDir: ".next-export",
trailingSlash: true, trailingSlash: true,
} }
: {}), : {}),
+26
View File
@@ -2837,6 +2837,11 @@ button {
cursor: default; 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,
.workplane-wrap.modifier-edge-pick .three-workplane-host:active { .workplane-wrap.modifier-edge-pick .three-workplane-host:active {
cursor: crosshair; cursor: crosshair;
@@ -2901,6 +2906,16 @@ button {
transition: fill 120ms ease, stroke 120ms ease, filter 120ms ease; 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 { .ruler-overlay.delete-mode .ruler-segment-group:hover .ruler-segment {
stroke: #dc3f36; stroke: #dc3f36;
stroke-width: 3; stroke-width: 3;
@@ -2925,6 +2940,17 @@ button {
pointer-events: none; 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 { .ruler-label {
position: absolute; position: absolute;
z-index: 2; z-index: 2;
+47 -21
View File
@@ -3,6 +3,7 @@
import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds"; import { createLocalId } from "@/lib/localIds";
import { importExtensionSupported } from "@/lib/stlImport"; import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
@@ -34,10 +35,16 @@ type StoredDashboardProject = Partial<DashboardProject> & {
type ProjectShapeCacheEntry = { type ProjectShapeCacheEntry = {
revision: number; revision: number;
shapes: WorkplaneShape[]; shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
}; };
type ProjectShapeRecord = ProjectShapeCacheEntry & { type ProjectShapeRecord = {
id: string; id: string;
revision: number;
shapes: WorkplaneShape[];
history?: EditorHistoryEntry[];
historyIndex?: number;
updatedAt: number; updatedAt: number;
}; };
@@ -57,6 +64,21 @@ function formatUpdated(timestamp: number) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(new Date(timestamp)); 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() { function openProjectShapesDb() {
return new Promise<IDBDatabase>((resolve, reject) => { return new Promise<IDBDatabase>((resolve, reject) => {
if (typeof window === "undefined" || !window.indexedDB) { 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(); const database = await openProjectShapesDb();
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite"); const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite");
@@ -102,10 +124,10 @@ async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], re
}; };
existingRequest.onsuccess = () => { existingRequest.onsuccess = () => {
const existing = existingRequest.result as ProjectShapeRecord | undefined; const existing = existingRequest.result as ProjectShapeRecord | undefined;
if (existing && existing.revision > revision) { if (existing && existing.revision > entry.revision) {
return; return;
} }
store.put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord); store.put({ id: projectId, ...entry, updatedAt: Date.now() } satisfies ProjectShapeRecord);
}; };
transaction.oncomplete = () => { transaction.oncomplete = () => {
database.close(); database.close();
@@ -151,7 +173,7 @@ function readStoredProjects() {
const revision = typeof project.revision === "number" ? project.revision : updatedAt; const revision = typeof project.revision === "number" ? project.revision : updatedAt;
const designShapes = Array.isArray(project.designShapes) ? (project.designShapes as WorkplaneShape[]) : null; const designShapes = Array.isArray(project.designShapes) ? (project.designShapes as WorkplaneShape[]) : null;
if (designShapes) { if (designShapes) {
legacyShapes[id] = { revision, shapes: designShapes }; legacyShapes[id] = projectShapeCacheEntry(revision, designShapes);
} }
return { return {
id, id,
@@ -272,7 +294,7 @@ export default function Home() {
if (Object.keys(legacyShapes).length > 0) { if (Object.keys(legacyShapes).length > 0) {
setProjectShapesById(legacyShapes); setProjectShapesById(legacyShapes);
Object.entries(legacyShapes).forEach(([projectId, entry]) => { 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"); setDashboardNotice("Could not migrate project shapes to larger storage");
}); });
}); });
@@ -348,12 +370,10 @@ export default function Home() {
.then((record) => { .then((record) => {
if (canceled) return; if (canceled) return;
const revision = activeProject.revision ?? record?.revision ?? Date.now(); const revision = activeProject.revision ?? record?.revision ?? Date.now();
const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex);
setProjectShapesById((current) => ({ setProjectShapesById((current) => ({
...current, ...current,
[activeProjectId]: { [activeProjectId]: entry,
revision,
shapes: record?.shapes ?? [],
},
})); }));
}) })
.catch((error) => { .catch((error) => {
@@ -361,10 +381,7 @@ export default function Home() {
setDashboardNotice(error instanceof Error ? error.message : "Could not load project shapes"); setDashboardNotice(error instanceof Error ? error.message : "Could not load project shapes");
setProjectShapesById((current) => ({ setProjectShapesById((current) => ({
...current, ...current,
[activeProjectId]: { [activeProjectId]: projectShapeCacheEntry(activeProject.revision ?? Date.now(), []),
revision: activeProject.revision ?? Date.now(),
shapes: [],
},
})); }));
} }
}); });
@@ -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); const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
nextProjectRevisionRef.current = revision; nextProjectRevisionRef.current = revision;
const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex);
setProjectShapesById((current) => { setProjectShapesById((current) => {
const existing = current[snapshot.projectId]; const existing = current[snapshot.projectId];
if (existing && existing.revision > revision) { if (existing && existing.revision > revision) {
@@ -459,12 +482,12 @@ export default function Home() {
} }
return { return {
...current, ...current,
[snapshot.projectId]: { revision, shapes: snapshot.shapes }, [snapshot.projectId]: entry,
}; };
}); });
const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve(); 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; projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave;
void queuedSave void queuedSave
@@ -519,9 +542,9 @@ export default function Home() {
const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length); const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length);
setProjectShapesById((current) => ({ setProjectShapesById((current) => ({
...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"); setDashboardNotice("Could not prepare project shape storage");
}); });
setProjects((current) => [project, ...current]); setProjects((current) => [project, ...current]);
@@ -542,10 +565,11 @@ export default function Home() {
: importedShapeFromStl(file.name, await file.arrayBuffer()); : importedShapeFromStl(file.name, await file.arrayBuffer());
const project = newProject(projectNameFromFileName(file.name), projects.length, 1); const project = newProject(projectNameFromFileName(file.name), projects.length, 1);
const revision = project.revision ?? project.updatedAt; const revision = project.revision ?? project.updatedAt;
await saveProjectShapes(project.id, [shape], revision); const entry = projectShapeCacheEntry(revision, [shape]);
await saveProjectShapes(project.id, entry);
setProjectShapesById((current) => ({ setProjectShapesById((current) => ({
...current, ...current,
[project.id]: { revision, shapes: [shape] }, [project.id]: entry,
})); }));
setDashboardNotice(`Imported ${file.name}`); setDashboardNotice(`Imported ${file.name}`);
setProjects((current) => [project, ...current]); setProjects((current) => [project, ...current]);
@@ -674,6 +698,8 @@ export default function Home() {
<div className={view === "editor" ? "editor-stage active" : "editor-stage"} aria-hidden={view !== "editor"}> <div className={view === "editor" ? "editor-stage active" : "editor-stage"} aria-hidden={view !== "editor"}>
<SketchForgeEditor <SketchForgeEditor
initialShapes={activeProjectShapeEntry?.shapes ?? []} initialShapes={activeProjectShapeEntry?.shapes ?? []}
initialHistory={activeProjectShapeEntry?.history}
initialHistoryIndex={activeProjectShapeEntry?.historyIndex}
initialSnap={activeProject?.snapGrid ?? DEFAULT_SNAP_GRID} initialSnap={activeProject?.snapGrid ?? DEFAULT_SNAP_GRID}
initialWorkspace={activeProject?.workspace ?? DEFAULT_WORKPLANE_WORKSPACE} initialWorkspace={activeProject?.workspace ?? DEFAULT_WORKPLANE_WORKSPACE}
onHome={openDashboard} onHome={openDashboard}
+313 -150
View File
@@ -17,6 +17,7 @@ import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typefac
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json"; import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
import { manifoldModuleSource } from "@/generated/manifoldModuleSource"; import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64"; import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
import { import {
ToolbarAlignIcon, ToolbarAlignIcon,
ToolbarChamferIcon, ToolbarChamferIcon,
@@ -65,12 +66,14 @@ import {
import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata"; import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata";
import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups"; import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups";
import { import {
CAD_MODIFIER_MAX_SHARP_ANGLE,
CAD_MODIFIER_REQUEST_TIMEOUT_MS, CAD_MODIFIER_REQUEST_TIMEOUT_MS,
cadModifierTimeoutMessage, cadModifierTimeoutMessage,
cadModifierWorkerFailureMessage, cadModifierWorkerFailureMessage,
type CadModifierRequestPhase, type CadModifierRequestPhase,
} from "@/lib/cadModifierRuntime"; } from "@/lib/cadModifierRuntime";
import { cloneWorkplaneShapeSnapshot, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; import { cloneWorkplaneShapeSnapshot, compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory";
import { appendEditorHistorySnapshot, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint, type EditorHistoryEntry, type EditorHistoryState } from "@/lib/editorHistory";
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap"; import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
import { createLocalId } from "@/lib/localIds"; import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames"; import { projectExportFileName } from "@/lib/exportNames";
@@ -183,6 +186,7 @@ const CUTTER_PADDING = 0.05;
const POINT_TOLERANCE = 0.0001; const POINT_TOLERANCE = 0.0001;
const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4; const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4;
const MIN_SHAPE_DIMENSION = 0.01; const MIN_SHAPE_DIMENSION = 0.01;
const MAX_SKETCH_HISTORY_ENTRIES = 100;
const MODEL_DIMENSION_PRECISION = 3; const MODEL_DIMENSION_PRECISION = 3;
const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000; const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000;
const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02; const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02;
@@ -1194,7 +1198,26 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI
const edgeById = new Map(edges.map((edge) => [edge.id, edge])); const edgeById = new Map(edges.map((edge) => [edge.id, edge]));
const selected = new Set<number>([startId]); const selected = new Set<number>([startId]);
const queue = [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) { while (queue.length > 0) {
const id = queue.shift() as number; const id = queue.shift() as number;
const edge = edgeById.get(id); const edge = edgeById.get(id);
@@ -1218,7 +1241,7 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI
} }
function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) { 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) { function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) {
@@ -1296,17 +1319,29 @@ function shapeWithEdgeTreatmentRecord(
}, },
], ],
edgeTreatmentHistory: [ edgeTreatmentHistory: [
...(before.edgeTreatmentHistory ?? []), ...compactEdgeTreatmentHistory(before.edgeTreatmentHistory),
{ {
id: createLocalId("edge-history"), id: createLocalId("edge-history"),
createdAt, createdAt,
feature, feature,
before: cloneWorkplaneShapeSnapshot(before), 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) { function shapeCenterDistance(a: WorkplaneShape, b: WorkplaneShape) {
const ax = a.x; const ax = a.x;
const ay = (a.elevation ?? 0) + a.height / 2; const ay = (a.elevation ?? 0) + a.height / 2;
@@ -1410,7 +1445,7 @@ function groupedShapeWithComponentEdgeTreatment(
...preview, ...preview,
edgeResizeMode: session.preserveEdgeSize ? "preserve" : "scale", edgeResizeMode: session.preserveEdgeSize ? "preserve" : "scale",
edgeTreatments: base.edgeTreatments, edgeTreatments: base.edgeTreatments,
edgeTreatmentHistory: base.edgeTreatmentHistory, edgeTreatmentHistory: base.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(base.edgeTreatmentHistory) : undefined,
groupedBaseWidth: shapeWidth(preview), groupedBaseWidth: shapeWidth(preview),
groupedBaseDepth: shapeDepth(preview), groupedBaseDepth: shapeDepth(preview),
groupedBaseHeight: preview.height, groupedBaseHeight: preview.height,
@@ -1479,9 +1514,13 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[]
...rebuilt.group, ...rebuilt.group,
id: shape.id, id: shape.id,
name: shape.name, name: shape.name,
color: shape.color,
hole: shape.hole || rebuilt.group.hole, hole: shape.hole || rebuilt.group.hole,
locked: shape.locked, locked: shape.locked,
hidden: shape.hidden, hidden: shape.hidden,
edgeResizeMode: shape.edgeResizeMode,
edgeTreatments: shape.edgeTreatments,
edgeTreatmentHistory: shape.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(shape.edgeTreatmentHistory) : undefined,
}), }),
label: restoredChild.label, label: restoredChild.label,
}; };
@@ -1575,8 +1614,7 @@ function cylinderMesh(shape: WorkplaneShape, sides = 96, topRadiusScale = 1): Me
} }
function sphereMesh(shape: WorkplaneShape): MeshData { function sphereMesh(shape: WorkplaneShape): MeshData {
const lat = 12; const { widthSegments: lon, heightSegments: lat } = sphereTessellation(shape.steps);
const lon = 32;
const width = shapeWidth(shape); const width = shapeWidth(shape);
const depth = shapeDepth(shape); const depth = shapeDepth(shape);
const height = shape.height; const height = shape.height;
@@ -1869,7 +1907,7 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null {
geometry.scale(width / 2, 1, depth / 2); geometry.scale(width / 2, 1, depth / 2);
break; break;
case "sphere": 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); geometry.scale(width / 2, height / 2, depth / 2);
break; break;
case "cone": { case "cone": {
@@ -3725,9 +3763,10 @@ function primitiveManifoldForShape(runtime: ManifoldToplevel, shape: WorkplaneSh
} }
if (shape.kind === "sphere") { if (shape.kind === "sphere") {
const { widthSegments } = sphereTessellation(shape.steps);
return transformedPrimitiveManifold( return transformedPrimitiveManifold(
runtime, runtime,
runtime.Manifold.sphere(1, shape.sides ?? 32), runtime.Manifold.sphere(1, widthSegments),
primitiveTransformMatrix(shape, new THREE.Vector3(width / 2, height / 2, depth / 2)), primitiveTransformMatrix(shape, new THREE.Vector3(width / 2, height / 2, depth / 2)),
created, created,
); );
@@ -4938,62 +4977,10 @@ function readMcpEditorIdentity() {
return identity; 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({ export function SketchForgeEditor({
initialShapes = [], initialShapes = [],
initialHistory,
initialHistoryIndex,
initialSnap, initialSnap,
initialWorkspace, initialWorkspace,
onHome, onHome,
@@ -5005,22 +4992,37 @@ export function SketchForgeEditor({
projectRevision = 0, projectRevision = 0,
}: { }: {
initialShapes?: WorkplaneShape[]; initialShapes?: WorkplaneShape[];
initialHistory?: EditorHistoryEntry[];
initialHistoryIndex?: number;
initialSnap?: GridSize; initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings; initialWorkspace?: WorkplaneWorkspaceSettings;
onHome?: () => void; 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; onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void; onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
projectId?: string | null; projectId?: string | null;
projectName?: string; projectName?: string;
projectRevision?: number; projectRevision?: number;
} = {}) { } = {}) {
const [shapes, setShapes] = useState<WorkplaneShape[]>(() => initialShapes.map(canonicalizeShape)); const initialSceneRef = useRef<WorkplaneShape[] | null>(null);
if (initialSceneRef.current === null) {
initialSceneRef.current = initialShapes.map(canonicalizeShape);
}
const initialHistoryStateRef = useRef<EditorHistoryState | null>(null);
if (initialHistoryStateRef.current === null) {
initialHistoryStateRef.current = hydrateEditorHistoryState(initialSceneRef.current, initialHistory, initialHistoryIndex);
}
const [shapes, setShapes] = useState<WorkplaneShape[]>(() => initialSceneRef.current as WorkplaneShape[]);
const [selectedIds, setSelectedIds] = useState<string[]>([]); const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [clipboard, setClipboard] = useState<WorkplaneShape[]>([]); const [clipboard, setClipboard] = useState<WorkplaneShape[]>([]);
const [systemClipboardSupported, setSystemClipboardSupported] = useState(false); const [systemClipboardSupported, setSystemClipboardSupported] = useState(false);
const [history, setHistory] = useState<WorkplaneShape[][]>([[]]); const [history, setHistory] = useState<EditorHistoryEntry[]>(() => (initialHistoryStateRef.current as EditorHistoryState).entries);
const [historyIndex, setHistoryIndex] = useState(0); const [historyIndex, setHistoryIndex] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).index);
const [placementElevation, setPlacementElevation] = useState(0); const [placementElevation, setPlacementElevation] = useState(0);
const [workspaceSettings, setWorkspaceSettings] = useState<WorkplaneWorkspaceSettings>(() => normalizeWorkspaceSettings(initialWorkspace)); const [workspaceSettings, setWorkspaceSettings] = useState<WorkplaneWorkspaceSettings>(() => normalizeWorkspaceSettings(initialWorkspace));
const [workplaneMode, setWorkplaneMode] = useState(false); const [workplaneMode, setWorkplaneMode] = useState(false);
@@ -5051,6 +5053,7 @@ export function SketchForgeEditor({
const noticeRef = useRef(notice); const noticeRef = useRef(notice);
const projectInfoRef = useRef({ projectId: projectId ?? null, projectName }); const projectInfoRef = useRef({ projectId: projectId ?? null, projectName });
const historyIndexRef = useRef(historyIndex); const historyIndexRef = useRef(historyIndex);
const historyRef = useRef(history);
const interactionHistoryStartRef = useRef(""); const interactionHistoryStartRef = useRef("");
const interactionHistoryChangedRef = useRef(false); const interactionHistoryChangedRef = useRef(false);
const interactionHistoryTimerRef = useRef<number | null>(null); const interactionHistoryTimerRef = useRef<number | null>(null);
@@ -5061,6 +5064,8 @@ export function SketchForgeEditor({
const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile()); const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile());
const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]); const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]);
const [sketchHistoryIndex, setSketchHistoryIndex] = useState(0); const [sketchHistoryIndex, setSketchHistoryIndex] = useState(0);
const sketchHistoryRef = useRef(sketchHistory);
const sketchHistoryIndexRef = useRef(sketchHistoryIndex);
const [sketchActivePointId, setSketchActivePointId] = useState<string | null>(null); const [sketchActivePointId, setSketchActivePointId] = useState<string | null>(null);
const [sketchSelection, setSketchSelection] = useState<SketchSelection>(null); const [sketchSelection, setSketchSelection] = useState<SketchSelection>(null);
const [sketchMeasureStart, setSketchMeasureStart] = useState<SketchPoint | null>(null); const [sketchMeasureStart, setSketchMeasureStart] = useState<SketchPoint | null>(null);
@@ -5179,6 +5184,8 @@ export function SketchForgeEditor({
selectedEdgeIds: [], selectedEdgeIds: [],
busy: false, busy: false,
prepared: true, prepared: true,
preview: null,
componentPreviews: [],
error: message.selectableEdgeIds.length ? null : "No sharp manifold edges were found at this threshold", error: message.selectableEdgeIds.length ? null : "No sharp manifold edges were found at this threshold",
} : current); } : current);
if (message.selectableEdgeIds.length) setNotice("Select highlighted edges, then adjust the preview"); if (message.selectableEdgeIds.length) setNotice("Select highlighted edges, then adjust the preview");
@@ -5238,12 +5245,19 @@ export function SketchForgeEditor({
const invalidateCadModifierSession = useCallback(() => { const invalidateCadModifierSession = useCallback(() => {
const wasActive = cadModifierBaseShapeRef.current !== null; const wasActive = cadModifierBaseShapeRef.current !== null;
if (!wasActive) return false; if (!wasActive) return false;
const hadInFlightRequest = cadModifierWatchdogRef.current !== null;
clearCadModifierWatchdog(); clearCadModifierWatchdog();
const requestId = cadModifierRequestRef.current + 1; const requestId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = requestId; cadModifierRequestRef.current = requestId;
cadModifierLatestPreviewRef.current = requestId; cadModifierLatestPreviewRef.current = requestId;
cadModifierPrepareRef.current = requestId; cadModifierPrepareRef.current = requestId;
if (hadInFlightRequest) {
cadModifierWorkerRef.current?.terminate();
cadModifierWorkerRef.current = null;
cadModifierWorkerRestartRef.current();
} else {
cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest); cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest);
}
cadModifierBaseShapeRef.current = null; cadModifierBaseShapeRef.current = null;
cadModifierBaseFingerprintRef.current = ""; cadModifierBaseFingerprintRef.current = "";
cadModifierSourcePartsRef.current = []; cadModifierSourcePartsRef.current = [];
@@ -5303,6 +5317,14 @@ export function SketchForgeEditor({
useEffect(() => { useEffect(() => {
selectedIdsRef.current = selectedIds; 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]); }, [selectedIds]);
useEffect(() => { useEffect(() => {
@@ -5321,6 +5343,18 @@ export function SketchForgeEditor({
historyIndexRef.current = historyIndex; historyIndexRef.current = historyIndex;
}, [historyIndex]); }, [historyIndex]);
useEffect(() => {
historyRef.current = history;
}, [history]);
useEffect(() => {
sketchHistoryRef.current = sketchHistory;
}, [sketchHistory]);
useEffect(() => {
sketchHistoryIndexRef.current = sketchHistoryIndex;
}, [sketchHistoryIndex]);
useEffect(() => { useEffect(() => {
edgeModifierRef.current = edgeModifier; edgeModifierRef.current = edgeModifier;
}, [edgeModifier]); }, [edgeModifier]);
@@ -5351,7 +5385,7 @@ export function SketchForgeEditor({
); );
const toggleModifierEdge = useCallback((id: number, singleEdge = false) => { const toggleModifierEdge = useCallback((id: number, singleEdge = false) => {
setEdgeModifier((current) => { 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)); const allowed = new Set(current.edges.filter((edge) => selectableCadModifierEdge(edge, current.sharpAngle)).map((edge) => edge.id));
if (!allowed.has(id)) return current; if (!allowed.has(id)) return current;
const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id]; const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id];
@@ -5462,13 +5496,30 @@ export function SketchForgeEditor({
projectSyncTimerRef.current = window.setTimeout(() => { projectSyncTimerRef.current = window.setTimeout(() => {
lastProjectShapesSyncRef.current = serialized; lastProjectShapesSyncRef.current = serialized;
lastProjectShapesEchoRef.current = serialized; lastProjectShapesEchoRef.current = serialized;
onProjectShapesChange({ projectId, shapes: canonicalNext }); onProjectShapesChange({
projectId,
shapes: canonicalNext,
history: historyRef.current,
historyIndex: historyIndexRef.current,
});
projectSyncTimerRef.current = null; projectSyncTimerRef.current = null;
}, 120); }, 120);
}, },
[onProjectShapesChange, projectId], [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 finalizeInteractionHistory = useCallback(() => {
const startFingerprint = interactionHistoryStartRef.current; const startFingerprint = interactionHistoryStartRef.current;
const hadChanges = interactionHistoryChangedRef.current; const hadChanges = interactionHistoryChangedRef.current;
@@ -5484,22 +5535,8 @@ export function SketchForgeEditor({
return; return;
} }
setHistory((current) => { appendHistorySnapshot(canonicalNext, selectedIdsRef.current);
const historyIndex = Math.min(historyIndexRef.current, Math.max(0, current.length - 1)); }, [appendHistorySnapshot]);
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;
});
}, []);
useEffect(() => { useEffect(() => {
if (projectInteractionActive || !pendingProjectShapesRef.current) { if (projectInteractionActive || !pendingProjectShapesRef.current) {
@@ -5517,6 +5554,7 @@ export function SketchForgeEditor({
if (interactionHistoryTimerRef.current !== null) { if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current); window.clearTimeout(interactionHistoryTimerRef.current);
interactionHistoryTimerRef.current = null; interactionHistoryTimerRef.current = null;
finalizeInteractionHistory();
} }
if (!projectInteractionActiveRef.current) { if (!projectInteractionActiveRef.current) {
interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current); interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current);
@@ -5557,20 +5595,18 @@ export function SketchForgeEditor({
const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : []; const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : [];
const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id)); const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id));
shapesRef.current = canonicalNext; shapesRef.current = canonicalNext;
selectedIdsRef.current = validSelection;
setShapes(canonicalNext); setShapes(canonicalNext);
setSelectedIds(validSelection); setSelectedIds(validSelection);
setHistory((current) => { const changed = appendHistorySnapshot(canonicalNext, validSelection);
const trimmed = current.slice(0, historyIndex + 1);
historyIndexRef.current = trimmed.length;
setHistoryIndex(historyIndexRef.current);
return [...trimmed, canonicalNext];
});
if (message) { if (message) {
setNotice(message); setNotice(message);
} }
if (changed) {
syncProjectShapes(canonicalNext); syncProjectShapes(canonicalNext);
}
}, },
[historyIndex, selectedIds, syncProjectShapes], [appendHistorySnapshot, selectedIds, syncProjectShapes],
); );
const removeEdgeTreatment = useCallback(async (optionId: string) => { const removeEdgeTreatment = useCallback(async (optionId: string) => {
@@ -5587,32 +5623,46 @@ export function SketchForgeEditor({
setNotice("Choose an edge feature to remove"); setNotice("Choose an edge feature to remove");
return; return;
} }
const sourceFingerprint = projectShapesFingerprint([selectedShape]);
const sourceProjectId = projectInfoRef.current.projectId;
const restored = await restoreEdgeTreatmentInShape(selectedShape, option.path, option.entryId); const restored = await restoreEdgeTreatmentInShape(selectedShape, option.path, option.entryId);
if (!restored) { if (!restored) {
setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove"); setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove");
return; 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(); invalidateCadModifierSession();
commitShapes( 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, restored.shape.id,
`Removed ${restored.label}`, `Removed ${restored.label}`,
); );
setNotice(`Removed ${restored.label}`); setNotice(`Removed ${restored.label}`);
}, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape, shapes]); }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape]);
const commitSketchProfile = useCallback( const commitSketchProfile = useCallback(
(next: SketchProfile, message?: string) => { (next: SketchProfile, message?: string) => {
const snapshot = cloneSketchProfile(next); 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); setSketchProfile(snapshot);
setSketchHistory((current) => { if (latest && JSON.stringify(latest) === JSON.stringify(snapshot)) {
const trimmed = current.slice(0, sketchHistoryIndex + 1); return;
return [...trimmed, cloneSketchProfile(snapshot)]; }
}); const nextHistory = [...trimmed, cloneSketchProfile(snapshot)].slice(-MAX_SKETCH_HISTORY_ENTRIES);
setSketchHistoryIndex(sketchHistoryIndex + 1); sketchHistoryRef.current = nextHistory;
sketchHistoryIndexRef.current = nextHistory.length - 1;
setSketchHistory(nextHistory);
setSketchHistoryIndex(sketchHistoryIndexRef.current);
if (message) setNotice(message); if (message) setNotice(message);
}, },
[sketchHistoryIndex], [],
); );
const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => { const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => {
@@ -5621,7 +5671,10 @@ export function SketchForgeEditor({
setSketchActive(true); setSketchActive(true);
setSketchTool(profile?.segments.length ? "select" : "line"); setSketchTool(profile?.segments.length ? "select" : "line");
setSketchProfile(initial); setSketchProfile(initial);
setSketchHistory([cloneSketchProfile(initial)]); const initialHistory = [cloneSketchProfile(initial)];
sketchHistoryRef.current = initialHistory;
sketchHistoryIndexRef.current = 0;
setSketchHistory(initialHistory);
setSketchHistoryIndex(0); setSketchHistoryIndex(0);
setSketchActivePointId(null); setSketchActivePointId(null);
setSketchSelection(null); setSketchSelection(null);
@@ -5650,30 +5703,36 @@ export function SketchForgeEditor({
}, []); }, []);
const sketchUndo = useCallback(() => { const sketchUndo = useCallback(() => {
if (sketchHistoryIndex <= 0) { const currentHistory = sketchHistoryRef.current;
const currentIndex = sketchHistoryIndexRef.current;
if (currentIndex <= 0) {
setNotice("Nothing to undo in this sketch"); setNotice("Nothing to undo in this sketch");
return; return;
} }
const nextIndex = sketchHistoryIndex - 1; const nextIndex = currentIndex - 1;
sketchHistoryIndexRef.current = nextIndex;
setSketchHistoryIndex(nextIndex); setSketchHistoryIndex(nextIndex);
setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile()));
setSketchActivePointId(null); setSketchActivePointId(null);
setSketchSelection(null); setSketchSelection(null);
setNotice("Sketch undo"); setNotice("Sketch undo");
}, [sketchHistory, sketchHistoryIndex]); }, []);
const sketchRedo = useCallback(() => { 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"); setNotice("Nothing to redo in this sketch");
return; return;
} }
const nextIndex = sketchHistoryIndex + 1; const nextIndex = currentIndex + 1;
sketchHistoryIndexRef.current = nextIndex;
setSketchHistoryIndex(nextIndex); setSketchHistoryIndex(nextIndex);
setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile()));
setSketchActivePointId(null); setSketchActivePointId(null);
setSketchSelection(null); setSketchSelection(null);
setNotice("Sketch redo"); setNotice("Sketch redo");
}, [sketchHistory, sketchHistoryIndex]); }, []);
const setActiveSketchTool = useCallback((tool: SketchTool) => { const setActiveSketchTool = useCallback((tool: SketchTool) => {
setSketchTool(tool); setSketchTool(tool);
@@ -5999,7 +6058,11 @@ export function SketchForgeEditor({
lastProjectShapesEchoRef.current = null; lastProjectShapesEchoRef.current = null;
return; return;
} }
if (lastProjectIdRef.current !== projectId) { if (projectInteractionActiveRef.current) {
return;
}
const projectChanged = lastProjectIdRef.current !== projectId;
if (projectChanged) {
lastProjectIdRef.current = projectId; lastProjectIdRef.current = projectId;
lastProjectShapesSyncRef.current = ""; lastProjectShapesSyncRef.current = "";
lastProjectShapesEchoRef.current = null; lastProjectShapesEchoRef.current = null;
@@ -6007,28 +6070,30 @@ export function SketchForgeEditor({
const incoming = initialShapes.map(canonicalizeShape); const incoming = initialShapes.map(canonicalizeShape);
const incomingSerialized = projectShapesFingerprint(incoming); const incomingSerialized = projectShapesFingerprint(incoming);
// The parent echoes shapes after a local save; rehydrating that echo can reset active transform state. // 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; lastProjectShapesSyncRef.current = incomingSerialized;
return; return;
} }
if (projectInteractionActiveRef.current) {
return;
}
lastProjectShapesSyncRef.current = incomingSerialized; lastProjectShapesSyncRef.current = incomingSerialized;
if (projectSyncTimerRef.current !== null) { if (projectSyncTimerRef.current !== null) {
window.clearTimeout(projectSyncTimerRef.current); window.clearTimeout(projectSyncTimerRef.current);
projectSyncTimerRef.current = null; projectSyncTimerRef.current = null;
} }
if (incomingSerialized === projectShapesFingerprint(shapes)) { if (!projectChanged && incomingSerialized === projectShapesFingerprint(shapes)) {
return; return;
} }
const hydratedHistory = hydrateEditorHistoryState(incoming, initialHistory, initialHistoryIndex);
projectHydratingRef.current = true; projectHydratingRef.current = true;
shapesRef.current = incoming;
selectedIdsRef.current = [];
historyRef.current = hydratedHistory.entries;
historyIndexRef.current = hydratedHistory.index;
setShapes(incoming); setShapes(incoming);
setSelectedIds([]); setSelectedIds([]);
setHistory([incoming]); setHistory(hydratedHistory.entries);
setHistoryIndex(0); setHistoryIndex(hydratedHistory.index);
setNotice(incoming.length ? "Project synced" : "Ready"); setNotice(incoming.length ? "Project synced" : "Ready");
}, [initialShapes, projectId, projectRevision]); }, [initialHistory, initialHistoryIndex, initialShapes, projectId, projectInteractionActive, projectRevision]);
useEffect(() => { useEffect(() => {
if (!projectId || !onProjectShapesChange) { if (!projectId || !onProjectShapesChange) {
@@ -6142,6 +6207,7 @@ export function SketchForgeEditor({
}, [hasSelection, selectedShapes]); }, [hasSelection, selectedShapes]);
const pasteShape = useCallback(async () => { const pasteShape = useCallback(async () => {
const sourceProjectId = projectInfoRef.current.projectId;
const systemClipboard = await readSystemClipboard(); const systemClipboard = await readSystemClipboard();
const sharedClipboard = readSharedClipboard(); const sharedClipboard = readSharedClipboard();
const sourceClipboard = systemClipboard.length > 0 ? systemClipboard : sharedClipboard.length > 0 ? sharedClipboard : clipboard; const sourceClipboard = systemClipboard.length > 0 ? systemClipboard : sharedClipboard.length > 0 ? sharedClipboard : clipboard;
@@ -6149,6 +6215,10 @@ export function SketchForgeEditor({
setNotice("SketchForge clipboard is empty"); setNotice("SketchForge clipboard is empty");
return; return;
} }
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice("Paste cancelled because the project changed");
return;
}
if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) { if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) {
setClipboard(sourceClipboard); setClipboard(sourceClipboard);
} }
@@ -6162,38 +6232,56 @@ export function SketchForgeEditor({
}, [clipboard, commitShapes]); }, [clipboard, commitShapes]);
const undo = useCallback(() => { const undo = useCallback(() => {
if (projectInteractionActiveRef.current) {
setNotice("Finish the current drag or transform before undoing");
return;
}
const modifierCancelled = invalidateCadModifierSession(); 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"); setNotice(modifierCancelled ? "Edge modifier cancelled" : "Nothing to undo");
return; return;
} }
const nextIndex = historyIndex - 1; const nextIndex = currentIndex - 1;
const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); 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; historyIndexRef.current = nextIndex;
shapesRef.current = nextShapes; shapesRef.current = nextShapes;
selectedIdsRef.current = nextSelection;
setHistoryIndex(nextIndex); setHistoryIndex(nextIndex);
setShapes(nextShapes); setShapes(nextShapes);
setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); setSelectedIds(nextSelection);
syncProjectShapes(nextShapes); syncProjectShapes(nextShapes);
setNotice(modifierCancelled ? "Edge modifier cancelled · Undo" : "Undo"); setNotice(modifierCancelled ? "Edge modifier cancelled · Undo" : "Undo");
}, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); }, [invalidateCadModifierSession, syncProjectShapes]);
const redo = useCallback(() => { 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"); setNotice("Nothing to redo");
return; return;
} }
const modifierCancelled = invalidateCadModifierSession(); const modifierCancelled = invalidateCadModifierSession();
const nextIndex = historyIndex + 1; const nextIndex = currentIndex + 1;
const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); 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; historyIndexRef.current = nextIndex;
shapesRef.current = nextShapes; shapesRef.current = nextShapes;
selectedIdsRef.current = nextSelection;
setHistoryIndex(nextIndex); setHistoryIndex(nextIndex);
setShapes(nextShapes); setShapes(nextShapes);
setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); setSelectedIds(nextSelection);
syncProjectShapes(nextShapes); syncProjectShapes(nextShapes);
setNotice(modifierCancelled ? "Edge modifier cancelled · Redo" : "Redo"); setNotice(modifierCancelled ? "Edge modifier cancelled · Redo" : "Redo");
}, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); }, [invalidateCadModifierSession, syncProjectShapes]);
const toggleAlignMode = useCallback(() => { const toggleAlignMode = useCallback(() => {
if (selectedShapes.length < 2) { if (selectedShapes.length < 2) {
@@ -6325,8 +6413,22 @@ export function SketchForgeEditor({
cadModifierRequestRef.current = requestId; cadModifierRequestRef.current = requestId;
return new Promise<CadModifierWorkerResponse>((resolve, reject) => { return new Promise<CadModifierWorkerResponse>((resolve, reject) => {
const timer = window.setTimeout(() => { const timer = window.setTimeout(() => {
cadModifierPendingRef.current.delete(requestId); if (!cadModifierPendingRef.current.has(requestId)) return;
reject(new Error("Timed out waiting for the CAD worker")); 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); }, timeoutMs);
cadModifierPendingRef.current.set(requestId, { resolve, reject, timer }); cadModifierPendingRef.current.set(requestId, { resolve, reject, timer });
try { try {
@@ -6349,6 +6451,7 @@ export function SketchForgeEditor({
setNotice(`Select one unlocked solid to ${kind}`); setNotice(`Select one unlocked solid to ${kind}`);
return; return;
} }
invalidateCadModifierSession();
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape); const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape]; const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape];
@@ -6416,7 +6519,7 @@ export function SketchForgeEditor({
} }
cadModifierPrepareRef.current = prepareRequestId; cadModifierPrepareRef.current = prepareRequestId;
armCadModifierWatchdog(prepareRequestId, "prepare"); armCadModifierWatchdog(prepareRequestId, "prepare");
}, [armCadModifierWatchdog, postCadModifierRequest, selectedShape, selectedShapes.length]); }, [armCadModifierWatchdog, invalidateCadModifierSession, postCadModifierRequest, selectedShape, selectedShapes.length]);
const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => { const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => {
if (shape.locked || shape.hole) { if (shape.locked || shape.hole) {
@@ -6468,8 +6571,10 @@ export function SketchForgeEditor({
params: Record<string, unknown>, params: Record<string, unknown>,
) => { ) => {
invalidateCadModifierSession(); invalidateCadModifierSession();
const sourceFingerprint = projectShapesFingerprint([shape]);
const sourceProjectId = projectInfoRef.current.projectId;
const kind: CadModifierKind = params.kind === "fillet" ? "fillet" : "chamfer"; 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 amount = Math.max(MIN_EDGE_MODIFIER_AMOUNT, mcpNumber(params.amount, 1));
const chamferAngle = Math.max(5, Math.min(85, mcpNumber(params.chamferAngle, 45))); const chamferAngle = Math.max(5, Math.min(85, mcpNumber(params.chamferAngle, 45)));
const quality: CadModifierQuality = params.quality === "draft" || params.quality === "fine" ? params.quality : "standard"; const quality: CadModifierQuality = params.quality === "draft" || params.quality === "fine" ? params.quality : "standard";
@@ -6529,7 +6634,21 @@ export function SketchForgeEditor({
}; };
const createdAt = Date.now(); const createdAt = Date.now();
const groupedModifiedShape = groupedShapeWithComponentEdgeTreatment(shape, preview, sourceParts, session, feature, createdAt); 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( commitShapes(
shapesRef.current.map((candidate) => candidate.id === shape.id ? modifiedShape : candidate), shapesRef.current.map((candidate) => candidate.id === shape.id ? modifiedShape : candidate),
modifiedShape.id, modifiedShape.id,
@@ -6581,7 +6700,7 @@ export function SketchForgeEditor({
createdAt, createdAt,
); );
const modifiedShape: WorkplaneShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord( const modifiedShape: WorkplaneShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(
previewShape, bakedEdgeTreatmentPreview(previewShape, base),
base, base,
feature, feature,
edgeModifier.preserveEdgeSize, edgeModifier.preserveEdgeSize,
@@ -6601,7 +6720,9 @@ export function SketchForgeEditor({
if (event.key === "Escape") { if (event.key === "Escape") {
event.preventDefault(); event.preventDefault();
cancelEdgeModifier(); 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(); event.preventDefault();
applyEdgeModifier(); applyEdgeModifier();
} }
@@ -6787,20 +6908,26 @@ export function SketchForgeEditor({
return; return;
} }
const sourceFingerprint = projectShapesFingerprint(shapesRef.current);
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildGroupedShapeFromSelection(selectedShapes); 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; const { group } = result;
if (!group) { if (!group) {
if (result.consumed) { if (result.consumed) {
const selected = new Set(selectedIds); 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; return;
} }
setNotice(result.failureNotice); setNotice(result.failureNotice);
return; return;
} }
const selected = new Set(selectedIds); const selected = new Set(selectedIds);
commitShapes([...shapes.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`); commitShapes([...shapesRef.current.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`);
}, [commitShapes, selectedIds, selectedShapes, shapes]); }, [commitShapes, selectedIds, selectedShapes]);
const intersectSelected = useCallback(async () => { const intersectSelected = useCallback(async () => {
const groupable = selectedShapes.filter((shape) => !shape.locked); const groupable = selectedShapes.filter((shape) => !shape.locked);
@@ -6811,14 +6938,20 @@ export function SketchForgeEditor({
return; return;
} }
const sourceFingerprint = projectShapesFingerprint(shapesRef.current);
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildIntersectionShapeFromSelection(groupable); 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) { if (!result.group && !result.empty) {
setNotice(result.failureNotice); setNotice(result.failureNotice);
return; return;
} }
const operandIds = new Set(groupable.map((shape) => shape.id)); 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) { if (result.empty) {
commitShapes(remainingShapes, null, "Intersection is empty"); commitShapes(remainingShapes, null, "Intersection is empty");
return; return;
@@ -6829,7 +6962,7 @@ export function SketchForgeEditor({
return; return;
} }
commitShapes([...remainingShapes, intersection], intersection.id, `Intersected ${groupable.length} shapes`); commitShapes([...remainingShapes, intersection], intersection.id, `Intersected ${groupable.length} shapes`);
}, [commitShapes, selectedShapes, shapes]); }, [commitShapes, selectedShapes]);
const ungroupSelected = useCallback(() => { const ungroupSelected = useCallback(() => {
const groups = selectedShapes.filter((shape) => shape.groupedShapes?.length); const groups = selectedShapes.filter((shape) => shape.groupedShapes?.length);
@@ -6929,7 +7062,17 @@ export function SketchForgeEditor({
const profile = defaultMcpSketchProfile(width, depth); const profile = defaultMcpSketchProfile(width, depth);
const extruded = shapeFromSketchProfile(profile, height); const extruded = shapeFromSketchProfile(profile, height);
if (!extruded) throw new Error("Could not create the sketch profile"); 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") { } else if (kind === "box" || kind === "cylinder") {
shape = sceneShape({ shape = sceneShape({
name, name,
@@ -6950,8 +7093,9 @@ export function SketchForgeEditor({
} else { } else {
throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch"); throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch");
} }
commitShapes([...currentShapes(), shape], shape.id, `${shape.name} added by MCP`); const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape));
return { object: mcpShapeSummary(shape) }; commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`);
return { object: mcpShapeSummary(committedShape) };
} }
if (command.action === "import_mesh") { if (command.action === "import_mesh") {
@@ -7016,6 +7160,9 @@ export function SketchForgeEditor({
if (!target) throw new Error("Object not found"); if (!target) throw new Error("Object not found");
if (target.locked) throw new Error("Unlock the object before updating it"); if (target.locked) throw new Error("Unlock the object before updating it");
const patch: ShapeUpdatePatch = {}; 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) => { (["x", "z", "elevation", "width", "depth", "height", "size", "rotation", "rotationX", "rotationZ"] as const).forEach((key) => {
if (typeof params[key] === "number" && Number.isFinite(params[key])) { if (typeof params[key] === "number" && Number.isFinite(params[key])) {
patch[key] = params[key]; patch[key] = params[key];
@@ -7029,7 +7176,8 @@ export function SketchForgeEditor({
const patched = { ...shape, ...cleanShapePatch(patch) }; const patched = { ...shape, ...cleanShapePatch(patch) };
const width = shapeWidth(patched); const width = shapeWidth(patched);
const depth = shapeDepth(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; const updated = nextShapes.find((shape) => shape.id === target.id) as WorkplaneShape;
commitShapes(nextShapes, target.id, `${updated.name} updated by MCP`); 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)); 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.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"); 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); 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.group) {
if (result.consumed) { if (result.consumed) {
commitShapes(currentShapes().filter((shape) => !ids.has(shape.id)), null, "MCP group consumed solid"); 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)) { if (operands.some((shape) => shape.locked)) {
throw new Error("Unlock every boolean operand before cutting"); throw new Error("Unlock every boolean operand before cutting");
} }
const sourceFingerprint = projectShapesFingerprint(currentShapes());
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildGroupedShapeFromSelection(operands); 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)); const remainingShapes = currentShapes().filter((shape) => !operandIds.has(shape.id));
if (result.consumed) { if (result.consumed) {
commitShapes(remainingShapes, null, "MCP cut consumed solid"); commitShapes(remainingShapes, null, "MCP cut consumed solid");
@@ -7136,7 +7294,7 @@ export function SketchForgeEditor({
const target = findShape(params.id); const target = findShape(params.id);
if (!target) throw new Error("Object not found"); if (!target) throw new Error("Object not found");
invalidateCadModifierSession(); 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 { response } = await prepareCadModifierForMcp(target, sharpAngle);
const selectableEdgeIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id); const selectableEdgeIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id);
return { object: mcpShapeSummary(target), sharpAngle, selectableEdgeIds, edges: response.edges }; return { object: mcpShapeSummary(target), sharpAngle, selectableEdgeIds, edges: response.edges };
@@ -7551,6 +7709,7 @@ export function SketchForgeEditor({
return; return;
} }
const sourceProjectId = projectInfoRef.current.projectId;
try { try {
let nextShape: WorkplaneShape; let nextShape: WorkplaneShape;
if (isStep) { if (isStep) {
@@ -7562,12 +7721,16 @@ export function SketchForgeEditor({
} else { } else {
nextShape = importedShapeFromStl(file.name, await file.arrayBuffer()); 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); setTopPanel(null);
} catch (error) { } catch (error) {
setNotice(error instanceof Error ? error.message : `Could not import ${file.name}`); setNotice(error instanceof Error ? error.message : `Could not import ${file.name}`);
} }
}, [commitShapes, shapes]); }, [commitShapes]);
const selectFiles = useCallback( const selectFiles = useCallback(
(files: FileList | File[]) => { (files: FileList | File[]) => {
@@ -7820,8 +7983,8 @@ export function SketchForgeEditor({
setTopPanel(null); setTopPanel(null);
setMenuOpen(false); setMenuOpen(false);
}} }}
canUndo={historyIndex > 0 || Boolean(edgeModifier)} canUndo={!projectInteractionActive && (historyIndex > 0 || Boolean(edgeModifier))}
canRedo={historyIndex < history.length - 1} canRedo={!projectInteractionActive && historyIndex < history.length - 1}
canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} 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))} canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))}
canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} 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)} onQualityChange={(quality) => setEdgeModifier((current) => current?.prepared ? { ...current, quality, preview: null, busy: true, error: null } : current)}
onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => { onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => {
if (!current?.prepared) return 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 const availableIds = new Set(current.edges
.filter((edge) => selectableCadModifierEdge(edge, nextAngle)) .filter((edge) => selectableCadModifierEdge(edge, nextAngle))
.map((edge) => edge.id)); .map((edge) => edge.id));
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,7 @@ import { useEffect, useState, type CSSProperties } from "react";
import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react"; import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits"; import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes"; 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"; import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_EDGE_MODIFIER_AMOUNT = 0.001; const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
@@ -104,8 +104,12 @@ function EdgeModifierSlider({
onBlur={commitDraft} onBlur={commitDraft}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.key === "Enter") { if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
event.currentTarget.blur(); event.currentTarget.blur();
} else if (event.key === "Escape") { } else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep)); setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(false); setEditing(false);
} }
@@ -216,8 +220,8 @@ export function EdgeModifierPanel({
</div> </div>
<div className="edge-modifier-quick-actions"> <div className="edge-modifier-quick-actions">
<button type="button" disabled={!prepared} onClick={onSelectAll}>All sharp edges</button> <button type="button" disabled={!prepared || busy} onClick={onSelectAll}>All sharp edges</button>
<button type="button" disabled={!prepared} onClick={onClear}>Clear</button> <button type="button" disabled={!prepared || busy} onClick={onClear}>Clear</button>
</div> </div>
{appliedFeatureCount > 0 ? ( {appliedFeatureCount > 0 ? (
@@ -260,27 +264,27 @@ export function EdgeModifierPanel({
step={EDGE_MODIFIER_AMOUNT_STEP} step={EDGE_MODIFIER_AMOUNT_STEP}
workspace={workspace} workspace={workspace}
length length
disabled={!prepared} disabled={!prepared || busy}
onChange={onAmountChange} onChange={onAmountChange}
/> />
{kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} disabled={!prepared} onChange={onChamferAngleChange} /> : null} {kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} disabled={!prepared || busy} onChange={onChamferAngleChange} /> : null}
<EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={120} step={1} unit="deg" workspace={workspace} disabled={!prepared} onChange={onSharpAngleChange} /> <EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={CAD_MODIFIER_MAX_SHARP_ANGLE} step={1} unit="deg" workspace={workspace} disabled={!prepared || busy} onChange={onSharpAngleChange} />
<label className="edge-modifier-check"> <label className="edge-modifier-check">
<input type="checkbox" checked={tangentChain} disabled={!prepared} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} /> <input type="checkbox" checked={tangentChain} disabled={!prepared || busy} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
<span>Select tangent chains</span> <span>Select tangent chains</span>
</label> </label>
<label className="edge-modifier-check"> <label className="edge-modifier-check">
<input type="checkbox" checked={preserveEdgeSize} disabled={!prepared} onChange={(event) => onPreserveEdgeSizeChange(event.currentTarget.checked)} /> <input type="checkbox" checked={preserveEdgeSize} disabled={!prepared || busy} onChange={(event) => onPreserveEdgeSizeChange(event.currentTarget.checked)} />
<span>Keep edge size when resizing</span> <span>Keep edge size when resizing</span>
</label> </label>
<label className="edge-modifier-field"> <label className="edge-modifier-field">
<span>Preview quality</span> <span>Preview quality</span>
<select value={quality} disabled={!prepared} onChange={(event) => onQualityChange(event.currentTarget.value as CadModifierQuality)}> <select value={quality} disabled={!prepared || busy} onChange={(event) => onQualityChange(event.currentTarget.value as CadModifierQuality)}>
<option value="draft">Draft</option> <option value="draft">Draft</option>
<option value="standard">Standard</option> <option value="standard">Standard</option>
<option value="fine">Fine</option> <option value="fine">Fine</option>
@@ -106,8 +106,6 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
if (shape.kind === "cylinder") { if (shape.kind === "cylinder") {
return [ return [
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) }, { label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 10, onChange: (bevel) => onUpdate({ bevel }) },
{ label: "Segments", value: shape.segments ?? 1, min: 1, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth }, { label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth }, { label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight }, { label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
@@ -208,6 +206,7 @@ export function ShapeInspector({
onEditSketch, onEditSketch,
canSeparateParts = false, canSeparateParts = false,
onSeparateParts, onSeparateParts,
onInteractionActiveChange,
}: { }: {
shape: WorkplaneShape; shape: WorkplaneShape;
snap: GridSize; snap: GridSize;
@@ -220,6 +219,7 @@ export function ShapeInspector({
onEditSketch?: () => void; onEditSketch?: () => void;
canSeparateParts?: boolean; canSeparateParts?: boolean;
onSeparateParts?: () => void; onSeparateParts?: () => void;
onInteractionActiveChange?: (active: boolean) => void;
}) { }) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color; const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked); const locked = Boolean(shape.locked);
@@ -227,6 +227,8 @@ export function ShapeInspector({
const [propertiesOpen, setPropertiesOpen] = useState(true); const [propertiesOpen, setPropertiesOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false); const [colorOpen, setColorOpen] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
return ( return (
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}> <aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header"> <div className="shape-inspector-header">
@@ -300,6 +302,8 @@ export function ShapeInspector({
type="color" type="color"
value={solidColor} value={solidColor}
disabled={locked} disabled={locked}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onChange={(event) => { onChange={(event) => {
onUpdate({ color: event.target.value, hole: false }); onUpdate({ color: event.target.value, hole: false });
setColorOpen(false); setColorOpen(false);
@@ -339,12 +343,12 @@ export function ShapeInspector({
<div className="property-list" id={`properties-${shape.id}`}> <div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => { {properties.map((property) => {
if (property.type === "text") { if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={locked} />; return <TextProperty key={property.label} {...property} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />;
} }
if (property.type === "select") { if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />; return <SelectProperty key={property.label} {...property} disabled={locked} />;
} }
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} />; return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />;
})} })}
</div> </div>
) : null} ) : null}
@@ -403,7 +407,8 @@ function RangeProperty({
workspace, workspace,
disabled, disabled,
onChange, onChange,
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean }) { onInteractionActiveChange,
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean; onInteractionActiveChange?: (active: boolean) => void }) {
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height"; const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
const isLength = propertyUsesLengthUnit(label); const isLength = propertyUsesLengthUnit(label);
const accuracy = workspace.accuracy; const accuracy = workspace.accuracy;
@@ -429,6 +434,7 @@ function RangeProperty({
const nextModelValue = toModelValue(finiteNext); const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max)); onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
setEditing(false); setEditing(false);
onInteractionActiveChange?.(false);
}; };
const handleSliderChange = (nextValue: number) => { const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax); const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
@@ -449,6 +455,7 @@ function RangeProperty({
disabled={disabled} disabled={disabled}
inputMode="decimal" inputMode="decimal"
onFocus={() => { onFocus={() => {
onInteractionActiveChange?.(true);
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep)); setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(true); setEditing(true);
}} }}
@@ -474,6 +481,11 @@ function RangeProperty({
step={controlStep} step={controlStep}
value={sliderValue} value={sliderValue}
disabled={disabled} disabled={disabled}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onPointerDown={() => onInteractionActiveChange?.(true)}
onPointerUp={() => onInteractionActiveChange?.(false)}
onPointerCancel={() => onInteractionActiveChange?.(false)}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))} onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/> />
</div> </div>
@@ -481,7 +493,7 @@ function RangeProperty({
); );
} }
function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig & { disabled?: boolean }) { function TextProperty({ label, value, disabled, onChange, onInteractionActiveChange }: TextPropertyConfig & { disabled?: boolean; onInteractionActiveChange?: (active: boolean) => void }) {
return ( return (
<label className="text-property"> <label className="text-property">
<span>{label}</span> <span>{label}</span>
@@ -491,6 +503,8 @@ function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig &
disabled={disabled} disabled={disabled}
maxLength={24} maxLength={24}
spellCheck={false} spellCheck={false}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onChange={(event) => onChange(event.currentTarget.value)} onChange={(event) => onChange(event.currentTarget.value)}
/> />
</label> </label>
+1
View File
@@ -1,5 +1,6 @@
export const CAD_MODIFIER_RUNTIME_BASE = "/occt"; export const CAD_MODIFIER_RUNTIME_BASE = "/occt";
export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000; export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000;
export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview"; export type CadModifierRequestPhase = "prepare" | "preview";
+71 -1
View File
@@ -1,12 +1,68 @@
import { canonicalizeShape } from "@/lib/workplaneShapes"; import { canonicalizeShape } from "@/lib/workplaneShapes";
import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge"; import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge";
export function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape { export function edgeTreatmentAppliedFrame(shape: WorkplaneShape): NonNullable<EdgeTreatmentHistoryEntry["appliedFrame"]> {
return {
x: shape.x,
z: shape.z,
elevation: shape.elevation ?? 0,
width: shape.width,
depth: shape.depth,
height: shape.height,
rotation: shape.rotation ?? 0,
rotationX: shape.rotationX ?? 0,
rotationZ: shape.rotationZ ?? 0,
mirrorX: Boolean(shape.mirrorX),
mirrorY: Boolean(shape.mirrorY),
mirrorZ: Boolean(shape.mirrorZ),
};
}
function cloneJsonShape(shape: WorkplaneShape): WorkplaneShape {
return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape; return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape;
} }
function compactSnapshotHistory(shape: WorkplaneShape, stripOwnHistory: boolean): WorkplaneShape {
const next: WorkplaneShape = {
...shape,
groupedShapes: shape.groupedShapes?.map((child) => compactSnapshotHistory(child, false)),
};
if (stripOwnHistory) {
delete next.edgeTreatmentHistory;
} else if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: compactSnapshotHistory(entry.before, true),
}));
}
return next;
}
export function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape {
return canonicalizeShape(compactSnapshotHistory(cloneJsonShape(shape), true));
}
export function compactEdgeTreatmentHistory(history: EdgeTreatmentHistoryEntry[] | undefined): EdgeTreatmentHistoryEntry[] {
return (history ?? []).map((entry) => ({
...entry,
feature: { ...entry.feature },
before: cloneWorkplaneShapeSnapshot(entry.before),
}));
}
export function restoreShapeBeforeEdgeTreatment(shape: WorkplaneShape, entry: EdgeTreatmentHistoryEntry) { export function restoreShapeBeforeEdgeTreatment(shape: WorkplaneShape, entry: EdgeTreatmentHistoryEntry) {
const before = cloneWorkplaneShapeSnapshot(entry.before); const before = cloneWorkplaneShapeSnapshot(entry.before);
const entryIndex = (shape.edgeTreatmentHistory ?? []).findIndex((candidate) => candidate.id === entry.id);
const earlierHistory = entryIndex > 0
? compactEdgeTreatmentHistory(shape.edgeTreatmentHistory?.slice(0, entryIndex))
: undefined;
const applied = entry.appliedFrame;
const width = applied ? before.width * shape.width / Math.max(0.001, applied.width) : before.width;
const depth = applied ? before.depth * shape.depth / Math.max(0.001, applied.depth) : before.depth;
const height = applied ? before.height * shape.height / Math.max(0.001, applied.height) : before.height;
const toggleMirror = (beforeValue: boolean | undefined, currentValue: boolean | undefined, appliedValue: boolean | undefined) => (
Boolean(beforeValue) !== (Boolean(currentValue) !== Boolean(appliedValue))
) || undefined;
return canonicalizeShape({ return canonicalizeShape({
...before, ...before,
id: shape.id, id: shape.id,
@@ -15,5 +71,19 @@ export function restoreShapeBeforeEdgeTreatment(shape: WorkplaneShape, entry: Ed
hole: shape.hole || undefined, hole: shape.hole || undefined,
locked: shape.locked, locked: shape.locked,
hidden: shape.hidden, hidden: shape.hidden,
x: applied ? before.x + shape.x - applied.x : before.x,
z: applied ? before.z + shape.z - applied.z : before.z,
elevation: applied ? (before.elevation ?? 0) + (shape.elevation ?? 0) - applied.elevation : before.elevation,
width,
depth,
height,
size: Math.max(width, depth),
rotation: applied ? (before.rotation ?? 0) + (shape.rotation ?? 0) - applied.rotation : before.rotation,
rotationX: applied ? (before.rotationX ?? 0) + (shape.rotationX ?? 0) - applied.rotationX : before.rotationX,
rotationZ: applied ? (before.rotationZ ?? 0) + (shape.rotationZ ?? 0) - applied.rotationZ : before.rotationZ,
mirrorX: applied ? toggleMirror(before.mirrorX, shape.mirrorX, applied.mirrorX) : before.mirrorX,
mirrorY: applied ? toggleMirror(before.mirrorY, shape.mirrorY, applied.mirrorY) : before.mirrorY,
mirrorZ: applied ? toggleMirror(before.mirrorZ, shape.mirrorZ, applied.mirrorZ) : before.mirrorZ,
edgeTreatmentHistory: earlierHistory?.length ? earlierHistory : undefined,
}); });
} }
+107
View File
@@ -0,0 +1,107 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes";
export const MAX_EDITOR_HISTORY_ENTRIES = 100;
export const MAX_EDITOR_HISTORY_BYTES = 64 * 1024 * 1024;
export type EditorHistoryEntry = {
shapes: WorkplaneShape[];
selectedIds: string[];
fingerprint: string;
estimatedBytes: number;
};
export type EditorHistoryState = {
entries: EditorHistoryEntry[];
index: number;
};
export function serializedSceneSignature(shapes: WorkplaneShape[]) {
const serialized = serializeShapesForSync(shapes);
let hashA = 2166136261;
let hashB = 5381;
for (let index = 0; index < serialized.length; index += 1) {
const code = serialized.charCodeAt(index);
hashA = Math.imul(hashA ^ code, 16777619);
hashB = Math.imul(hashB, 33) ^ code;
}
return {
fingerprint: `${serialized.length}:${hashA >>> 0}:${hashB >>> 0}`,
estimatedBytes: serialized.length * 2,
};
}
export function projectShapesFingerprint(shapes: WorkplaneShape[]) {
return serializedSceneSignature(shapes).fingerprint;
}
export function editorHistoryEntry(shapes: WorkplaneShape[], selectedIds: string[]): EditorHistoryEntry {
const canonicalShapes = shapes.map(canonicalizeShape);
const validSelection = selectedIds.filter((id, index) => selectedIds.indexOf(id) === index && canonicalShapes.some((shape) => shape.id === id));
return {
shapes: canonicalShapes,
selectedIds: validSelection,
...serializedSceneSignature(canonicalShapes),
};
}
export function boundedEditorHistory(entries: EditorHistoryEntry[]) {
const bounded = entries.slice(-MAX_EDITOR_HISTORY_ENTRIES);
let totalBytes = bounded.reduce((total, entry) => total + entry.estimatedBytes, 0);
while (bounded.length > 2 && totalBytes > MAX_EDITOR_HISTORY_BYTES) {
const removed = bounded.shift();
totalBytes -= removed?.estimatedBytes ?? 0;
}
return bounded;
}
export function appendEditorHistorySnapshot(entries: EditorHistoryEntry[], requestedIndex: number, entry: EditorHistoryEntry) {
const index = Math.min(Math.max(0, requestedIndex), Math.max(0, entries.length - 1));
const current = entries[index];
if (current?.fingerprint === entry.fingerprint) {
const selectionChanged = current.selectedIds.join("\0") !== entry.selectedIds.join("\0");
return {
entries: selectionChanged ? entries.map((candidate, candidateIndex) => candidateIndex === index ? { ...candidate, selectedIds: entry.selectedIds } : candidate) : entries,
index,
changed: false,
};
}
const nextEntries = boundedEditorHistory([...entries.slice(0, index + 1), entry]);
return { entries: nextEntries, index: nextEntries.length - 1, changed: true };
}
export function hydrateEditorHistoryState(
currentShapes: WorkplaneShape[],
storedEntries: EditorHistoryEntry[] | undefined,
requestedIndex: number | undefined,
): EditorHistoryState {
const fallback = editorHistoryEntry(currentShapes, []);
if (!Array.isArray(storedEntries) || storedEntries.length === 0) {
return { entries: [fallback], index: 0 };
}
try {
const normalized = storedEntries.map((entry) =>
editorHistoryEntry(
Array.isArray(entry?.shapes) ? entry.shapes : [],
Array.isArray(entry?.selectedIds) ? entry.selectedIds.filter((id): id is string => typeof id === "string") : [],
),
);
const index = Number.isInteger(requestedIndex)
? Math.min(Math.max(0, requestedIndex as number), normalized.length - 1)
: normalized.length - 1;
if (normalized[index]?.fingerprint !== fallback.fingerprint) {
return { entries: [fallback], index: 0 };
}
const entries = boundedEditorHistory(normalized);
const boundedIndex = index - (normalized.length - entries.length);
if (boundedIndex < 0 || boundedIndex >= entries.length) {
return { entries: [fallback], index: 0 };
}
return { entries, index: boundedIndex };
} catch {
return { entries: [fallback], index: 0 };
}
}
+10
View File
@@ -0,0 +1,10 @@
export const DEFAULT_SPHERE_STEPS = 24;
export function sphereTessellation(steps = DEFAULT_SPHERE_STEPS) {
const normalizedSteps = Math.max(6, Math.round(steps));
return {
widthSegments: Math.max(8, normalizedSteps * 2),
heightSegments: Math.max(6, normalizedSteps),
};
}
+10
View File
@@ -64,3 +64,13 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
export function workplaneSettingsFingerprint(workspace: WorkplaneWorkspaceSettings, snapGrid: GridSize) { export function workplaneSettingsFingerprint(workspace: WorkplaneWorkspaceSettings, snapGrid: GridSize) {
return JSON.stringify({ workspace, snapGrid }); return JSON.stringify({ workspace, snapGrid });
} }
export function workspaceHydrationSyncDecision(pendingFingerprint: string | null, currentFingerprint: string) {
if (pendingFingerprint === null) {
return { shouldSync: true, pendingFingerprint: null };
}
return {
shouldSync: false,
pendingFingerprint: currentFingerprint === pendingFingerprint ? null : pendingFingerprint,
};
}
+8 -2
View File
@@ -29,8 +29,14 @@ export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size; return shape.depth ?? shape.size;
} }
function edgeTreatmentPreserveZone(shape: WorkplaneShape): number {
const own = Math.max(...(shape.edgeTreatments ?? []).map((feature) => feature.amount), 0);
const child = Math.max(...(shape.groupedShapes ?? []).map(edgeTreatmentPreserveZone), 0);
return Math.max(own, child);
}
export function preservesEdgeTreatmentSize(shape: WorkplaneShape) { export function preservesEdgeTreatmentSize(shape: WorkplaneShape) {
return shape.edgeResizeMode === "preserve" && Boolean(shape.importedMesh && shape.edgeTreatments?.length); return shape.edgeResizeMode === "preserve" && Boolean(shape.importedMesh && edgeTreatmentPreserveZone(shape) > 0);
} }
function edgePreservedCoordinate(value: number, baseSize: number, targetSize: number, centered: boolean, requestedZone: number) { function edgePreservedCoordinate(value: number, baseSize: number, targetSize: number, centered: boolean, requestedZone: number) {
@@ -57,7 +63,7 @@ export function resizedImportedCoordinates(shape: WorkplaneShape, sourcePosition
const depth = shapeDepth(shape); const depth = shapeDepth(shape);
const height = shape.height; const height = shape.height;
const preserve = preservesEdgeTreatmentSize(shape); const preserve = preservesEdgeTreatmentSize(shape);
const zone = preserve ? Math.max(...(shape.edgeTreatments ?? []).map((feature) => feature.amount), 0) : 0; const zone = preserve ? edgeTreatmentPreserveZone(shape) : 0;
const positions = new Array<number>(sourcePositions.length); const positions = new Array<number>(sourcePositions.length);
for (let index = 0; index + 2 < sourcePositions.length; index += 3) { for (let index = 0; index + 2 < sourcePositions.length; index += 3) {
if (preserve) { if (preserve) {
+14
View File
@@ -105,6 +105,20 @@ export type EdgeTreatmentHistoryEntry = {
createdAt: number; createdAt: number;
feature: EdgeTreatmentFeature; feature: EdgeTreatmentFeature;
before: WorkplaneShape; before: WorkplaneShape;
appliedFrame?: {
x: number;
z: number;
elevation: number;
width: number;
depth: number;
height: number;
rotation: number;
rotationX: number;
rotationZ: number;
mirrorX: boolean;
mirrorY: boolean;
mirrorZ: boolean;
};
}; };
export type CadDisplayEdge = { export type CadDisplayEdge = {
+64 -19
View File
@@ -50,7 +50,7 @@ function releaseSession(cad: OcctKernel) {
function cadShapeIsValid(cad: OcctKernel, shape: ShapeHandle) { function cadShapeIsValid(cad: OcctKernel, shape: ShapeHandle) {
const validator = (cad as { isValid?: unknown }).isValid; const validator = (cad as { isValid?: unknown }).isValid;
if (typeof validator !== "function") return true; if (typeof validator !== "function") throw new Error("isValid is not a function");
try { try {
return Boolean(validator.call(cad, shape)); return Boolean(validator.call(cad, shape));
} catch { } catch {
@@ -280,9 +280,21 @@ function isSelectableModifierEdge(edge: CollectedCadEdgeGeometry) {
return edge.manifold && !edge.boundary && edge.points.length >= 6; return edge.manifold && !edge.boundary && edge.points.length >= 6;
} }
function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number, suppressTreatmentDetailEdges = false) { function releaseHandles(cad: OcctKernel, handles: ShapeHandle[]) {
handles.forEach((handle) => {
try {
cad.release(handle);
} catch {
// A failed topology operation can invalidate temporary handles.
}
});
}
function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number, suppressTreatmentDetailEdges = false, retainEdgeHandles = false) {
const handles = cad.getSubShapes(shape, "edge"); const handles = cad.getSubShapes(shape, "edge");
const faces = cad.getSubShapes(shape, "face"); const faces = cad.getSubShapes(shape, "face");
let keepEdgeHandles = false;
try {
const faceByHash = new Map(faces.map((face) => [cad.hashCode(face, HASH_UPPER_BOUND), face])); const faceByHash = new Map(faces.map((face) => [cad.hashCode(face, HASH_UPPER_BOUND), face]));
const faceAreaByHash = new Map<number, number>(); const faceAreaByHash = new Map<number, number>();
faces.forEach((face) => { faces.forEach((face) => {
@@ -330,19 +342,27 @@ function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number, s
} }
return { id, points, ...classification, curveType, surfaceTypes, faceAreas }; return { id, points, ...classification, curveType, surfaceTypes, faceAreas };
}).filter((edge) => edge.points.length >= 6); }).filter((edge) => edge.points.length >= 6);
const edges: CollectedCadEdge[] = collectedEdges.map((edge) => ({ const edges: CollectedCadEdge[] = collectedEdges.map((edge) => {
const display = treatmentAreaLimit > 0 ? isModifierDisplayCadEdge(edge, treatmentAreaLimit) : isDisplayCadEdge(edge);
return {
...edge, ...edge,
display: treatmentAreaLimit > 0 ? isModifierDisplayCadEdge(edge, treatmentAreaLimit) : isDisplayCadEdge(edge), display,
selectable: isSelectableModifierEdge(edge), selectable: isSelectableModifierEdge(edge) && (treatmentAreaLimit <= 0 || display),
})); };
});
const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id); const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const displayEdges = cadDisplayEdgesFromCollected(edges); const displayEdges = cadDisplayEdgesFromCollected(edges);
keepEdgeHandles = retainEdgeHandles;
return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, faceAreas: _faceAreas, ...edge }) => edge), selectableEdgeIds, displayEdges }; return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, faceAreas: _faceAreas, ...edge }) => edge), selectableEdgeIds, displayEdges };
} finally {
releaseHandles(cad, faces);
if (!keepEdgeHandles) releaseHandles(cad, handles);
}
} }
function cadDisplayEdgesFromCollected(edges: CollectedCadEdge[]): CadModifierDisplayEdge[] { function cadDisplayEdgesFromCollected(edges: CollectedCadEdge[]): CadModifierDisplayEdge[] {
return edges return edges
.filter(isDisplayCadEdge) .filter((edge) => edge.display)
.map((edge) => ({ points: edge.points })); .map((edge) => ({ points: edge.points }));
} }
@@ -387,15 +407,31 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
if (request.type === "prepare") { if (request.type === "prepare") {
releaseSession(activeCad); releaseSession(activeCad);
baseShape = reconstructParts(activeCad, request.parts); baseShape = reconstructParts(activeCad, request.parts);
const collected = collectEdges(activeCad, baseShape, request.sharpAngle, Boolean(request.suppressTreatmentDetailEdges)); const collected = collectEdges(activeCad, baseShape, request.sharpAngle, Boolean(request.suppressTreatmentDetailEdges), true);
edgeHandles = collected.handles; edgeHandles = collected.handles;
baseSolids = activeCad.isSolid(baseShape) ? [baseShape] : activeCad.getSubShapes(baseShape, "solid"); baseSolids = activeCad.isSolid(baseShape) ? [baseShape] : activeCad.getSubShapes(baseShape, "solid");
if (baseSolids.length === 0) throw new Error("The selected group contains no closed solid components"); if (baseSolids.length === 0) throw new Error("The selected group contains no closed solid components");
const ownerHashes = baseSolids.map((solid) => new Set(activeCad.getSubShapes(solid, "edge").map((edge) => activeCad.hashCode(edge, HASH_UPPER_BOUND)))); const ownerEdgeHandles = baseSolids.map((solid) => activeCad.getSubShapes(solid, "edge"));
try {
const ownerCandidates = new Map<number, Array<{ owner: number; edge: ShapeHandle }>>();
ownerEdgeHandles.forEach((componentEdges, owner) => {
componentEdges.forEach((edge) => {
const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND);
const candidates = ownerCandidates.get(hash) ?? [];
candidates.push({ owner, edge });
ownerCandidates.set(hash, candidates);
});
});
edgeOwners = edgeHandles.map((edge) => { edgeOwners = edgeHandles.map((edge) => {
const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND); const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND);
return Math.max(0, ownerHashes.findIndex((hashes) => hashes.has(hash))); const candidates = ownerCandidates.get(hash) ?? [];
const exact = candidates.find((candidate) => activeCad.isSame(edge, candidate.edge));
if (!exact) throw new Error("A CAD edge could not be mapped to its solid component; restart the edge tool");
return exact.owner;
}); });
} finally {
ownerEdgeHandles.forEach((componentEdges) => releaseHandles(activeCad, componentEdges));
}
post({ post({
type: "ready", type: "ready",
requestId: request.requestId, requestId: request.requestId,
@@ -408,20 +444,26 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
if (baseShape === null) throw new Error("Prepare an object before previewing the modifier"); if (baseShape === null) throw new Error("Prepare an object before previewing the modifier");
const selected = request.edgeIds.map((id) => ({ edge: edgeHandles[id], owner: edgeOwners[id] })).filter((entry): entry is { edge: ShapeHandle; owner: number } => entry.edge !== undefined); const selected = request.edgeIds.map((id) => ({ edge: edgeHandles[id], owner: edgeOwners[id] })).filter((entry): entry is { edge: ShapeHandle; owner: number } => entry.edge !== undefined);
if (selected.length === 0) throw new Error("Select at least one highlighted edge"); if (selected.length === 0) throw new Error("Select at least one highlighted edge");
const componentResults = baseSolids.map((solid, owner) => { const componentResults: ShapeHandle[] = [];
let result: ShapeHandle | null = null;
try {
for (let owner = 0; owner < baseSolids.length; owner += 1) {
const solid = baseSolids[owner];
const componentEdges = selected.filter((entry) => entry.owner === owner).map((entry) => entry.edge); const componentEdges = selected.filter((entry) => entry.owner === owner).map((entry) => entry.edge);
if (componentEdges.length === 0) return activeCad.copy(solid); const component = componentEdges.length === 0
return request.kind === "fillet" ? activeCad.copy(solid)
: request.kind === "fillet"
? activeCad.fillet(solid, componentEdges, request.amount) ? activeCad.fillet(solid, componentEdges, request.amount)
: Math.abs(request.chamferAngle - 45) < 0.001 : Math.abs(request.chamferAngle - 45) < 0.001
? activeCad.chamfer(solid, componentEdges, request.amount) ? activeCad.chamfer(solid, componentEdges, request.amount)
: activeCad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle); : activeCad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
}); componentResults.push(component);
const result = componentResults.length === 1 ? componentResults[0] : activeCad.makeCompound(componentResults); }
result = componentResults.length === 1 ? componentResults[0] : activeCad.makeCompound(componentResults);
if (!cadShapeIsValid(activeCad, result)) throw new Error("The chosen size creates invalid or overlapping edge geometry"); if (!cadShapeIsValid(activeCad, result)) throw new Error("The chosen size creates invalid or overlapping edge geometry");
const options = tessellationOptions(request.quality, request.amount); const options = tessellationOptions(request.quality, request.amount);
const mesh = copyCadMesh(activeCad.tessellate(result, options)); const mesh = copyCadMesh(activeCad.tessellate(result, options));
const displayEdges = collectEdges(activeCad, result, request.chamferAngle).displayEdges; const displayEdges = collectEdges(activeCad, result, 0).displayEdges;
const brep = activeCad.toBREP(result); const brep = activeCad.toBREP(result);
const components: CadModifierComponentMesh[] = componentResults.map((component, owner) => { const components: CadModifierComponentMesh[] = componentResults.map((component, owner) => {
const componentMesh = copyCadMesh(activeCad.tessellate(component, options)); const componentMesh = copyCadMesh(activeCad.tessellate(component, options));
@@ -432,11 +474,9 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
indices: componentMesh.indices, indices: componentMesh.indices,
triangleCount: componentMesh.triangleCount, triangleCount: componentMesh.triangleCount,
brep: activeCad.toBREP(component), brep: activeCad.toBREP(component),
displayEdges: collectEdges(activeCad, component, request.chamferAngle).displayEdges, displayEdges: collectEdges(activeCad, component, 0).displayEdges,
}; };
}); });
componentResults.forEach((component) => activeCad.release(component));
if (componentResults.length > 1) activeCad.release(result);
post( post(
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges, components }, { type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges, components },
[ [
@@ -446,6 +486,10 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
...components.flatMap((component) => [component.positions.buffer, component.normals.buffer, component.indices.buffer]), ...components.flatMap((component) => [component.positions.buffer, component.normals.buffer, component.indices.buffer]),
], ],
); );
} finally {
componentResults.forEach((component) => activeCad.release(component));
if (result !== null && componentResults.length > 1) activeCad.release(result);
}
} catch (error) { } catch (error) {
const rawMessage = error instanceof Error ? error.message : String(error ?? ""); const rawMessage = error instanceof Error ? error.message : String(error ?? "");
if (isWasmMemoryFault(rawMessage) || isImportStlWasmFault(rawMessage) || isMissingValidatorFault(rawMessage)) { if (isWasmMemoryFault(rawMessage) || isImportStlWasmFault(rawMessage) || isMissingValidatorFault(rawMessage)) {
@@ -467,6 +511,7 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
const message = request.type === "preview" && (rawMessage.includes("WebAssembly.Exception") || rawMessage.includes("fillet:") || rawMessage.includes("chamfer:")) const message = request.type === "preview" && (rawMessage.includes("WebAssembly.Exception") || rawMessage.includes("fillet:") || rawMessage.includes("chamfer:"))
? `The selected edges cannot be ${request.kind === "fillet" ? "filleted" : "chamfered"} together at this size. Reduce the size or select fewer connected edges.` ? `The selected edges cannot be ${request.kind === "fillet" ? "filleted" : "chamfered"} together at this size. Reduce the size or select fewer connected edges.`
: rawMessage || "The CAD kernel could not complete this edge treatment"; : rawMessage || "The CAD kernel could not complete this edge treatment";
if (request.type === "prepare" && cad) releaseSession(cad);
post({ type: "error", requestId: request.requestId, message }); post({ type: "error", requestId: request.requestId, message });
} }
}; };
+18 -4
View File
@@ -1,7 +1,11 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"], "lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false, "allowJs": false,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
@@ -19,9 +23,19 @@
} }
], ],
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": [
"./src/*"
]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": [
"exclude": ["node_modules"] "**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"next-env.d.ts",
".next-dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
} }
+5
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
CAD_MODIFIER_MAX_SHARP_ANGLE,
CAD_MODIFIER_REQUEST_TIMEOUT_MS, CAD_MODIFIER_REQUEST_TIMEOUT_MS,
CAD_MODIFIER_RUNTIME_BASE, CAD_MODIFIER_RUNTIME_BASE,
cadModifierTimeoutMessage, cadModifierTimeoutMessage,
@@ -22,4 +23,8 @@ describe("CAD modifier runtime state", () => {
expect(CAD_MODIFIER_REQUEST_TIMEOUT_MS).toBeLessThanOrEqual(60_000); expect(CAD_MODIFIER_REQUEST_TIMEOUT_MS).toBeLessThanOrEqual(60_000);
expect(cadModifierTimeoutMessage("prepare")).toContain("Firefox 121+"); expect(cadModifierTimeoutMessage("prepare")).toContain("Firefox 121+");
}); });
it("does not expose thresholds above the worker's folded edge-angle range", () => {
expect(CAD_MODIFIER_MAX_SHARP_ANGLE).toBe(90);
});
}); });
+46 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; import { compactEdgeTreatmentHistory, edgeTreatmentAppliedFrame, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory";
import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge"; import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge";
function box(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape { function box(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
@@ -116,4 +116,49 @@ describe("edge treatment history restoration", () => {
expect(restored).toMatchObject({ kind: "box", x: 18, width: 8, depth: 6, height: 50, size: 8 }); expect(restored).toMatchObject({ kind: "box", x: 18, width: 8, depth: 6, height: 50, size: 8 });
expect(restored.importedMesh).toBeUndefined(); expect(restored.importedMesh).toBeUndefined();
}); });
it("keeps history snapshots flat instead of recursively nesting older history", () => {
const first = historyEntry(box({ id: "before-first" }));
const second = {
...historyEntry(box({ id: "before-second", edgeTreatmentHistory: [first] })),
id: "history-2",
};
const compacted = compactEdgeTreatmentHistory([first, second]);
expect(compacted).toHaveLength(2);
expect(compacted[0].before.edgeTreatmentHistory).toBeUndefined();
expect(compacted[1].before.edgeTreatmentHistory).toBeUndefined();
});
it("preserves edits made after applying a feature while restoring the pre-feature geometry", () => {
const before = box({ x: 8, z: 3, width: 40, depth: 20, height: 30, rotation: 15 });
const applied = box({ kind: "mesh", x: 7.5, z: 3, width: 39, depth: 20, height: 30, rotation: 0 });
const entry: EdgeTreatmentHistoryEntry = {
...historyEntry(before),
appliedFrame: edgeTreatmentAppliedFrame(applied),
};
const current = box({
...applied,
x: 17.5,
z: -2,
width: 78,
depth: 30,
height: 45,
rotation: 20,
edgeTreatmentHistory: [entry],
});
const restored = restoreShapeBeforeEdgeTreatment(current, entry);
expect(restored).toMatchObject({
kind: "box",
x: 18,
z: -2,
width: 80,
depth: 30,
height: 45,
rotation: 35,
});
});
}); });
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vitest";
import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory";
import type { WorkplaneShape } from "@/types/sketchforge";
function box(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id: "box-1",
name: "Box",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
size: 20,
width: 20,
depth: 20,
height: 20,
rotation: 0,
locked: false,
hidden: false,
...overrides,
};
}
describe("editor history snapshots", () => {
it("seeds history with the real loaded scene and valid selection", () => {
const shape = box();
const entry = editorHistoryEntry([shape], [shape.id, "missing", shape.id]);
expect(entry.shapes).toHaveLength(1);
expect(entry.shapes[0].id).toBe(shape.id);
expect(entry.selectedIds).toEqual([shape.id]);
});
it("detects persistence-relevant fields that the old fingerprint omitted", () => {
const shape = box({ kind: "cylinder", sides: 32 });
const baseline = projectShapesFingerprint([shape]);
expect(projectShapesFingerprint([{ ...shape, locked: true }])).not.toBe(baseline);
expect(projectShapesFingerprint([{ ...shape, hidden: true }])).not.toBe(baseline);
expect(projectShapesFingerprint([{ ...shape, sides: 64 }])).not.toBe(baseline);
});
it("detects mesh coordinate changes even when array lengths are unchanged", () => {
const shape = box({
kind: "mesh",
importedMesh: {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 1,
baseDepth: 1,
baseHeight: 1,
triangleCount: 1,
sourceFormat: "json",
},
});
const changed = {
...shape,
importedMesh: { ...shape.importedMesh!, positions: [0, 0, 0, 2, 0, 0, 0, 1, 0] },
};
expect(projectShapesFingerprint([changed])).not.toBe(projectShapesFingerprint([shape]));
});
it("bounds entry count and estimated memory while retaining undo depth", () => {
const entries = Array.from({ length: 140 }, (_, index) => ({
...editorHistoryEntry([box({ id: `box-${index}`, x: index })], []),
estimatedBytes: 2 * 1024 * 1024,
}));
const bounded = boundedEditorHistory(entries);
expect(bounded.length).toBeLessThanOrEqual(100);
expect(bounded.length).toBeGreaterThanOrEqual(2);
expect(bounded.reduce((total, entry) => total + entry.estimatedBytes, 0)).toBeLessThanOrEqual(64 * 1024 * 1024);
expect(bounded.at(-1)?.shapes[0].id).toBe("box-139");
});
it("trims redo only for a real new edit and preserves it for a no-op", () => {
const entries = [0, 1, 2].map((x) => editorHistoryEntry([box({ x })], []));
const noOp = appendEditorHistorySnapshot(entries, 1, editorHistoryEntry([box({ x: 1 })], ["box-1"]));
expect(noOp.changed).toBe(false);
expect(noOp.entries).toHaveLength(3);
expect(noOp.entries[1].selectedIds).toEqual(["box-1"]);
const branch = appendEditorHistorySnapshot(noOp.entries, 1, editorHistoryEntry([box({ x: 5 })], []));
expect(branch.changed).toBe(true);
expect(branch.entries).toHaveLength(3);
expect(branch.entries.at(-1)?.shapes[0].x).toBe(5);
});
it("restores a persisted undo and redo stack at its saved index", () => {
const entries = [0, 5, 10].map((x) => editorHistoryEntry([box({ x })], []));
const restored = hydrateEditorHistoryState([box({ x: 5 })], entries, 1);
expect(restored.index).toBe(1);
expect(restored.entries).toHaveLength(3);
expect(restored.entries[restored.index].shapes[0].x).toBe(5);
expect(restored.entries[0].shapes[0].x).toBe(0);
expect(restored.entries[2].shapes[0].x).toBe(10);
});
it("falls back to the loaded scene when persisted history is stale", () => {
const stale = [editorHistoryEntry([box({ x: 1 })], [])];
const restored = hydrateEditorHistoryState([box({ x: 9 })], stale, 0);
expect(restored.index).toBe(0);
expect(restored.entries).toHaveLength(1);
expect(restored.entries[0].shapes[0].x).toBe(9);
});
});
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { sphereTessellation } from "@/lib/sphereTessellation";
describe("sphere tessellation", () => {
it("uses the visible sphere Steps value for both rendering and boolean operands", () => {
expect(sphereTessellation(6)).toEqual({ widthSegments: 12, heightSegments: 6 });
expect(sphereTessellation(24)).toEqual({ widthSegments: 48, heightSegments: 24 });
expect(sphereTessellation(64)).toEqual({ widthSegments: 128, heightSegments: 64 });
});
it("uses the catalog default and normalizes fractional input", () => {
expect(sphereTessellation()).toEqual({ widthSegments: 48, heightSegments: 24 });
expect(sphereTessellation(27.6)).toEqual({ widthSegments: 56, heightSegments: 28 });
});
});
+14 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, scaleOptionsForUnits } from "@/lib/measurementUnits"; import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, scaleOptionsForUnits } from "@/lib/measurementUnits";
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";
describe("workplane settings helpers", () => { describe("workplane settings helpers", () => {
it("accepts known snap grid values and falls back for unknown values", () => { it("accepts known snap grid values and falls back for unknown values", () => {
@@ -88,4 +88,17 @@ describe("workplane settings helpers", () => {
expect(changedSnap).not.toBe(base); expect(changedSnap).not.toBe(base);
expect(changedWorkspace).not.toBe(base); expect(changedWorkspace).not.toBe(base);
}); });
it("blocks the previous project's workspace while a new project hydrates", () => {
const projectOne = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE, width: 350, depth: 260 }, "5.0 mm");
const projectTwo = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
const staleCommit = workspaceHydrationSyncDecision(projectTwo, projectOne);
expect(staleCommit).toEqual({ shouldSync: false, pendingFingerprint: projectTwo });
const hydratedCommit = workspaceHydrationSyncDecision(staleCommit.pendingFingerprint, projectTwo);
expect(hydratedCommit).toEqual({ shouldSync: false, pendingFingerprint: null });
expect(workspaceHydrationSyncDecision(hydratedCommit.pendingFingerprint, projectTwo).shouldSync).toBe(true);
});
}); });
+21
View File
@@ -167,4 +167,25 @@ describe("workplane shape helpers", () => {
expect(resizedImportedMeshPositions({ ...modified, edgeResizeMode: "scale" })[3]).toBe(-18); expect(resizedImportedMeshPositions({ ...modified, edgeResizeMode: "scale" })[3]).toBe(-18);
expect(resizedImportedCoordinates(modified, [-9, 1, 0, 9, 19, 0])).toEqual([-19, 1, 0, 19, 39, 0]); expect(resizedImportedCoordinates(modified, [-9, 1, 0, 9, 19, 0])).toEqual([-19, 1, 0, 19, 39, 0]);
}); });
it("uses child edge features when preserving the size of grouped treatments", () => {
const grouped = shape({
kind: "mesh",
edgeResizeMode: "preserve",
importedMesh: {
positions: [-10, 0, 0, -8, 2, 0, 8, 18, 0, 10, 20, 0],
baseWidth: 20,
baseDepth: 20,
baseHeight: 20,
triangleCount: 1,
sourceFormat: "json",
},
groupedShapes: [shape({ edgeTreatments: [{ kind: "fillet", amount: 2, edgeCount: 1 }] })],
width: 40,
height: 40,
});
expect(preservesEdgeTreatmentSize(grouped)).toBe(true);
expect(resizedImportedMeshPositions(grouped)).toEqual([-20, 0, 0, -18, 2, 0, 18, 38, 0, 20, 40, 0]);
});
}); });