release: publish v0.9.0 modeling update

This commit is contained in:
Formsmith
2026-08-02 17:38:53 +03:00
parent ab2f34aa80
commit c5f34422e4
28 changed files with 3099 additions and 402 deletions
+354 -69
View File
@@ -1,6 +1,6 @@
"use client";
import { Check, CloudUpload, Download, FolderOpen, X } from "lucide-react";
import { Check, CloudUpload, Download, Eye, FolderOpen, X } from "lucide-react";
import type manifoldModule from "manifold-3d";
import type { ManifoldToplevel } from "manifold-3d";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -20,6 +20,7 @@ import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
import { createGearGeometry } from "@/lib/gearGeometry";
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
import {
ToolbarAlignIcon,
ToolbarChamferIcon,
@@ -44,7 +45,6 @@ import {
ToolbarUngroupIcon,
ToolbarUndoIcon,
ToolbarVectorExportIcon,
ToolbarWorkplaneIcon,
} from "./icons";
import { WorkplaneViewport } from "./WorkplaneViewport";
import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type SketchTool } from "./SketchWorkspace";
@@ -71,6 +71,7 @@ import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups";
import {
CAD_MODIFIER_MAX_SHARP_ANGLE,
CAD_MODIFIER_REQUEST_TIMEOUT_MS,
cadModifierPrepareTimeoutMs,
cadModifierTimeoutMessage,
cadModifierWorkerFailureMessage,
defaultCadModifierTangentChain,
@@ -91,6 +92,17 @@ import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import {
normalizePlacementWorkplane,
placementPatchForNewShape,
placementWorkplaneCoordinates,
placementWorkplaneFromSurface,
placementWorkplaneIsBase,
translationToWorkplane,
type PlacementPoint,
type PlacementWorkplane,
} from "@/lib/placementWorkplane";
import { placeSketchExtrusion } from "@/lib/sketchPlacement";
import {
SKETCHFORGE_MCP_POLL_MS,
SKETCHFORGE_MCP_ROUTE,
@@ -104,7 +116,7 @@ import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset,
export { importedShapeFromStl, importedShapeFromSvg };
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type TopPanel = "import" | "export" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj" | "step" | "svg" | "skf";
type DirectExportFormat = Exclude<ExportFormat, "step" | "skf">;
type SkfHistoryLimit = EditorHistoryExportLimit;
@@ -1857,9 +1869,10 @@ function createBooleanWedgeGeometry(width: number, height: number, depth: number
function createBooleanPyramidGeometry(width: number, height: number, depth: number, sides = 4) {
const count = Math.max(3, Math.round(sides));
if (count !== 4) {
const radius = Math.min(width, depth) / 2;
const geometry = new THREE.ConeGeometry(radius, height, count);
geometry.translate(0, height / 2, 0);
const footprintScale = regularPolygonFootprintScale(width, depth, count);
const geometry = new THREE.ConeGeometry(1, height, count);
geometry.scale(footprintScale.x, 1, footprintScale.z);
geometry.translate(footprintScale.offsetX, height / 2, footprintScale.offsetZ);
return geometry;
}
@@ -2146,6 +2159,63 @@ function meshForShape(shape: WorkplaneShape): MeshData {
return transformMesh(raw, shape);
}
function sketchReferenceShapeOnWorkplane(shape: WorkplaneShape, workplane: PlacementWorkplane): WorkplaneShape {
const mesh = meshForShape(shape);
const projectedVertices = mesh.vertices.map(([x, y, z]) => {
const local = placementWorkplaneCoordinates(workplane, { x, y, z });
return { x: local.x, y: -local.y, z: local.z };
});
const minX = Math.min(...projectedVertices.map((vertex) => vertex.x));
const maxX = Math.max(...projectedVertices.map((vertex) => vertex.x));
const minY = Math.min(...projectedVertices.map((vertex) => vertex.y));
const maxY = Math.max(...projectedVertices.map((vertex) => vertex.y));
const minZ = Math.min(...projectedVertices.map((vertex) => vertex.z));
const maxZ = Math.max(...projectedVertices.map((vertex) => vertex.z));
const centerX = (minX + maxX) / 2;
const centerY = (minY + maxY) / 2;
const centerZ = (minZ + maxZ) / 2;
const positions = mesh.faces.flatMap(([a, b, c]) => [a, b, c].flatMap((index) => {
const vertex = projectedVertices[index];
return [vertex.x - centerX, vertex.y - centerY, vertex.z - centerZ];
}));
const width = Math.max(0.01, maxX - minX);
const depth = Math.max(0.01, maxZ - minZ);
const height = Math.max(0.01, maxY - minY);
return canonicalizeShape({
...shape,
kind: "mesh",
x: centerX,
z: centerZ,
elevation: 0,
size: Math.max(width, depth),
width,
depth,
height,
rotation: 0,
rotationX: 0,
rotationZ: 0,
mirrorX: undefined,
mirrorY: undefined,
mirrorZ: undefined,
importedMesh: {
positions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
triangleCount: mesh.faces.length,
sourceFormat: "json",
},
groupedShapes: undefined,
edgeTreatments: undefined,
edgeTreatmentHistory: undefined,
cadDisplayEdges: undefined,
cadBrep: undefined,
cadBrepFrame: undefined,
cadPrimitiveFrame: undefined,
});
}
function appendMeshData(vertices: Vec3[], faces: [number, number, number][], mesh: MeshData) {
const offset = vertices.length;
for (let i = 0; i < mesh.vertices.length; i += 1) {
@@ -5195,6 +5265,7 @@ export function SketchForgeEditor({
initialSnap,
initialWorkspace,
initialPlacementElevation = 0,
initialPlacementWorkplane,
onHome,
onOpenSkfProjectFile,
onSaveSharedProject,
@@ -5218,6 +5289,7 @@ export function SketchForgeEditor({
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
initialPlacementElevation?: number;
initialPlacementWorkplane?: PlacementWorkplane;
onHome?: () => void;
onOpenSkfProjectFile?: (file: File) => Promise<{ ok: boolean; message: string } | void> | { ok: boolean; message: string } | void;
onSaveSharedProject?: (request: { exportName: string; bytes: Uint8Array }) => Promise<string>;
@@ -5232,9 +5304,18 @@ export function SketchForgeEditor({
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
placementWorkplane: PlacementWorkplane;
sketchPlacementWorkplane: PlacementWorkplane;
}) => void;
onProjectSnapshot?: (snapshot: { image: string; projectId: string; shapes: number }) => void;
onProjectWorkspaceChange?: (snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => void;
onProjectWorkspaceChange?: (snapshot: {
projectId: string;
workspace: WorkplaneWorkspaceSettings;
snap: GridSize;
placementElevation?: number;
placementWorkplane?: PlacementWorkplane;
sketchPlacementWorkplane?: PlacementWorkplane;
}) => void;
projectId?: string | null;
projectName?: string;
projectCreatedAt?: number;
@@ -5266,6 +5347,9 @@ export function SketchForgeEditor({
const [history, setHistory] = useState<EditorHistoryEntry[]>(() => (initialHistoryStateRef.current as EditorHistoryState).entries);
const [historyIndex, setHistoryIndex] = useState(() => (initialHistoryStateRef.current as EditorHistoryState).index);
const [placementElevation, setPlacementElevation] = useState(() => Number.isFinite(initialPlacementElevation) ? initialPlacementElevation : 0);
const [placementWorkplane, setPlacementWorkplane] = useState<PlacementWorkplane>(
() => normalizePlacementWorkplane(initialPlacementWorkplane, initialPlacementElevation),
);
const [workspaceSettings, setWorkspaceSettings] = useState<WorkplaneWorkspaceSettings>(() => normalizeWorkspaceSettings(initialWorkspace));
const [snapGrid, setSnapGrid] = useState<GridSize>(() => normalizeSnapGrid(initialSnap));
const [workplaneMode, setWorkplaneMode] = useState(false);
@@ -5298,6 +5382,7 @@ export function SketchForgeEditor({
const workspaceSettingsRef = useRef(workspaceSettings);
const snapGridRef = useRef(snapGrid);
const placementElevationRef = useRef(placementElevation);
const placementWorkplaneRef = useRef(placementWorkplane);
const noticeRef = useRef(notice);
const projectInfoRef = useRef({ projectId: projectId ?? null, projectName, projectCreatedAt });
const historyIndexRef = useRef(historyIndex);
@@ -5309,6 +5394,9 @@ export function SketchForgeEditor({
const [projectInteractionActive, setProjectInteractionActive] = useState(false);
const [toolbarMode, setToolbarMode] = useState<ToolbarMode>("geometry");
const [sketchActive, setSketchActive] = useState(false);
const [activeSketchWorkplane, setActiveSketchWorkplane] = useState<PlacementWorkplane>(
() => normalizePlacementWorkplane(initialPlacementWorkplane, initialPlacementElevation),
);
const [sketchOperation, setSketchOperation] = useState<SketchOperation>("extrude");
const [sketchRevolveSettings, setSketchRevolveSettings] = useState<SketchRevolveSettings>(() => ({ ...DEFAULT_SKETCH_REVOLVE_SETTINGS }));
const [sketchRevolvePreview, setSketchRevolvePreview] = useState<SketchRevolveMesh | null>(null);
@@ -5352,7 +5440,7 @@ export function SketchForgeEditor({
cadModifierWatchdogRef.current = null;
}, []);
const armCadModifierWatchdog = useCallback((requestId: number, phase: CadModifierRequestPhase) => {
const armCadModifierWatchdog = useCallback((requestId: number, phase: CadModifierRequestPhase, timeoutMs = CAD_MODIFIER_REQUEST_TIMEOUT_MS) => {
clearCadModifierWatchdog();
const timer = window.setTimeout(() => {
const active = cadModifierWatchdogRef.current;
@@ -5370,7 +5458,7 @@ export function SketchForgeEditor({
error: message,
} : current);
setNotice(message);
}, CAD_MODIFIER_REQUEST_TIMEOUT_MS);
}, timeoutMs);
cadModifierWatchdogRef.current = { requestId, phase, timer };
}, [clearCadModifierWatchdog]);
@@ -5598,6 +5686,10 @@ export function SketchForgeEditor({
placementElevationRef.current = placementElevation;
}, [placementElevation]);
useEffect(() => {
placementWorkplaneRef.current = placementWorkplane;
}, [placementWorkplane]);
useEffect(() => {
noticeRef.current = notice;
}, [notice]);
@@ -5712,6 +5804,14 @@ export function SketchForgeEditor({
: shapes,
[alignMode, alignPreview, edgeModifier?.preview, effectiveAlignAnchorId, mirrorMode, mirrorPreviewAxis, selectedIds, selectedShapes, shapes],
);
const sketchReferenceShapes = useMemo(
() => sketchOperation === "revolve" || placementWorkplaneIsBase(activeSketchWorkplane)
? shapes
: shapes.map((shape) => shape.hidden || shape.id === editingSketchShapeId
? shape
: sketchReferenceShapeOnWorkplane(shape, activeSketchWorkplane)),
[activeSketchWorkplane, editingSketchShapeId, shapes, sketchOperation],
);
const debugState = useMemo(
() =>
JSON.stringify({
@@ -5828,6 +5928,8 @@ export function SketchForgeEditor({
workspace: workspaceSettingsRef.current,
snapGrid: snapGridRef.current,
placementElevation: placementElevationRef.current,
placementWorkplane: placementWorkplaneRef.current,
sketchPlacementWorkplane: placementWorkplaneRef.current,
});
projectSyncTimerRef.current = null;
}, 120);
@@ -5944,7 +6046,14 @@ export function SketchForgeEditor({
if (!projectId || !onProjectWorkspaceChange) {
return;
}
onProjectWorkspaceChange({ projectId, workspace: nextWorkspace, snap: settings.snap, placementElevation });
onProjectWorkspaceChange({
projectId,
workspace: nextWorkspace,
snap: settings.snap,
placementElevation,
placementWorkplane: placementWorkplaneRef.current,
sketchPlacementWorkplane: placementWorkplaneRef.current,
});
},
[onProjectWorkspaceChange, placementElevation, projectId],
);
@@ -5956,8 +6065,10 @@ export function SketchForgeEditor({
workspace: workspaceSettingsRef.current,
snap: snapGrid,
placementElevation,
placementWorkplane,
sketchPlacementWorkplane: placementWorkplane,
});
}, [onProjectWorkspaceChange, placementElevation, projectId, snapGrid]);
}, [onProjectWorkspaceChange, placementElevation, placementWorkplane, projectId, snapGrid]);
const commitShapes = useCallback(
(next: WorkplaneShape[], nextSelection: string | string[] | null = selectedIds, message?: string) => {
@@ -6035,8 +6146,16 @@ export function SketchForgeEditor({
[],
);
const beginSketch = useCallback((operation: SketchOperation, profile?: SketchProfile, editingId: string | null = null, revolveSettings?: Partial<SketchRevolveSettings>) => {
const beginSketch = useCallback((
operation: SketchOperation,
profile?: SketchProfile,
editingId: string | null = null,
revolveSettings?: Partial<SketchRevolveSettings>,
workplaneOverride?: PlacementWorkplane,
) => {
const initial = cloneSketchProfile(profile ?? emptySketchProfile());
setWorkplaneMode(false);
setActiveSketchWorkplane(normalizePlacementWorkplane(workplaneOverride ?? placementWorkplaneRef.current));
setToolbarMode("sketch");
setSketchActive(true);
setSketchOperation(operation);
@@ -6063,7 +6182,34 @@ export function SketchForgeEditor({
return;
}
const operation = selectedShape.sketchOperation ?? (selectedShape.sketchRevolve ? "revolve" : "extrude");
beginSketch(operation, selectedShape.sketchProfile, selectedShape.id, selectedShape.sketchRevolve);
let editWorkplane: PlacementWorkplane | undefined;
if (operation === "extrude") {
const quaternion = quaternionForShape(selectedShape);
const normal = new THREE.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
const xAxis = new THREE.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
const zAxis = new THREE.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
const points = selectedShape.sketchProfile.points;
const profileCenterX = points.length
? (Math.min(...points.map((point) => point.x)) + Math.max(...points.map((point) => point.x))) / 2
: 0;
const profileCenterZ = points.length
? (Math.min(...points.map((point) => point.z)) + Math.max(...points.map((point) => point.z))) / 2
: 0;
const origin = new THREE.Vector3(
selectedShape.x,
(selectedShape.elevation ?? 0) + selectedShape.height / 2,
selectedShape.z,
)
.addScaledVector(normal, -selectedShape.height / 2)
.addScaledVector(xAxis, -profileCenterX)
.addScaledVector(zAxis, -profileCenterZ);
editWorkplane = placementWorkplaneFromSurface(
{ x: origin.x, y: origin.y, z: origin.z },
{ x: normal.x, y: normal.y, z: normal.z },
{ x: xAxis.x, y: xAxis.y, z: xAxis.z },
);
}
beginSketch(operation, selectedShape.sketchProfile, selectedShape.id, selectedShape.sketchRevolve, editWorkplane);
}, [beginSketch, selectedShape, selectedShapes.length]);
const cancelSketch = useCallback(() => {
@@ -6416,9 +6562,12 @@ export function SketchForgeEditor({
const height = existing?.height ?? 10;
let resolved: WorkplaneShape | null;
try {
resolved = sketchOperation === "revolve"
? await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing)
: await shapeFromSketchProfile(sketchProfile, height, existing);
if (sketchOperation === "revolve") {
resolved = await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing);
} else {
const extrusion = await shapeFromSketchProfile(sketchProfile, height, existing);
resolved = extrusion ? placeSketchExtrusion(extrusion, activeSketchWorkplane, existing) : null;
}
} catch (error) {
setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`);
return;
@@ -6434,7 +6583,7 @@ export function SketchForgeEditor({
setSketchRevolvePreview(null);
setEditingSketchShapeId(null);
setToolbarMode("geometry");
}, [commitShapes, editingSketchShapeId, shapes, sketchOperation, sketchProfile, sketchRevolveSettings]);
}, [activeSketchWorkplane, commitShapes, editingSketchShapeId, shapes, sketchOperation, sketchProfile, sketchRevolveSettings]);
useEffect(() => {
if (!projectId) {
@@ -6454,7 +6603,9 @@ export function SketchForgeEditor({
const nextAssets = dedupeProjectAssets(initialAssets);
projectAssetsRef.current = nextAssets;
setProjectAssets(nextAssets);
setPlacementElevation(Number.isFinite(initialPlacementElevation) ? initialPlacementElevation : 0);
const nextPlacementElevation = Number.isFinite(initialPlacementElevation) ? initialPlacementElevation : 0;
setPlacementElevation(nextPlacementElevation);
setPlacementWorkplane(normalizePlacementWorkplane(initialPlacementWorkplane, nextPlacementElevation));
}
const incoming = initialShapes.map(canonicalizeShape);
const incomingSerialized = projectShapesFingerprint(incoming);
@@ -6487,7 +6638,7 @@ export function SketchForgeEditor({
setHistory(hydratedHistory.entries);
setHistoryIndex(hydratedHistory.index);
setNotice("Ready");
}, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialShapes, projectId, projectRevision]);
}, [initialAssets, initialHistory, initialHistoryIndex, initialPlacementElevation, initialPlacementWorkplane, initialShapes, projectId, projectRevision]);
useEffect(() => {
if (!projectId || !onProjectShapesChange) {
@@ -6514,11 +6665,15 @@ export function SketchForgeEditor({
}, []);
const addShape = useCallback(
(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }) => {
const nextShape = makeShapeFromAsset(asset, point ?? { x: 0, z: 0, elevation: placementElevation });
(asset: ShapeAsset, point?: PlacementPoint) => {
const shape = makeShapeFromAsset(asset);
const nextShape = {
...shape,
...placementPatchForNewShape(shape, placementWorkplane, point ?? placementWorkplane.origin),
};
commitShapes([...shapes, nextShape], nextShape.id, `${asset.name} added`);
},
[commitShapes, placementElevation, shapes],
[commitShapes, placementWorkplane, shapes],
);
const scheduleRevolveShapeUpdate = useCallback((id: string, settings: SketchRevolveSettings) => {
@@ -6976,7 +7131,7 @@ export function SketchForgeEditor({
return;
}
cadModifierPrepareRef.current = prepareRequestId;
armCadModifierWatchdog(prepareRequestId, "prepare");
armCadModifierWatchdog(prepareRequestId, "prepare", cadModifierPrepareTimeoutMs(triangleCount));
}, [armCadModifierWatchdog, invalidateCadModifierSession, postCadModifierRequest, selectedShape, selectedShapes.length]);
const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => {
@@ -7017,7 +7172,7 @@ export function SketchForgeEditor({
parts,
sharpAngle,
suppressTreatmentDetailEdges: appliedEdgeTreatmentCount > 0,
}, transfer);
}, transfer, cadModifierPrepareTimeoutMs(triangleCount));
if (response.type !== "ready") {
throw new Error("The CAD worker did not return an edge list");
}
@@ -7313,12 +7468,15 @@ export function SketchForgeEditor({
return;
}
const selected = new Set(selectedIds);
const normal = placementWorkplane.normal;
commitShapes(
shapes.map((shape) =>
selected.has(shape.id) && !shape.locked
? {
...shape,
elevation: Math.max(0, Math.min(180, (shape.elevation ?? 0) + delta)),
x: cleanNearZero(shape.x + normal.x * delta),
z: cleanNearZero(shape.z + normal.z * delta),
elevation: cleanNearZero((shape.elevation ?? 0) + normal.y * delta),
}
: shape,
),
@@ -7326,7 +7484,7 @@ export function SketchForgeEditor({
delta > 0 ? "Moved selection up" : "Moved selection down",
);
},
[commitShapes, hasSelection, selectedIds, shapes],
[commitShapes, hasSelection, placementWorkplane, selectedIds, shapes],
);
const dropSelectedToWorkplane = useCallback(() => {
@@ -7336,23 +7494,52 @@ export function SketchForgeEditor({
}
const selected = new Set(selectedIds);
commitShapes(
shapes.map((shape) => (selected.has(shape.id) && !shape.locked ? { ...shape, ...dropPatchForShape(shape, placementElevation) } : shape)),
shapes.map((shape) => {
if (!selected.has(shape.id) || shape.locked) return shape;
const translation = translationToWorkplane(
placementWorkplane,
meshForShape(shape).vertices.map(([x, y, z]) => ({ x, y, z })),
);
return {
...shape,
x: cleanNearZero(shape.x + translation.x),
z: cleanNearZero(shape.z + translation.z),
elevation: cleanNearZero((shape.elevation ?? 0) + translation.y),
};
}),
selectedIds,
placementElevation === 0 ? "Dropped selection to the workplane" : `Dropped selection to ${placementElevation.toFixed(2)} mm workplane`,
"Dropped selection to the workplane",
);
}, [commitShapes, hasSelection, placementElevation, selectedIds, shapes]);
}, [commitShapes, hasSelection, placementWorkplane, selectedIds, shapes]);
const activateWorkplaneTool = useCallback(() => {
setWorkplaneMode((active) => {
const next = !active;
setNotice(next ? "Workplane tool: click a shape top or empty grid" : "Workplane tool cancelled");
setNotice(next ? "Workplane tool: click a face or empty grid; hold Shift to reverse" : "Workplane tool cancelled");
return next;
});
}, []);
const setPlacementWorkplane = useCallback((elevation: number, source: "shape" | "base") => {
setPlacementElevation(elevation);
setNotice(source === "shape" ? `Workplane set to ${elevation.toFixed(2)} mm` : "Workplane reset to base");
const setActivePlacementWorkplane = useCallback((next: PlacementWorkplane, source: "shape" | "base") => {
placementWorkplaneRef.current = next;
setPlacementWorkplane(next);
const horizontalElevation = Math.abs(next.normal.x) < 1e-6
&& Math.abs(next.normal.y - 1) < 1e-6
&& Math.abs(next.normal.z) < 1e-6
? next.origin.y
: 0;
setPlacementElevation(horizontalElevation);
setNotice(source === "shape"
? "Workplane set to selected face"
: placementWorkplaneIsBase(next) ? "Workplane reset to base" : "Workplane updated");
}, []);
const setViewportPlacementWorkplane = useCallback((next: PlacementWorkplane, source: "shape" | "base") => {
setActivePlacementWorkplane(next, source);
}, [setActivePlacementWorkplane]);
const closeViewportWorkplaneMode = useCallback((active: boolean) => {
setWorkplaneMode(active);
}, []);
const groupSelected = useCallback(async () => {
@@ -8145,6 +8332,8 @@ export function SketchForgeEditor({
workspace: workspaceSettingsRef.current,
snapGrid,
placementElevation,
placementWorkplane,
sketchPlacementWorkplane: placementWorkplane,
});
if (target === "shared" && onSaveSharedProject) {
setNotice(await onSaveSharedProject({ exportName: exportName.trim() || projectName, bytes }));
@@ -8158,7 +8347,7 @@ export function SketchForgeEditor({
} finally {
setSkfExporting(false);
}
}, [onSaveSharedProject, placementElevation, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]);
}, [onSaveSharedProject, placementElevation, placementWorkplane, projectCreatedAt, projectModifiedAt, projectName, skfExporting, snapGrid]);
const clearDesign = useCallback(() => {
commitShapes([], [], "New empty design");
@@ -8336,13 +8525,19 @@ export function SketchForgeEditor({
return;
}
const selected = new Set(selectedIds);
const translation = {
x: placementWorkplane.xAxis.x * deltaX + placementWorkplane.zAxis.x * deltaZ,
y: placementWorkplane.xAxis.y * deltaX + placementWorkplane.zAxis.y * deltaZ,
z: placementWorkplane.xAxis.z * deltaX + placementWorkplane.zAxis.z * deltaZ,
};
commitShapes(
shapes.map((shape) =>
selected.has(shape.id) && !shape.locked
? {
...shape,
x: Math.max(-110, Math.min(110, shape.x + deltaX)),
z: Math.max(-110, Math.min(110, shape.z + deltaZ)),
x: cleanNearZero(shape.x + translation.x),
z: cleanNearZero(shape.z + translation.z),
elevation: cleanNearZero((shape.elevation ?? 0) + translation.y),
}
: shape,
),
@@ -8350,7 +8545,7 @@ export function SketchForgeEditor({
`Moved ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"}`,
);
},
[commitShapes, hasSelection, selectedIds, selectedShapes.length, shapes],
[commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes.length, shapes],
);
useEffect(() => {
@@ -8552,6 +8747,7 @@ export function SketchForgeEditor({
toolbarMode={toolbarMode}
onToolbarModeChange={(mode) => {
setToolbarMode(mode);
setWorkplaneMode(false);
setTopPanel(null);
setMenuOpen(false);
}}
@@ -8562,6 +8758,8 @@ export function SketchForgeEditor({
canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))}
hasClipboard={clipboard.length > 0 || systemClipboardSupported}
hasSelection={hasSelection}
hiddenShapeCount={shapes.filter((shape) => shape.hidden).length}
selectionHidden={hasSelection && selectedShapes.every((shape) => shape.hidden)}
alignMode={alignMode}
canAlign={selectedShapes.length > 1}
canEdgeModify={selectedShapes.length === 1 && Boolean(selectedShape && !selectedShape.locked && !selectedShape.hole)}
@@ -8601,15 +8799,10 @@ export function SketchForgeEditor({
onPaste={pasteShape}
onRedo={redo}
onSnap={snapSelected}
onTips={() => {
setTopPanel(topPanel === "tips" ? null : "tips");
setMenuOpen(false);
}}
onShowHidden={showHidden}
onToggleHidden={toggleHidden}
onUngroup={ungroupSelected}
onUndo={undo}
onWorkplaneTool={activateWorkplaneTool}
workplaneMode={workplaneMode}
onTopPanel={(panel) => {
setTopPanel((current) => (current === panel ? null : panel));
setMenuOpen(false);
@@ -8626,7 +8819,7 @@ export function SketchForgeEditor({
profile={sketchProfile}
operation={sketchOperation}
revolvePreviewPositions={sketchRevolvePreview?.positions ?? null}
referenceShapes={shapes.filter((shape) => shape.id !== editingSketchShapeId)}
referenceShapes={sketchReferenceShapes.filter((shape) => shape.id !== editingSketchShapeId)}
tool={sketchTool}
activePointId={sketchActivePointId}
selected={sketchSelection}
@@ -8671,7 +8864,7 @@ export function SketchForgeEditor({
alignReferenceShapes={shapes}
mirrorMode={mirrorMode}
mirrorReferenceShapes={shapes}
placementElevation={placementElevation}
placementWorkplane={placementWorkplane}
workplaneMode={workplaneMode}
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
@@ -8685,14 +8878,15 @@ export function SketchForgeEditor({
onMirrorPreviewClear={clearMirrorPreview}
onMirrorSelection={mirrorSelectionAcross}
onSelectShape={selectShape}
onSetPlacementElevation={setPlacementWorkplane}
onSetPlacementWorkplane={setViewportPlacementWorkplane}
onToggleWorkplaneTool={activateWorkplaneTool}
onInteractionActiveChange={updateProjectInteractionActive}
onEditSketch={beginSketchEdit}
canSeparateParts={canSeparateSelectedParts}
onSeparateParts={separateSelectedParts}
onUpdateShape={updateShape}
onWorkspaceSettingsChange={updateProjectWorkspaceSettings}
onWorkplaneModeChange={setWorkplaneMode}
onWorkplaneModeChange={closeViewportWorkplaneMode}
modifierActive={Boolean(edgeModifier)}
modifierPreviewActive={Boolean(edgeModifier?.preview)}
modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []}
@@ -8862,6 +9056,8 @@ function SecondaryToolbar({
canUndo,
hasClipboard,
hasSelection,
hiddenShapeCount,
selectionHidden,
mirrorMode,
sketchActive,
sketchOperation,
@@ -8891,12 +9087,10 @@ function SecondaryToolbar({
onPaste,
onRedo,
onSnap,
onTips,
onShowHidden,
onToggleHidden,
onUngroup,
onUndo,
onWorkplaneTool,
workplaneMode,
onTopPanel,
onAddShape,
}: {
@@ -8913,6 +9107,8 @@ function SecondaryToolbar({
canUndo: boolean;
hasClipboard: boolean;
hasSelection: boolean;
hiddenShapeCount: number;
selectionHidden: boolean;
mirrorMode: boolean;
sketchActive: boolean;
sketchOperation: SketchOperation;
@@ -8942,23 +9138,25 @@ function SecondaryToolbar({
onPaste: () => void;
onRedo: () => void;
onSnap: () => void;
onTips: () => void;
onShowHidden: () => void;
onToggleHidden: () => void;
onUngroup: () => void;
onUndo: () => void;
onWorkplaneTool: () => void;
workplaneMode: boolean;
onTopPanel: (panel: TopPanel) => void;
onAddShape: (shape: ShapeAsset) => void;
}) {
const [shapesOpen, setShapesOpen] = useState(false);
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
const [visibilityOpen, setVisibilityOpen] = useState(false);
const [visibilityMenuPosition, setVisibilityMenuPosition] = useState({ top: 0, left: 0 });
const sketchCreateMenuRef = useRef<HTMLDivElement>(null);
const visibilityMenuRef = useRef<HTMLDivElement>(null);
const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
const suppressNextShapeClickRef = useRef(false);
const selectToolbarMode = (mode: "geometry" | "sketch") => {
setShapesOpen(false);
setSketchCreateOpen(false);
setVisibilityOpen(false);
onTopPanel(null);
onToolbarModeChange(mode);
};
@@ -8988,6 +9186,51 @@ function SecondaryToolbar({
useEffect(() => {
if (sketchActive) setSketchCreateOpen(false);
}, [sketchActive]);
useEffect(() => {
if (!visibilityOpen) return;
const closeOnPointerDown = (event: PointerEvent) => {
if (!visibilityMenuRef.current?.contains(event.target as Node)) setVisibilityOpen(false);
};
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") setVisibilityOpen(false);
};
const closeOnViewportChange = () => setVisibilityOpen(false);
window.addEventListener("pointerdown", closeOnPointerDown);
window.addEventListener("keydown", closeOnEscape);
window.addEventListener("resize", closeOnViewportChange);
window.addEventListener("scroll", closeOnViewportChange, true);
return () => {
window.removeEventListener("pointerdown", closeOnPointerDown);
window.removeEventListener("keydown", closeOnEscape);
window.removeEventListener("resize", closeOnViewportChange);
window.removeEventListener("scroll", closeOnViewportChange, true);
};
}, [visibilityOpen]);
const toggleVisibilityMenu = () => {
if (visibilityOpen) {
setVisibilityOpen(false);
return;
}
const triggerBounds = visibilityMenuRef.current?.getBoundingClientRect();
if (triggerBounds) {
const viewportGutter = 12;
const menuWidth = Math.min(276, Math.max(0, window.innerWidth - viewportGutter * 2));
setVisibilityMenuPosition({
top: triggerBounds.bottom + 8,
left: Math.max(
viewportGutter,
Math.min(
triggerBounds.left + triggerBounds.width / 2 - menuWidth / 2,
window.innerWidth - menuWidth - viewportGutter,
),
),
});
}
setShapesOpen(false);
setSketchCreateOpen(false);
onTopPanel(null);
setVisibilityOpen(true);
};
const leftTools = [
{ label: "Copy", icon: ToolbarCopyIcon, action: onCopy, enabled: hasSelection },
{ label: "Paste", icon: ToolbarPasteIcon, action: onPaste, enabled: hasClipboard },
@@ -8997,8 +9240,15 @@ function SecondaryToolbar({
{ label: "Redo", icon: ToolbarRedoIcon, action: onRedo, enabled: canRedo },
];
const visibilityTools = [
{ label: "Hide selected", icon: ToolbarHideSelectedIcon, action: onToggleHidden, enabled: hasSelection },
{ label: "Visibility options", icon: ToolbarCaretDownIcon, action: onTips, enabled: hasSelection },
{
label: selectionHidden ? "Show selected" : "Hide selected",
icon: ToolbarHideSelectedIcon,
action: () => {
setVisibilityOpen(false);
onToggleHidden();
},
enabled: hasSelection,
},
];
const combineTools = [
{ label: "Group", icon: ToolbarGroupIcon, action: onGroup, enabled: canGroup },
@@ -9013,7 +9263,6 @@ function SecondaryToolbar({
{ label: "Fillet", icon: ToolbarFilletIcon, action: onFillet, enabled: canEdgeModify, active: edgeModifierKind === "fillet" },
];
const arrangeTools = [
{ label: "Workplane", icon: ToolbarWorkplaneIcon, action: onWorkplaneTool, enabled: true, active: workplaneMode },
{ label: "Drop to workplane", icon: ToolbarDropToWorkplaneIcon, action: onDropToWorkplane, enabled: hasSelection },
];
const renderToolButton = (tool: (typeof leftTools)[number] | (typeof visibilityTools)[number] | (typeof combineTools)[number] | (typeof modifyTools)[number] | (typeof arrangeTools)[number]) => {
@@ -9059,7 +9308,10 @@ function SecondaryToolbar({
className={`shape-menu-trigger ${shapesOpen ? "active" : ""}`}
aria-label="Add shape"
aria-expanded={shapesOpen}
onClick={() => setShapesOpen((value) => !value)}
onClick={() => {
setVisibilityOpen(false);
setShapesOpen((value) => !value);
}}
>
<ToolbarShapeAddIcon />
</button>
@@ -9138,9 +9390,49 @@ function SecondaryToolbar({
</div>
<div className="toolbar-spacer" />
<div className="tool-group right">
<div className="toolbar-section compact">
<div className="toolbar-section compact toolbar-visibility-section" ref={visibilityMenuRef}>
<div className="toolbar-section-label">Visibility</div>
<div className="toolbar-section-tools">{visibilityTools.map(renderToolButton)}</div>
<div className="toolbar-section-tools">
{visibilityTools.map(renderToolButton)}
<button
className={`toolbar-icon visibility-menu-trigger ${visibilityOpen ? "active" : ""}`}
type="button"
aria-label="Visibility options"
title="Visibility options"
aria-haspopup="menu"
aria-expanded={visibilityOpen}
onClick={toggleVisibilityMenu}
>
<ToolbarCaretDownIcon />
</button>
</div>
{visibilityOpen ? (
<div
className="visibility-dropdown"
role="menu"
aria-label="Visibility options"
style={visibilityMenuPosition}
>
<button
className="visibility-dropdown-action"
type="button"
role="menuitem"
disabled={hiddenShapeCount === 0}
onClick={() => {
setVisibilityOpen(false);
onShowHidden();
}}
>
<Eye size={20} aria-hidden="true" />
<strong>{hiddenShapeCount === 0 ? "Nothing hidden" : `Show all hidden (${hiddenShapeCount})`}</strong>
</button>
<div className="visibility-dropdown-help">
<span>Eye again: selected</span>
<span aria-hidden="true">·</span>
<span><kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>H</kbd>: all</span>
</div>
</div>
) : null}
</div>
<div className="toolbar-section">
<div className="toolbar-section-label">Combine</div>
@@ -9353,11 +9645,9 @@ function TopActionPanel({
? "Profile"
: panel === "settings"
? "Settings"
: panel === "tips"
? "Tips"
: panel === "export"
? "Export"
: "Import";
: panel === "export"
? "Export"
: "Import";
const exportDetails: Record<ExportFormat, { label: string; description: string; note: string }> = {
stl: {
@@ -9544,11 +9834,6 @@ function TopActionPanel({
</footer>
</div>
) : null}
{panel === "tips" ? (
<div className="top-action-body">
<p>Click a shape to select it. Use the inspector for dimensions, rotation, solid/hole, color, duplicate, and delete.</p>
</div>
) : null}
{panel === "settings" ? (
<div className="top-action-body">
<p>Workspace preferences</p>