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
+26
View File
@@ -2837,6 +2837,11 @@ button {
cursor: default;
}
.workplane-wrap.ruler-move-mode .three-workplane-host,
.workplane-wrap.ruler-move-mode .three-workplane-host:active {
cursor: default;
}
.workplane-wrap.modifier-edge-pick .three-workplane-host,
.workplane-wrap.modifier-edge-pick .three-workplane-host:active {
cursor: crosshair;
@@ -2901,6 +2906,16 @@ button {
transition: fill 120ms ease, stroke 120ms ease, filter 120ms ease;
}
.ruler-overlay.move-mode .ruler-point {
cursor: grab;
}
.ruler-overlay.move-mode .ruler-point:active {
cursor: grabbing;
fill: #dff7ff;
filter: drop-shadow(0 0 4px rgba(0, 143, 190, 0.4));
}
.ruler-overlay.delete-mode .ruler-segment-group:hover .ruler-segment {
stroke: #dc3f36;
stroke-width: 3;
@@ -2925,6 +2940,17 @@ button {
pointer-events: none;
}
.ruler-hover-edge {
fill: none;
stroke: #00aeea;
stroke-width: 4;
stroke-linecap: round;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
filter: drop-shadow(0 0 3px rgba(0, 174, 234, 0.48));
pointer-events: none;
}
.ruler-label {
position: absolute;
z-index: 2;
+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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds";
import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
@@ -34,10 +35,16 @@ type StoredDashboardProject = Partial<DashboardProject> & {
type ProjectShapeCacheEntry = {
revision: number;
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
};
type ProjectShapeRecord = ProjectShapeCacheEntry & {
type ProjectShapeRecord = {
id: string;
revision: number;
shapes: WorkplaneShape[];
history?: EditorHistoryEntry[];
historyIndex?: number;
updatedAt: number;
};
@@ -57,6 +64,21 @@ function formatUpdated(timestamp: number) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(new Date(timestamp));
}
function projectShapeCacheEntry(
revision: number,
shapes: WorkplaneShape[],
history?: EditorHistoryEntry[],
historyIndex?: number,
): ProjectShapeCacheEntry {
const hydrated = hydrateEditorHistoryState(shapes, history, historyIndex);
return {
revision,
shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes,
history: hydrated.entries,
historyIndex: hydrated.index,
};
}
function openProjectShapesDb() {
return new Promise<IDBDatabase>((resolve, reject) => {
if (typeof window === "undefined" || !window.indexedDB) {
@@ -91,7 +113,7 @@ async function loadProjectShapes(projectId: string) {
});
}
async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], revision: number) {
async function saveProjectShapes(projectId: string, entry: ProjectShapeCacheEntry) {
const database = await openProjectShapesDb();
return new Promise<void>((resolve, reject) => {
const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite");
@@ -102,10 +124,10 @@ async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], re
};
existingRequest.onsuccess = () => {
const existing = existingRequest.result as ProjectShapeRecord | undefined;
if (existing && existing.revision > revision) {
if (existing && existing.revision > entry.revision) {
return;
}
store.put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord);
store.put({ id: projectId, ...entry, updatedAt: Date.now() } satisfies ProjectShapeRecord);
};
transaction.oncomplete = () => {
database.close();
@@ -151,7 +173,7 @@ function readStoredProjects() {
const revision = typeof project.revision === "number" ? project.revision : updatedAt;
const designShapes = Array.isArray(project.designShapes) ? (project.designShapes as WorkplaneShape[]) : null;
if (designShapes) {
legacyShapes[id] = { revision, shapes: designShapes };
legacyShapes[id] = projectShapeCacheEntry(revision, designShapes);
}
return {
id,
@@ -272,7 +294,7 @@ export default function Home() {
if (Object.keys(legacyShapes).length > 0) {
setProjectShapesById(legacyShapes);
Object.entries(legacyShapes).forEach(([projectId, entry]) => {
void saveProjectShapes(projectId, entry.shapes, entry.revision).catch(() => {
void saveProjectShapes(projectId, entry).catch(() => {
setDashboardNotice("Could not migrate project shapes to larger storage");
});
});
@@ -348,12 +370,10 @@ export default function Home() {
.then((record) => {
if (canceled) return;
const revision = activeProject.revision ?? record?.revision ?? Date.now();
const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex);
setProjectShapesById((current) => ({
...current,
[activeProjectId]: {
revision,
shapes: record?.shapes ?? [],
},
[activeProjectId]: entry,
}));
})
.catch((error) => {
@@ -361,10 +381,7 @@ export default function Home() {
setDashboardNotice(error instanceof Error ? error.message : "Could not load project shapes");
setProjectShapesById((current) => ({
...current,
[activeProjectId]: {
revision: activeProject.revision ?? Date.now(),
shapes: [],
},
[activeProjectId]: projectShapeCacheEntry(activeProject.revision ?? Date.now(), []),
}));
}
});
@@ -449,9 +466,15 @@ export default function Home() {
});
}, []);
const updateProjectShapes = useCallback((snapshot: { projectId: string; shapes: WorkplaneShape[] }) => {
const updateProjectShapes = useCallback((snapshot: {
projectId: string;
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
}) => {
const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
nextProjectRevisionRef.current = revision;
const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex);
setProjectShapesById((current) => {
const existing = current[snapshot.projectId];
if (existing && existing.revision > revision) {
@@ -459,12 +482,12 @@ export default function Home() {
}
return {
...current,
[snapshot.projectId]: { revision, shapes: snapshot.shapes },
[snapshot.projectId]: entry,
};
});
const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve();
const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, snapshot.shapes, revision));
const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, entry));
projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave;
void queuedSave
@@ -519,9 +542,9 @@ export default function Home() {
const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length);
setProjectShapesById((current) => ({
...current,
[project.id]: { revision: project.revision ?? project.updatedAt, shapes: [] },
[project.id]: projectShapeCacheEntry(project.revision ?? project.updatedAt, []),
}));
void saveProjectShapes(project.id, [], project.revision ?? project.updatedAt).catch(() => {
void saveProjectShapes(project.id, projectShapeCacheEntry(project.revision ?? project.updatedAt, [])).catch(() => {
setDashboardNotice("Could not prepare project shape storage");
});
setProjects((current) => [project, ...current]);
@@ -542,10 +565,11 @@ export default function Home() {
: importedShapeFromStl(file.name, await file.arrayBuffer());
const project = newProject(projectNameFromFileName(file.name), projects.length, 1);
const revision = project.revision ?? project.updatedAt;
await saveProjectShapes(project.id, [shape], revision);
const entry = projectShapeCacheEntry(revision, [shape]);
await saveProjectShapes(project.id, entry);
setProjectShapesById((current) => ({
...current,
[project.id]: { revision, shapes: [shape] },
[project.id]: entry,
}));
setDashboardNotice(`Imported ${file.name}`);
setProjects((current) => [project, ...current]);
@@ -674,6 +698,8 @@ export default function Home() {
<div className={view === "editor" ? "editor-stage active" : "editor-stage"} aria-hidden={view !== "editor"}>
<SketchForgeEditor
initialShapes={activeProjectShapeEntry?.shapes ?? []}
initialHistory={activeProjectShapeEntry?.history}
initialHistoryIndex={activeProjectShapeEntry?.historyIndex}
initialSnap={activeProject?.snapGrid ?? DEFAULT_SNAP_GRID}
initialWorkspace={activeProject?.workspace ?? DEFAULT_WORKPLANE_WORKSPACE}
onHome={openDashboard}
+315 -152
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 { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
import {
ToolbarAlignIcon,
ToolbarChamferIcon,
@@ -65,12 +66,14 @@ import {
import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata";
import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups";
import {
CAD_MODIFIER_MAX_SHARP_ANGLE,
CAD_MODIFIER_REQUEST_TIMEOUT_MS,
cadModifierTimeoutMessage,
cadModifierWorkerFailureMessage,
type CadModifierRequestPhase,
} 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 { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
@@ -183,6 +186,7 @@ const CUTTER_PADDING = 0.05;
const POINT_TOLERANCE = 0.0001;
const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4;
const MIN_SHAPE_DIMENSION = 0.01;
const MAX_SKETCH_HISTORY_ENTRIES = 100;
const MODEL_DIMENSION_PRECISION = 3;
const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000;
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 selected = new Set<number>([startId]);
const queue = [startId];
const tolerance = 0.025;
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
edges.forEach((edge) => {
for (let index = 0; index + 2 < edge.points.length; index += 3) {
minX = Math.min(minX, edge.points[index]);
minY = Math.min(minY, edge.points[index + 1]);
minZ = Math.min(minZ, edge.points[index + 2]);
maxX = Math.max(maxX, edge.points[index]);
maxY = Math.max(maxY, edge.points[index + 1]);
maxZ = Math.max(maxZ, edge.points[index + 2]);
}
});
const diagonal = [minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite)
? Math.hypot(maxX - minX, maxY - minY, maxZ - minZ)
: 1;
const tolerance = Math.max(1e-6, Math.min(0.01, diagonal * 1e-5));
while (queue.length > 0) {
const id = queue.shift() as number;
const edge = edgeById.get(id);
@@ -1218,7 +1241,7 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI
}
function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) {
return edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle;
return edge.display && edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle;
}
function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) {
@@ -1296,17 +1319,29 @@ function shapeWithEdgeTreatmentRecord(
},
],
edgeTreatmentHistory: [
...(before.edgeTreatmentHistory ?? []),
...compactEdgeTreatmentHistory(before.edgeTreatmentHistory),
{
id: createLocalId("edge-history"),
createdAt,
feature,
before: cloneWorkplaneShapeSnapshot(before),
appliedFrame: edgeTreatmentAppliedFrame(shape),
},
],
});
}
function bakedEdgeTreatmentPreview(shape: WorkplaneShape, base: WorkplaneShape) {
if (!base.groupedShapes?.length) return shape;
return canonicalizeShape({
...shape,
groupedShapes: undefined,
groupedBaseWidth: undefined,
groupedBaseDepth: undefined,
groupedBaseHeight: undefined,
});
}
function shapeCenterDistance(a: WorkplaneShape, b: WorkplaneShape) {
const ax = a.x;
const ay = (a.elevation ?? 0) + a.height / 2;
@@ -1410,7 +1445,7 @@ function groupedShapeWithComponentEdgeTreatment(
...preview,
edgeResizeMode: session.preserveEdgeSize ? "preserve" : "scale",
edgeTreatments: base.edgeTreatments,
edgeTreatmentHistory: base.edgeTreatmentHistory,
edgeTreatmentHistory: base.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(base.edgeTreatmentHistory) : undefined,
groupedBaseWidth: shapeWidth(preview),
groupedBaseDepth: shapeDepth(preview),
groupedBaseHeight: preview.height,
@@ -1479,9 +1514,13 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[]
...rebuilt.group,
id: shape.id,
name: shape.name,
color: shape.color,
hole: shape.hole || rebuilt.group.hole,
locked: shape.locked,
hidden: shape.hidden,
edgeResizeMode: shape.edgeResizeMode,
edgeTreatments: shape.edgeTreatments,
edgeTreatmentHistory: shape.edgeTreatmentHistory?.length ? compactEdgeTreatmentHistory(shape.edgeTreatmentHistory) : undefined,
}),
label: restoredChild.label,
};
@@ -1575,8 +1614,7 @@ function cylinderMesh(shape: WorkplaneShape, sides = 96, topRadiusScale = 1): Me
}
function sphereMesh(shape: WorkplaneShape): MeshData {
const lat = 12;
const lon = 32;
const { widthSegments: lon, heightSegments: lat } = sphereTessellation(shape.steps);
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const height = shape.height;
@@ -1869,7 +1907,7 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null {
geometry.scale(width / 2, 1, depth / 2);
break;
case "sphere":
geometry = new THREE.SphereGeometry(1, Math.max(8, (shape.steps ?? 24) * 2), Math.max(6, shape.steps ?? 24));
geometry = new THREE.SphereGeometry(1, sphereTessellation(shape.steps).widthSegments, sphereTessellation(shape.steps).heightSegments);
geometry.scale(width / 2, height / 2, depth / 2);
break;
case "cone": {
@@ -3725,9 +3763,10 @@ function primitiveManifoldForShape(runtime: ManifoldToplevel, shape: WorkplaneSh
}
if (shape.kind === "sphere") {
const { widthSegments } = sphereTessellation(shape.steps);
return transformedPrimitiveManifold(
runtime,
runtime.Manifold.sphere(1, shape.sides ?? 32),
runtime.Manifold.sphere(1, widthSegments),
primitiveTransformMatrix(shape, new THREE.Vector3(width / 2, height / 2, depth / 2)),
created,
);
@@ -4938,62 +4977,10 @@ function readMcpEditorIdentity() {
return identity;
}
function projectShapesFingerprint(shapes: WorkplaneShape[]) {
return shapes
.map((shape, index) =>
[
compactShapeSummary(shape, index),
`id${shape.id}`,
`n${shape.name}`,
`clr${shape.color}`,
`txt${shape.text ?? ""}`,
`mesh${shape.importedMesh?.positions.length ?? 0}:${shape.importedMesh?.normals?.length ?? 0}`,
`cadFrame${shape.cadBrepFrame ? JSON.stringify({
x: Number(shape.cadBrepFrame.x.toFixed(6)),
z: Number(shape.cadBrepFrame.z.toFixed(6)),
elevation: Number(shape.cadBrepFrame.elevation.toFixed(6)),
width: Number(shape.cadBrepFrame.width.toFixed(6)),
depth: Number(shape.cadBrepFrame.depth.toFixed(6)),
height: Number(shape.cadBrepFrame.height.toFixed(6)),
sourceTransform: shape.cadBrepFrame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null,
}) : ""}`,
`primitiveFrame${shape.cadPrimitiveFrame ? JSON.stringify({
kind: shape.cadPrimitiveFrame.kind,
width: Number(shape.cadPrimitiveFrame.width.toFixed(6)),
depth: Number(shape.cadPrimitiveFrame.depth.toFixed(6)),
height: Number(shape.cadPrimitiveFrame.height.toFixed(6)),
frame: {
x: Number(shape.cadPrimitiveFrame.frame.x.toFixed(6)),
z: Number(shape.cadPrimitiveFrame.frame.z.toFixed(6)),
elevation: Number(shape.cadPrimitiveFrame.frame.elevation.toFixed(6)),
width: Number(shape.cadPrimitiveFrame.frame.width.toFixed(6)),
depth: Number(shape.cadPrimitiveFrame.frame.depth.toFixed(6)),
height: Number(shape.cadPrimitiveFrame.frame.height.toFixed(6)),
sourceTransform: shape.cadPrimitiveFrame.frame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null,
},
}) : ""}`,
`sketch${shape.sketchProfile ? JSON.stringify({
points: shape.sketchProfile.points,
segments: shape.sketchProfile.segments,
images: (shape.sketchProfile.images ?? []).map((image) => ({
id: image.id,
name: image.name,
x: image.x,
z: image.z,
width: image.width,
depth: image.depth,
opacity: image.opacity,
lockAspect: image.lockAspect,
sourceLength: image.dataUrl.length,
})),
}) : ""}`,
].join(","),
)
.join(";");
}
export function SketchForgeEditor({
initialShapes = [],
initialHistory,
initialHistoryIndex,
initialSnap,
initialWorkspace,
onHome,
@@ -5005,22 +4992,37 @@ export function SketchForgeEditor({
projectRevision = 0,
}: {
initialShapes?: WorkplaneShape[];
initialHistory?: EditorHistoryEntry[];
initialHistoryIndex?: number;
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
onHome?: () => void;
onProjectShapesChange?: (snapshot: { projectId: string; shapes: WorkplaneShape[] }) => void;
onProjectShapesChange?: (snapshot: {
projectId: string;
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
historyIndex: number;
}) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
projectId?: string | null;
projectName?: string;
projectRevision?: number;
} = {}) {
const [shapes, setShapes] = useState<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 [clipboard, setClipboard] = useState<WorkplaneShape[]>([]);
const [systemClipboardSupported, setSystemClipboardSupported] = useState(false);
const [history, setHistory] = useState<WorkplaneShape[][]>([[]]);
const [historyIndex, setHistoryIndex] = useState(0);
const [history, setHistory] = useState<EditorHistoryEntry[]>(() => (initialHistoryStateRef.current as EditorHistoryState).entries);
const [historyIndex, setHistoryIndex] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).index);
const [placementElevation, setPlacementElevation] = useState(0);
const [workspaceSettings, setWorkspaceSettings] = useState<WorkplaneWorkspaceSettings>(() => normalizeWorkspaceSettings(initialWorkspace));
const [workplaneMode, setWorkplaneMode] = useState(false);
@@ -5051,6 +5053,7 @@ export function SketchForgeEditor({
const noticeRef = useRef(notice);
const projectInfoRef = useRef({ projectId: projectId ?? null, projectName });
const historyIndexRef = useRef(historyIndex);
const historyRef = useRef(history);
const interactionHistoryStartRef = useRef("");
const interactionHistoryChangedRef = useRef(false);
const interactionHistoryTimerRef = useRef<number | null>(null);
@@ -5061,6 +5064,8 @@ export function SketchForgeEditor({
const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile());
const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]);
const [sketchHistoryIndex, setSketchHistoryIndex] = useState(0);
const sketchHistoryRef = useRef(sketchHistory);
const sketchHistoryIndexRef = useRef(sketchHistoryIndex);
const [sketchActivePointId, setSketchActivePointId] = useState<string | null>(null);
const [sketchSelection, setSketchSelection] = useState<SketchSelection>(null);
const [sketchMeasureStart, setSketchMeasureStart] = useState<SketchPoint | null>(null);
@@ -5179,6 +5184,8 @@ export function SketchForgeEditor({
selectedEdgeIds: [],
busy: false,
prepared: true,
preview: null,
componentPreviews: [],
error: message.selectableEdgeIds.length ? null : "No sharp manifold edges were found at this threshold",
} : current);
if (message.selectableEdgeIds.length) setNotice("Select highlighted edges, then adjust the preview");
@@ -5238,12 +5245,19 @@ export function SketchForgeEditor({
const invalidateCadModifierSession = useCallback(() => {
const wasActive = cadModifierBaseShapeRef.current !== null;
if (!wasActive) return false;
const hadInFlightRequest = cadModifierWatchdogRef.current !== null;
clearCadModifierWatchdog();
const requestId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = requestId;
cadModifierLatestPreviewRef.current = requestId;
cadModifierPrepareRef.current = requestId;
cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest);
if (hadInFlightRequest) {
cadModifierWorkerRef.current?.terminate();
cadModifierWorkerRef.current = null;
cadModifierWorkerRestartRef.current();
} else {
cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest);
}
cadModifierBaseShapeRef.current = null;
cadModifierBaseFingerprintRef.current = "";
cadModifierSourcePartsRef.current = [];
@@ -5303,6 +5317,14 @@ export function SketchForgeEditor({
useEffect(() => {
selectedIdsRef.current = selectedIds;
const currentHistory = historyRef.current;
const currentIndex = Math.min(historyIndexRef.current, Math.max(0, currentHistory.length - 1));
const currentEntry = currentHistory[currentIndex];
if (currentEntry && currentEntry.selectedIds.join("\0") !== selectedIds.join("\0")) {
const updated = currentHistory.map((entry, index) => index === currentIndex ? { ...entry, selectedIds: [...selectedIds] } : entry);
historyRef.current = updated;
setHistory(updated);
}
}, [selectedIds]);
useEffect(() => {
@@ -5321,6 +5343,18 @@ export function SketchForgeEditor({
historyIndexRef.current = historyIndex;
}, [historyIndex]);
useEffect(() => {
historyRef.current = history;
}, [history]);
useEffect(() => {
sketchHistoryRef.current = sketchHistory;
}, [sketchHistory]);
useEffect(() => {
sketchHistoryIndexRef.current = sketchHistoryIndex;
}, [sketchHistoryIndex]);
useEffect(() => {
edgeModifierRef.current = edgeModifier;
}, [edgeModifier]);
@@ -5351,7 +5385,7 @@ export function SketchForgeEditor({
);
const toggleModifierEdge = useCallback((id: number, singleEdge = false) => {
setEdgeModifier((current) => {
if (!current) return current;
if (!current || current.busy) return current;
const allowed = new Set(current.edges.filter((edge) => selectableCadModifierEdge(edge, current.sharpAngle)).map((edge) => edge.id));
if (!allowed.has(id)) return current;
const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id];
@@ -5462,13 +5496,30 @@ export function SketchForgeEditor({
projectSyncTimerRef.current = window.setTimeout(() => {
lastProjectShapesSyncRef.current = serialized;
lastProjectShapesEchoRef.current = serialized;
onProjectShapesChange({ projectId, shapes: canonicalNext });
onProjectShapesChange({
projectId,
shapes: canonicalNext,
history: historyRef.current,
historyIndex: historyIndexRef.current,
});
projectSyncTimerRef.current = null;
}, 120);
},
[onProjectShapesChange, projectId],
);
const appendHistorySnapshot = useCallback((nextShapes: WorkplaneShape[], nextSelection: string[]) => {
const entry = editorHistoryEntry(nextShapes, nextSelection);
const result = appendEditorHistorySnapshot(historyRef.current, historyIndexRef.current, entry);
if (result.entries !== historyRef.current) {
historyRef.current = result.entries;
setHistory(result.entries);
}
historyIndexRef.current = result.index;
setHistoryIndex(result.index);
return result.changed;
}, []);
const finalizeInteractionHistory = useCallback(() => {
const startFingerprint = interactionHistoryStartRef.current;
const hadChanges = interactionHistoryChangedRef.current;
@@ -5484,22 +5535,8 @@ export function SketchForgeEditor({
return;
}
setHistory((current) => {
const historyIndex = Math.min(historyIndexRef.current, Math.max(0, current.length - 1));
const trimmed = current.slice(0, historyIndex + 1);
const latestHistory = trimmed.at(-1) ?? [];
if (projectShapesFingerprint(latestHistory) === nextFingerprint) {
historyIndexRef.current = Math.max(0, trimmed.length - 1);
setHistoryIndex(historyIndexRef.current);
return trimmed;
}
const nextHistory = [...trimmed, canonicalNext];
historyIndexRef.current = nextHistory.length - 1;
setHistoryIndex(historyIndexRef.current);
return nextHistory;
});
}, []);
appendHistorySnapshot(canonicalNext, selectedIdsRef.current);
}, [appendHistorySnapshot]);
useEffect(() => {
if (projectInteractionActive || !pendingProjectShapesRef.current) {
@@ -5517,6 +5554,7 @@ export function SketchForgeEditor({
if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current);
interactionHistoryTimerRef.current = null;
finalizeInteractionHistory();
}
if (!projectInteractionActiveRef.current) {
interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current);
@@ -5557,20 +5595,18 @@ export function SketchForgeEditor({
const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : [];
const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id));
shapesRef.current = canonicalNext;
selectedIdsRef.current = validSelection;
setShapes(canonicalNext);
setSelectedIds(validSelection);
setHistory((current) => {
const trimmed = current.slice(0, historyIndex + 1);
historyIndexRef.current = trimmed.length;
setHistoryIndex(historyIndexRef.current);
return [...trimmed, canonicalNext];
});
const changed = appendHistorySnapshot(canonicalNext, validSelection);
if (message) {
setNotice(message);
}
syncProjectShapes(canonicalNext);
if (changed) {
syncProjectShapes(canonicalNext);
}
},
[historyIndex, selectedIds, syncProjectShapes],
[appendHistorySnapshot, selectedIds, syncProjectShapes],
);
const removeEdgeTreatment = useCallback(async (optionId: string) => {
@@ -5587,32 +5623,46 @@ export function SketchForgeEditor({
setNotice("Choose an edge feature to remove");
return;
}
const sourceFingerprint = projectShapesFingerprint([selectedShape]);
const sourceProjectId = projectInfoRef.current.projectId;
const restored = await restoreEdgeTreatmentInShape(selectedShape, option.path, option.entryId);
if (!restored) {
setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove");
return;
}
const currentTarget = shapesRef.current.find((shape) => shape.id === selectedShape.id);
if (projectInfoRef.current.projectId !== sourceProjectId || !currentTarget || projectShapesFingerprint([currentTarget]) !== sourceFingerprint) {
setNotice("The object changed while removing the edge feature; try again");
return;
}
invalidateCadModifierSession();
commitShapes(
shapes.map((shape) => shape.id === selectedShape.id ? restored.shape : shape),
shapesRef.current.map((shape) => shape.id === selectedShape.id ? restored.shape : shape),
restored.shape.id,
`Removed ${restored.label}`,
);
setNotice(`Removed ${restored.label}`);
}, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape, shapes]);
}, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape]);
const commitSketchProfile = useCallback(
(next: SketchProfile, message?: string) => {
const snapshot = cloneSketchProfile(next);
const current = sketchHistoryRef.current;
const currentIndex = Math.min(sketchHistoryIndexRef.current, Math.max(0, current.length - 1));
const trimmed = current.slice(0, currentIndex + 1);
const latest = trimmed.at(-1);
setSketchProfile(snapshot);
setSketchHistory((current) => {
const trimmed = current.slice(0, sketchHistoryIndex + 1);
return [...trimmed, cloneSketchProfile(snapshot)];
});
setSketchHistoryIndex(sketchHistoryIndex + 1);
if (latest && JSON.stringify(latest) === JSON.stringify(snapshot)) {
return;
}
const nextHistory = [...trimmed, cloneSketchProfile(snapshot)].slice(-MAX_SKETCH_HISTORY_ENTRIES);
sketchHistoryRef.current = nextHistory;
sketchHistoryIndexRef.current = nextHistory.length - 1;
setSketchHistory(nextHistory);
setSketchHistoryIndex(sketchHistoryIndexRef.current);
if (message) setNotice(message);
},
[sketchHistoryIndex],
[],
);
const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => {
@@ -5621,7 +5671,10 @@ export function SketchForgeEditor({
setSketchActive(true);
setSketchTool(profile?.segments.length ? "select" : "line");
setSketchProfile(initial);
setSketchHistory([cloneSketchProfile(initial)]);
const initialHistory = [cloneSketchProfile(initial)];
sketchHistoryRef.current = initialHistory;
sketchHistoryIndexRef.current = 0;
setSketchHistory(initialHistory);
setSketchHistoryIndex(0);
setSketchActivePointId(null);
setSketchSelection(null);
@@ -5650,30 +5703,36 @@ export function SketchForgeEditor({
}, []);
const sketchUndo = useCallback(() => {
if (sketchHistoryIndex <= 0) {
const currentHistory = sketchHistoryRef.current;
const currentIndex = sketchHistoryIndexRef.current;
if (currentIndex <= 0) {
setNotice("Nothing to undo in this sketch");
return;
}
const nextIndex = sketchHistoryIndex - 1;
const nextIndex = currentIndex - 1;
sketchHistoryIndexRef.current = nextIndex;
setSketchHistoryIndex(nextIndex);
setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile()));
setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile()));
setSketchActivePointId(null);
setSketchSelection(null);
setNotice("Sketch undo");
}, [sketchHistory, sketchHistoryIndex]);
}, []);
const sketchRedo = useCallback(() => {
if (sketchHistoryIndex >= sketchHistory.length - 1) {
const currentHistory = sketchHistoryRef.current;
const currentIndex = sketchHistoryIndexRef.current;
if (currentIndex >= currentHistory.length - 1) {
setNotice("Nothing to redo in this sketch");
return;
}
const nextIndex = sketchHistoryIndex + 1;
const nextIndex = currentIndex + 1;
sketchHistoryIndexRef.current = nextIndex;
setSketchHistoryIndex(nextIndex);
setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile()));
setSketchProfile(cloneSketchProfile(currentHistory[nextIndex] ?? emptySketchProfile()));
setSketchActivePointId(null);
setSketchSelection(null);
setNotice("Sketch redo");
}, [sketchHistory, sketchHistoryIndex]);
}, []);
const setActiveSketchTool = useCallback((tool: SketchTool) => {
setSketchTool(tool);
@@ -5999,7 +6058,11 @@ export function SketchForgeEditor({
lastProjectShapesEchoRef.current = null;
return;
}
if (lastProjectIdRef.current !== projectId) {
if (projectInteractionActiveRef.current) {
return;
}
const projectChanged = lastProjectIdRef.current !== projectId;
if (projectChanged) {
lastProjectIdRef.current = projectId;
lastProjectShapesSyncRef.current = "";
lastProjectShapesEchoRef.current = null;
@@ -6007,28 +6070,30 @@ export function SketchForgeEditor({
const incoming = initialShapes.map(canonicalizeShape);
const incomingSerialized = projectShapesFingerprint(incoming);
// The parent echoes shapes after a local save; rehydrating that echo can reset active transform state.
if (lastProjectShapesEchoRef.current !== null && incomingSerialized === lastProjectShapesEchoRef.current) {
if (!projectChanged && lastProjectShapesEchoRef.current !== null && incomingSerialized === lastProjectShapesEchoRef.current) {
lastProjectShapesSyncRef.current = incomingSerialized;
return;
}
if (projectInteractionActiveRef.current) {
return;
}
lastProjectShapesSyncRef.current = incomingSerialized;
if (projectSyncTimerRef.current !== null) {
window.clearTimeout(projectSyncTimerRef.current);
projectSyncTimerRef.current = null;
}
if (incomingSerialized === projectShapesFingerprint(shapes)) {
if (!projectChanged && incomingSerialized === projectShapesFingerprint(shapes)) {
return;
}
const hydratedHistory = hydrateEditorHistoryState(incoming, initialHistory, initialHistoryIndex);
projectHydratingRef.current = true;
shapesRef.current = incoming;
selectedIdsRef.current = [];
historyRef.current = hydratedHistory.entries;
historyIndexRef.current = hydratedHistory.index;
setShapes(incoming);
setSelectedIds([]);
setHistory([incoming]);
setHistoryIndex(0);
setHistory(hydratedHistory.entries);
setHistoryIndex(hydratedHistory.index);
setNotice(incoming.length ? "Project synced" : "Ready");
}, [initialShapes, projectId, projectRevision]);
}, [initialHistory, initialHistoryIndex, initialShapes, projectId, projectInteractionActive, projectRevision]);
useEffect(() => {
if (!projectId || !onProjectShapesChange) {
@@ -6142,6 +6207,7 @@ export function SketchForgeEditor({
}, [hasSelection, selectedShapes]);
const pasteShape = useCallback(async () => {
const sourceProjectId = projectInfoRef.current.projectId;
const systemClipboard = await readSystemClipboard();
const sharedClipboard = readSharedClipboard();
const sourceClipboard = systemClipboard.length > 0 ? systemClipboard : sharedClipboard.length > 0 ? sharedClipboard : clipboard;
@@ -6149,6 +6215,10 @@ export function SketchForgeEditor({
setNotice("SketchForge clipboard is empty");
return;
}
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice("Paste cancelled because the project changed");
return;
}
if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) {
setClipboard(sourceClipboard);
}
@@ -6162,38 +6232,56 @@ export function SketchForgeEditor({
}, [clipboard, commitShapes]);
const undo = useCallback(() => {
if (projectInteractionActiveRef.current) {
setNotice("Finish the current drag or transform before undoing");
return;
}
const modifierCancelled = invalidateCadModifierSession();
if (historyIndex <= 0) {
const currentHistory = historyRef.current;
const currentIndex = historyIndexRef.current;
if (currentIndex <= 0) {
setNotice(modifierCancelled ? "Edge modifier cancelled" : "Nothing to undo");
return;
}
const nextIndex = historyIndex - 1;
const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape);
const nextIndex = currentIndex - 1;
const entry = currentHistory[nextIndex];
const nextShapes = (entry?.shapes ?? []).map(canonicalizeShape);
const nextSelection = (entry?.selectedIds ?? []).filter((id) => nextShapes.some((shape) => shape.id === id));
historyIndexRef.current = nextIndex;
shapesRef.current = nextShapes;
selectedIdsRef.current = nextSelection;
setHistoryIndex(nextIndex);
setShapes(nextShapes);
setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id)));
setSelectedIds(nextSelection);
syncProjectShapes(nextShapes);
setNotice(modifierCancelled ? "Edge modifier cancelled · Undo" : "Undo");
}, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]);
}, [invalidateCadModifierSession, syncProjectShapes]);
const redo = useCallback(() => {
if (historyIndex >= history.length - 1) {
if (projectInteractionActiveRef.current) {
setNotice("Finish the current drag or transform before redoing");
return;
}
const currentHistory = historyRef.current;
const currentIndex = historyIndexRef.current;
if (currentIndex >= currentHistory.length - 1) {
setNotice("Nothing to redo");
return;
}
const modifierCancelled = invalidateCadModifierSession();
const nextIndex = historyIndex + 1;
const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape);
const nextIndex = currentIndex + 1;
const entry = currentHistory[nextIndex];
const nextShapes = (entry?.shapes ?? []).map(canonicalizeShape);
const nextSelection = (entry?.selectedIds ?? []).filter((id) => nextShapes.some((shape) => shape.id === id));
historyIndexRef.current = nextIndex;
shapesRef.current = nextShapes;
selectedIdsRef.current = nextSelection;
setHistoryIndex(nextIndex);
setShapes(nextShapes);
setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id)));
setSelectedIds(nextSelection);
syncProjectShapes(nextShapes);
setNotice(modifierCancelled ? "Edge modifier cancelled · Redo" : "Redo");
}, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]);
}, [invalidateCadModifierSession, syncProjectShapes]);
const toggleAlignMode = useCallback(() => {
if (selectedShapes.length < 2) {
@@ -6325,8 +6413,22 @@ export function SketchForgeEditor({
cadModifierRequestRef.current = requestId;
return new Promise<CadModifierWorkerResponse>((resolve, reject) => {
const timer = window.setTimeout(() => {
cadModifierPendingRef.current.delete(requestId);
reject(new Error("Timed out waiting for the CAD worker"));
if (!cadModifierPendingRef.current.has(requestId)) return;
const pendingRequests = [...cadModifierPendingRef.current.values()];
cadModifierPendingRef.current.clear();
pendingRequests.forEach((pending) => window.clearTimeout(pending.timer));
cadModifierWorkerRef.current?.terminate();
cadModifierWorkerRef.current = null;
const invalidationId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = invalidationId;
cadModifierLatestPreviewRef.current = invalidationId;
cadModifierPrepareRef.current = invalidationId;
cadModifierBaseShapeRef.current = null;
cadModifierBaseFingerprintRef.current = "";
cadModifierSourcePartsRef.current = [];
setEdgeModifier(null);
cadModifierWorkerRestartRef.current();
pendingRequests.forEach((pending) => pending.reject(new Error("Timed out waiting for the CAD worker; the worker was restarted")));
}, timeoutMs);
cadModifierPendingRef.current.set(requestId, { resolve, reject, timer });
try {
@@ -6349,6 +6451,7 @@ export function SketchForgeEditor({
setNotice(`Select one unlocked solid to ${kind}`);
return;
}
invalidateCadModifierSession();
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape];
@@ -6416,7 +6519,7 @@ export function SketchForgeEditor({
}
cadModifierPrepareRef.current = prepareRequestId;
armCadModifierWatchdog(prepareRequestId, "prepare");
}, [armCadModifierWatchdog, postCadModifierRequest, selectedShape, selectedShapes.length]);
}, [armCadModifierWatchdog, invalidateCadModifierSession, postCadModifierRequest, selectedShape, selectedShapes.length]);
const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => {
if (shape.locked || shape.hole) {
@@ -6468,8 +6571,10 @@ export function SketchForgeEditor({
params: Record<string, unknown>,
) => {
invalidateCadModifierSession();
const sourceFingerprint = projectShapesFingerprint([shape]);
const sourceProjectId = projectInfoRef.current.projectId;
const kind: CadModifierKind = params.kind === "fillet" ? "fillet" : "chamfer";
const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25)));
const sharpAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, mcpNumber(params.sharpAngle, 25)));
const amount = Math.max(MIN_EDGE_MODIFIER_AMOUNT, mcpNumber(params.amount, 1));
const chamferAngle = Math.max(5, Math.min(85, mcpNumber(params.chamferAngle, 45)));
const quality: CadModifierQuality = params.quality === "draft" || params.quality === "fine" ? params.quality : "standard";
@@ -6529,7 +6634,21 @@ export function SketchForgeEditor({
};
const createdAt = Date.now();
const groupedModifiedShape = groupedShapeWithComponentEdgeTreatment(shape, preview, sourceParts, session, feature, createdAt);
const modifiedShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(preview, shape, feature, preserveEdgeSize, createdAt);
const modifiedShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(
bakedEdgeTreatmentPreview(preview, shape),
shape,
feature,
preserveEdgeSize,
createdAt,
);
const currentTarget = shapesRef.current.find((candidate) => candidate.id === shape.id);
if (
projectInfoRef.current.projectId !== sourceProjectId ||
!currentTarget ||
projectShapesFingerprint([currentTarget]) !== sourceFingerprint
) {
throw new Error("The target object or project changed while the edge treatment was running; try again");
}
commitShapes(
shapesRef.current.map((candidate) => candidate.id === shape.id ? modifiedShape : candidate),
modifiedShape.id,
@@ -6581,7 +6700,7 @@ export function SketchForgeEditor({
createdAt,
);
const modifiedShape: WorkplaneShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(
previewShape,
bakedEdgeTreatmentPreview(previewShape, base),
base,
feature,
edgeModifier.preserveEdgeSize,
@@ -6601,7 +6720,9 @@ export function SketchForgeEditor({
if (event.key === "Escape") {
event.preventDefault();
cancelEdgeModifier();
} else if (event.key === "Enter" && edgeModifier.preview && !edgeModifier.busy && !edgeModifier.error) {
} else if (event.key === "Enter" && edgeModifier.preview && edgeModifier.selectedEdgeIds.length > 0 && !edgeModifier.busy && !edgeModifier.error) {
const target = event.target instanceof HTMLElement ? event.target : null;
if (target?.closest("input, select, textarea, button, [contenteditable='true']")) return;
event.preventDefault();
applyEdgeModifier();
}
@@ -6787,20 +6908,26 @@ export function SketchForgeEditor({
return;
}
const sourceFingerprint = projectShapesFingerprint(shapesRef.current);
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildGroupedShapeFromSelection(selectedShapes);
if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(shapesRef.current) !== sourceFingerprint) {
setNotice("The scene changed while grouping; select the objects and try again");
return;
}
const { group } = result;
if (!group) {
if (result.consumed) {
const selected = new Set(selectedIds);
commitShapes(shapes.filter((shape) => !selected.has(shape.id)), null, "Grouped: hole consumed solid");
commitShapes(shapesRef.current.filter((shape) => !selected.has(shape.id)), null, "Grouped: hole consumed solid");
return;
}
setNotice(result.failureNotice);
return;
}
const selected = new Set(selectedIds);
commitShapes([...shapes.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`);
}, [commitShapes, selectedIds, selectedShapes, shapes]);
commitShapes([...shapesRef.current.filter((shape) => !selected.has(shape.id)), group], group.id, `Grouped ${selectedShapes.length} shapes`);
}, [commitShapes, selectedIds, selectedShapes]);
const intersectSelected = useCallback(async () => {
const groupable = selectedShapes.filter((shape) => !shape.locked);
@@ -6811,14 +6938,20 @@ export function SketchForgeEditor({
return;
}
const sourceFingerprint = projectShapesFingerprint(shapesRef.current);
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildIntersectionShapeFromSelection(groupable);
if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(shapesRef.current) !== sourceFingerprint) {
setNotice("The scene changed while intersecting; select the objects and try again");
return;
}
if (!result.group && !result.empty) {
setNotice(result.failureNotice);
return;
}
const operandIds = new Set(groupable.map((shape) => shape.id));
const remainingShapes = shapes.filter((shape) => !operandIds.has(shape.id));
const remainingShapes = shapesRef.current.filter((shape) => !operandIds.has(shape.id));
if (result.empty) {
commitShapes(remainingShapes, null, "Intersection is empty");
return;
@@ -6829,7 +6962,7 @@ export function SketchForgeEditor({
return;
}
commitShapes([...remainingShapes, intersection], intersection.id, `Intersected ${groupable.length} shapes`);
}, [commitShapes, selectedShapes, shapes]);
}, [commitShapes, selectedShapes]);
const ungroupSelected = useCallback(() => {
const groups = selectedShapes.filter((shape) => shape.groupedShapes?.length);
@@ -6929,7 +7062,17 @@ export function SketchForgeEditor({
const profile = defaultMcpSketchProfile(width, depth);
const extruded = shapeFromSketchProfile(profile, height);
if (!extruded) throw new Error("Could not create the sketch profile");
shape = canonicalizeShape({ ...extruded, name, color, x, z, elevation, rotation: mcpNumber(params.rotation, 0) });
shape = canonicalizeShape({
...extruded,
name,
color,
x,
z,
elevation,
rotation: mcpNumber(params.rotation, 0),
rotationX: mcpNumber(params.rotationX, 0),
rotationZ: mcpNumber(params.rotationZ, 0),
});
} else if (kind === "box" || kind === "cylinder") {
shape = sceneShape({
name,
@@ -6950,8 +7093,9 @@ export function SketchForgeEditor({
} else {
throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch");
}
commitShapes([...currentShapes(), shape], shape.id, `${shape.name} added by MCP`);
return { object: mcpShapeSummary(shape) };
const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape));
commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`);
return { object: mcpShapeSummary(committedShape) };
}
if (command.action === "import_mesh") {
@@ -7016,6 +7160,9 @@ export function SketchForgeEditor({
if (!target) throw new Error("Object not found");
if (target.locked) throw new Error("Unlock the object before updating it");
const patch: ShapeUpdatePatch = {};
const rotationWasRequested = [params.rotation, params.rotationX, params.rotationZ].some(
(value) => typeof value === "number" && Number.isFinite(value),
);
(["x", "z", "elevation", "width", "depth", "height", "size", "rotation", "rotationX", "rotationZ"] as const).forEach((key) => {
if (typeof params[key] === "number" && Number.isFinite(params[key])) {
patch[key] = params[key];
@@ -7029,7 +7176,8 @@ export function SketchForgeEditor({
const patched = { ...shape, ...cleanShapePatch(patch) };
const width = shapeWidth(patched);
const depth = shapeDepth(patched);
return canonicalizeShape({ ...patched, size: Math.max(width, depth) });
const canonical = canonicalizeShape({ ...patched, size: Math.max(width, depth) });
return rotationWasRequested ? canonicalizeShape(bakeShapeTransformIntoMesh(canonical)) : canonical;
});
const updated = nextShapes.find((shape) => shape.id === target.id) as WorkplaneShape;
commitShapes(nextShapes, target.id, `${updated.name} updated by MCP`);
@@ -7073,7 +7221,12 @@ export function SketchForgeEditor({
const groupable = currentShapes().filter((shape) => ids.has(shape.id));
if (groupable.length < 2) throw new Error("Select at least two objects to group");
if (groupable.some((shape) => shape.locked)) throw new Error("Unlock every selected object before grouping");
const sourceFingerprint = projectShapesFingerprint(currentShapes());
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildGroupedShapeFromSelection(groupable);
if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(currentShapes()) !== sourceFingerprint) {
throw new Error("The scene changed while grouping; run the command again");
}
if (!result.group) {
if (result.consumed) {
commitShapes(currentShapes().filter((shape) => !ids.has(shape.id)), null, "MCP group consumed solid");
@@ -7109,7 +7262,12 @@ export function SketchForgeEditor({
if (operands.some((shape) => shape.locked)) {
throw new Error("Unlock every boolean operand before cutting");
}
const sourceFingerprint = projectShapesFingerprint(currentShapes());
const sourceProjectId = projectInfoRef.current.projectId;
const result = await buildGroupedShapeFromSelection(operands);
if (projectInfoRef.current.projectId !== sourceProjectId || projectShapesFingerprint(currentShapes()) !== sourceFingerprint) {
throw new Error("The scene changed while cutting; run the command again");
}
const remainingShapes = currentShapes().filter((shape) => !operandIds.has(shape.id));
if (result.consumed) {
commitShapes(remainingShapes, null, "MCP cut consumed solid");
@@ -7136,7 +7294,7 @@ export function SketchForgeEditor({
const target = findShape(params.id);
if (!target) throw new Error("Object not found");
invalidateCadModifierSession();
const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25)));
const sharpAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, mcpNumber(params.sharpAngle, 25)));
const { response } = await prepareCadModifierForMcp(target, sharpAngle);
const selectableEdgeIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id);
return { object: mcpShapeSummary(target), sharpAngle, selectableEdgeIds, edges: response.edges };
@@ -7551,6 +7709,7 @@ export function SketchForgeEditor({
return;
}
const sourceProjectId = projectInfoRef.current.projectId;
try {
let nextShape: WorkplaneShape;
if (isStep) {
@@ -7562,12 +7721,16 @@ export function SketchForgeEditor({
} else {
nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
}
commitShapes([...shapes, nextShape], nextShape.id, `Imported ${file.name}`);
if (projectInfoRef.current.projectId !== sourceProjectId) {
setNotice(`Import of ${file.name} cancelled because the project changed`);
return;
}
commitShapes([...shapesRef.current, nextShape], nextShape.id, `Imported ${file.name}`);
setTopPanel(null);
} catch (error) {
setNotice(error instanceof Error ? error.message : `Could not import ${file.name}`);
}
}, [commitShapes, shapes]);
}, [commitShapes]);
const selectFiles = useCallback(
(files: FileList | File[]) => {
@@ -7820,8 +7983,8 @@ export function SketchForgeEditor({
setTopPanel(null);
setMenuOpen(false);
}}
canUndo={historyIndex > 0 || Boolean(edgeModifier)}
canRedo={historyIndex < history.length - 1}
canUndo={!projectInteractionActive && (historyIndex > 0 || Boolean(edgeModifier))}
canRedo={!projectInteractionActive && historyIndex < history.length - 1}
canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)}
canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))}
canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))}
@@ -7989,7 +8152,7 @@ export function SketchForgeEditor({
onQualityChange={(quality) => setEdgeModifier((current) => current?.prepared ? { ...current, quality, preview: null, busy: true, error: null } : current)}
onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => {
if (!current?.prepared) return current;
const nextAngle = Math.max(1, Math.min(120, sharpAngle));
const nextAngle = Math.max(1, Math.min(CAD_MODIFIER_MAX_SHARP_ANGLE, sharpAngle));
const availableIds = new Set(current.edges
.filter((edge) => selectableCadModifierEdge(edge, nextAngle))
.map((edge) => edge.id));
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 { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import { edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
@@ -104,8 +104,12 @@ function EdgeModifierSlider({
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
event.currentTarget.blur();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(false);
}
@@ -216,8 +220,8 @@ export function EdgeModifierPanel({
</div>
<div className="edge-modifier-quick-actions">
<button type="button" disabled={!prepared} onClick={onSelectAll}>All sharp edges</button>
<button type="button" disabled={!prepared} onClick={onClear}>Clear</button>
<button type="button" disabled={!prepared || busy} onClick={onSelectAll}>All sharp edges</button>
<button type="button" disabled={!prepared || busy} onClick={onClear}>Clear</button>
</div>
{appliedFeatureCount > 0 ? (
@@ -260,27 +264,27 @@ export function EdgeModifierPanel({
step={EDGE_MODIFIER_AMOUNT_STEP}
workspace={workspace}
length
disabled={!prepared}
disabled={!prepared || busy}
onChange={onAmountChange}
/>
{kind === "chamfer" ? <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">
<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>
</label>
<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>
</label>
<label className="edge-modifier-field">
<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="standard">Standard</option>
<option value="fine">Fine</option>
@@ -106,8 +106,6 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
if (shape.kind === "cylinder") {
return [
{ 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: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
@@ -208,6 +206,7 @@ export function ShapeInspector({
onEditSketch,
canSeparateParts = false,
onSeparateParts,
onInteractionActiveChange,
}: {
shape: WorkplaneShape;
snap: GridSize;
@@ -220,6 +219,7 @@ export function ShapeInspector({
onEditSketch?: () => void;
canSeparateParts?: boolean;
onSeparateParts?: () => void;
onInteractionActiveChange?: (active: boolean) => void;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
@@ -227,6 +227,8 @@ export function ShapeInspector({
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
return (
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
@@ -300,6 +302,8 @@ export function ShapeInspector({
type="color"
value={solidColor}
disabled={locked}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onChange={(event) => {
onUpdate({ color: event.target.value, hole: false });
setColorOpen(false);
@@ -339,12 +343,12 @@ export function ShapeInspector({
<div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => {
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") {
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>
) : null}
@@ -403,7 +407,8 @@ function RangeProperty({
workspace,
disabled,
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 isLength = propertyUsesLengthUnit(label);
const accuracy = workspace.accuracy;
@@ -429,6 +434,7 @@ function RangeProperty({
const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
setEditing(false);
onInteractionActiveChange?.(false);
};
const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
@@ -449,6 +455,7 @@ function RangeProperty({
disabled={disabled}
inputMode="decimal"
onFocus={() => {
onInteractionActiveChange?.(true);
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(true);
}}
@@ -474,6 +481,11 @@ function RangeProperty({
step={controlStep}
value={sliderValue}
disabled={disabled}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onPointerDown={() => onInteractionActiveChange?.(true)}
onPointerUp={() => onInteractionActiveChange?.(false)}
onPointerCancel={() => onInteractionActiveChange?.(false)}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</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 (
<label className="text-property">
<span>{label}</span>
@@ -491,6 +503,8 @@ function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig &
disabled={disabled}
maxLength={24}
spellCheck={false}
onFocus={() => onInteractionActiveChange?.(true)}
onBlur={() => onInteractionActiveChange?.(false)}
onChange={(event) => onChange(event.currentTarget.value)}
/>
</label>
+1
View File
@@ -1,5 +1,6 @@
export const CAD_MODIFIER_RUNTIME_BASE = "/occt";
export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000;
export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview";
+71 -1
View File
@@ -1,12 +1,68 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
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;
}
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) {
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({
...before,
id: shape.id,
@@ -15,5 +71,19 @@ export function restoreShapeBeforeEdgeTreatment(shape: WorkplaneShape, entry: Ed
hole: shape.hole || undefined,
locked: shape.locked,
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) {
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;
}
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) {
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) {
@@ -57,7 +63,7 @@ export function resizedImportedCoordinates(shape: WorkplaneShape, sourcePosition
const depth = shapeDepth(shape);
const height = shape.height;
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);
for (let index = 0; index + 2 < sourcePositions.length; index += 3) {
if (preserve) {
+14
View File
@@ -105,6 +105,20 @@ export type EdgeTreatmentHistoryEntry = {
createdAt: number;
feature: EdgeTreatmentFeature;
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 = {
+145 -100
View File
@@ -50,7 +50,7 @@ function releaseSession(cad: OcctKernel) {
function cadShapeIsValid(cad: OcctKernel, shape: ShapeHandle) {
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 {
return Boolean(validator.call(cad, shape));
} catch {
@@ -280,69 +280,89 @@ function isSelectableModifierEdge(edge: CollectedCadEdgeGeometry) {
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 faces = cad.getSubShapes(shape, "face");
const faceByHash = new Map(faces.map((face) => [cad.hashCode(face, HASH_UPPER_BOUND), face]));
const faceAreaByHash = new Map<number, number>();
faces.forEach((face) => {
const hash = cad.hashCode(face, HASH_UPPER_BOUND);
let area = 0;
try {
area = Math.abs(cad.getSurfaceArea(face));
} catch {
area = 0;
let keepEdgeHandles = false;
try {
const faceByHash = new Map(faces.map((face) => [cad.hashCode(face, HASH_UPPER_BOUND), face]));
const faceAreaByHash = new Map<number, number>();
faces.forEach((face) => {
const hash = cad.hashCode(face, HASH_UPPER_BOUND);
let area = 0;
try {
area = Math.abs(cad.getSurfaceArea(face));
} catch {
area = 0;
}
faceAreaByHash.set(hash, area);
});
const treatmentAreaLimit = suppressTreatmentDetailEdges ? treatmentDetailFaceAreaLimit([...faceAreaByHash.values()]) : 0;
const adjacentFaces = parseEdgeFaceMap(cad.edgeToFaceMap(shape, HASH_UPPER_BOUND));
const wire = cad.wireframe(shape, CAD_EDGE_WIREFRAME_DEFLECTION);
const pointsByHash = new Map<number, number[]>();
for (let index = 0; index + 2 < wire.edgeGroups.length; index += 3) {
const start = wire.edgeGroups[index];
const count = wire.edgeGroups[index + 1];
const hash = wire.edgeGroups[index + 2];
if (!pointsByHash.has(hash)) pointsByHash.set(hash, Array.from(wire.points.slice(start, start + count)));
}
faceAreaByHash.set(hash, area);
});
const treatmentAreaLimit = suppressTreatmentDetailEdges ? treatmentDetailFaceAreaLimit([...faceAreaByHash.values()]) : 0;
const adjacentFaces = parseEdgeFaceMap(cad.edgeToFaceMap(shape, HASH_UPPER_BOUND));
const wire = cad.wireframe(shape, CAD_EDGE_WIREFRAME_DEFLECTION);
const pointsByHash = new Map<number, number[]>();
for (let index = 0; index + 2 < wire.edgeGroups.length; index += 3) {
const start = wire.edgeGroups[index];
const count = wire.edgeGroups[index + 1];
const hash = wire.edgeGroups[index + 2];
if (!pointsByHash.has(hash)) pointsByHash.set(hash, Array.from(wire.points.slice(start, start + count)));
}
const collectedEdges = handles.map((handle, id) => {
const hash = cad.hashCode(handle, HASH_UPPER_BOUND);
const faceHashes = adjacentFaces.get(hash) ?? [];
const points = pointsByHash.get(hash) ?? [];
const classification = edgeAngle(cad, points, faceHashes, faceByHash);
const faceAreas = faceHashes.map((faceHash) => faceAreaByHash.get(faceHash) ?? 0);
const surfaceTypes = faceHashes
.map((faceHash) => faceByHash.get(faceHash))
.filter((face): face is ShapeHandle => face !== undefined)
.map((face) => {
try {
return cad.surfaceType(face);
} catch {
return "unknown";
}
});
let curveType = "line";
try {
curveType = cad.curveType(handle);
} catch {
curveType = "unknown";
}
return { id, points, ...classification, curveType, surfaceTypes, faceAreas };
}).filter((edge) => edge.points.length >= 6);
const edges: CollectedCadEdge[] = collectedEdges.map((edge) => ({
...edge,
display: treatmentAreaLimit > 0 ? isModifierDisplayCadEdge(edge, treatmentAreaLimit) : isDisplayCadEdge(edge),
selectable: isSelectableModifierEdge(edge),
}));
const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const displayEdges = cadDisplayEdgesFromCollected(edges);
return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, faceAreas: _faceAreas, ...edge }) => edge), selectableEdgeIds, displayEdges };
const collectedEdges = handles.map((handle, id) => {
const hash = cad.hashCode(handle, HASH_UPPER_BOUND);
const faceHashes = adjacentFaces.get(hash) ?? [];
const points = pointsByHash.get(hash) ?? [];
const classification = edgeAngle(cad, points, faceHashes, faceByHash);
const faceAreas = faceHashes.map((faceHash) => faceAreaByHash.get(faceHash) ?? 0);
const surfaceTypes = faceHashes
.map((faceHash) => faceByHash.get(faceHash))
.filter((face): face is ShapeHandle => face !== undefined)
.map((face) => {
try {
return cad.surfaceType(face);
} catch {
return "unknown";
}
});
let curveType = "line";
try {
curveType = cad.curveType(handle);
} catch {
curveType = "unknown";
}
return { id, points, ...classification, curveType, surfaceTypes, faceAreas };
}).filter((edge) => edge.points.length >= 6);
const edges: CollectedCadEdge[] = collectedEdges.map((edge) => {
const display = treatmentAreaLimit > 0 ? isModifierDisplayCadEdge(edge, treatmentAreaLimit) : isDisplayCadEdge(edge);
return {
...edge,
display,
selectable: isSelectableModifierEdge(edge) && (treatmentAreaLimit <= 0 || display),
};
});
const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const displayEdges = cadDisplayEdgesFromCollected(edges);
keepEdgeHandles = retainEdgeHandles;
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[] {
return edges
.filter(isDisplayCadEdge)
.filter((edge) => edge.display)
.map((edge) => ({ points: edge.points }));
}
@@ -387,15 +407,31 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
if (request.type === "prepare") {
releaseSession(activeCad);
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;
baseSolids = activeCad.isSolid(baseShape) ? [baseShape] : activeCad.getSubShapes(baseShape, "solid");
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))));
edgeOwners = edgeHandles.map((edge) => {
const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND);
return Math.max(0, ownerHashes.findIndex((hashes) => hashes.has(hash)));
});
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) => {
const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND);
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({
type: "ready",
requestId: request.requestId,
@@ -408,44 +444,52 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
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);
if (selected.length === 0) throw new Error("Select at least one highlighted edge");
const componentResults = baseSolids.map((solid, owner) => {
const componentEdges = selected.filter((entry) => entry.owner === owner).map((entry) => entry.edge);
if (componentEdges.length === 0) return activeCad.copy(solid);
return request.kind === "fillet"
? activeCad.fillet(solid, componentEdges, request.amount)
: Math.abs(request.chamferAngle - 45) < 0.001
? activeCad.chamfer(solid, componentEdges, request.amount)
: activeCad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
});
const 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");
const options = tessellationOptions(request.quality, request.amount);
const mesh = copyCadMesh(activeCad.tessellate(result, options));
const displayEdges = collectEdges(activeCad, result, request.chamferAngle).displayEdges;
const brep = activeCad.toBREP(result);
const components: CadModifierComponentMesh[] = componentResults.map((component, owner) => {
const componentMesh = copyCadMesh(activeCad.tessellate(component, options));
return {
owner,
positions: componentMesh.positions,
normals: componentMesh.normals,
indices: componentMesh.indices,
triangleCount: componentMesh.triangleCount,
brep: activeCad.toBREP(component),
displayEdges: collectEdges(activeCad, component, request.chamferAngle).displayEdges,
};
});
componentResults.forEach((component) => activeCad.release(component));
if (componentResults.length > 1) activeCad.release(result);
post(
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges, components },
[
mesh.positions.buffer,
mesh.normals.buffer,
mesh.indices.buffer,
...components.flatMap((component) => [component.positions.buffer, component.normals.buffer, component.indices.buffer]),
],
);
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 component = componentEdges.length === 0
? activeCad.copy(solid)
: request.kind === "fillet"
? activeCad.fillet(solid, componentEdges, request.amount)
: Math.abs(request.chamferAngle - 45) < 0.001
? activeCad.chamfer(solid, componentEdges, request.amount)
: activeCad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
componentResults.push(component);
}
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");
const options = tessellationOptions(request.quality, request.amount);
const mesh = copyCadMesh(activeCad.tessellate(result, options));
const displayEdges = collectEdges(activeCad, result, 0).displayEdges;
const brep = activeCad.toBREP(result);
const components: CadModifierComponentMesh[] = componentResults.map((component, owner) => {
const componentMesh = copyCadMesh(activeCad.tessellate(component, options));
return {
owner,
positions: componentMesh.positions,
normals: componentMesh.normals,
indices: componentMesh.indices,
triangleCount: componentMesh.triangleCount,
brep: activeCad.toBREP(component),
displayEdges: collectEdges(activeCad, component, 0).displayEdges,
};
});
post(
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges, components },
[
mesh.positions.buffer,
mesh.normals.buffer,
mesh.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) {
const rawMessage = error instanceof Error ? error.message : String(error ?? "");
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:"))
? `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";
if (request.type === "prepare" && cad) releaseSession(cad);
post({ type: "error", requestId: request.requestId, message });
}
};