release: add sketch revolve and configurable gears

This commit is contained in:
Formsmith
2026-07-24 11:55:44 +03:00
parent 5dde9faceb
commit fe161f8d75
32 changed files with 1913 additions and 115 deletions
+231 -19
View File
@@ -18,6 +18,7 @@ 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 { createGearGeometry } from "@/lib/gearGeometry";
import {
ToolbarAlignIcon,
ToolbarChamferIcon,
@@ -80,6 +81,7 @@ import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
@@ -95,7 +97,7 @@ import {
type SketchForgeMcpViewFace,
} from "@/lib/sketchforgeMcpProtocol";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl, importedShapeFromSvg };
@@ -390,6 +392,7 @@ async function shapeFromResolvedSketchProfile(
sourceFormat: "json",
},
sketchProfile: cloneSketchProfile(profile),
sketchOperation: "extrude",
} satisfies WorkplaneShape);
} finally {
[...new Set(disposable)].reverse().forEach(disposeManifold);
@@ -505,6 +508,50 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex
sourceFormat: "json",
},
sketchProfile: cloneSketchProfile(profile),
sketchOperation: "extrude",
} satisfies WorkplaneShape);
}
async function shapeFromRevolvedSketchProfile(
profile: SketchProfile,
settings: Partial<SketchRevolveSettings>,
existing?: WorkplaneShape | null,
) {
const runtime = await getManifoldRuntime();
const normalizedSettings = normalizeSketchRevolveSettings(settings);
const mesh = buildSketchRevolveMesh(runtime, profile, normalizedSettings);
return canonicalizeShape({
id: existing?.id ?? createLocalId("sketch-revolve"),
name: existing?.name ?? "Sketch revolve",
kind: "mesh",
color: existing?.color ?? "#78b96b",
hole: existing?.hole,
x: existing?.x ?? 0,
z: existing?.z ?? 0,
elevation: existing?.elevation ?? 0,
size: Math.max(mesh.width, mesh.depth),
width: mesh.width,
depth: mesh.depth,
height: mesh.height,
rotation: existing?.rotation ?? 0,
rotationX: existing?.rotationX ?? 0,
rotationZ: existing?.rotationZ ?? 0,
mirrorX: existing?.mirrorX,
mirrorY: existing?.mirrorY,
mirrorZ: existing?.mirrorZ,
importedMesh: {
positions: mesh.positions,
baseWidth: mesh.width,
baseDepth: mesh.depth,
baseHeight: mesh.height,
triangleCount: mesh.triangleCount,
sourceFormat: "json",
},
sketchProfile: cloneSketchProfile(profile),
sketchOperation: "revolve",
sketchRevolve: normalizedSettings,
locked: existing?.locked ?? false,
hidden: existing?.hidden ?? false,
} satisfies WorkplaneShape);
}
@@ -2029,6 +2076,20 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null {
case "tube":
geometry = createBooleanHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144);
break;
case "gear":
geometry = createGearGeometry({
width,
depth,
height,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
centerHoleSize: shape.centerHoleSize,
gearType: shape.gearType,
helixAngle: shape.helixAngle,
helixQuality: shape.helixQuality,
});
break;
case "wedge":
geometry = createBooleanWedgeGeometry(width, height, depth);
break;
@@ -5229,6 +5290,12 @@ export function SketchForgeEditor({
const [projectInteractionActive, setProjectInteractionActive] = useState(false);
const [toolbarMode, setToolbarMode] = useState<ToolbarMode>("geometry");
const [sketchActive, setSketchActive] = useState(false);
const [sketchOperation, setSketchOperation] = useState<SketchOperation>("extrude");
const [sketchRevolveSettings, setSketchRevolveSettings] = useState<SketchRevolveSettings>(() => ({ ...DEFAULT_SKETCH_REVOLVE_SETTINGS }));
const [sketchRevolvePreview, setSketchRevolvePreview] = useState<SketchRevolveMesh | null>(null);
const sketchRevolvePreviewRequestRef = useRef(0);
const sketchRevolveUpdateRequestRef = useRef(new Map<string, number>());
const sketchRevolveUpdateTimerRef = useRef(new Map<string, number>());
const [sketchTool, setSketchTool] = useState<SketchTool>("line");
const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile());
const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]);
@@ -5532,6 +5599,26 @@ export function SketchForgeEditor({
edgeModifierRef.current = edgeModifier;
}, [edgeModifier]);
useEffect(() => {
const requestId = sketchRevolvePreviewRequestRef.current + 1;
sketchRevolvePreviewRequestRef.current = requestId;
if (!sketchActive || sketchOperation !== "revolve" || sketchProfile.segments.length === 0) {
setSketchRevolvePreview(null);
return;
}
const timer = window.setTimeout(() => {
void getManifoldRuntime()
.then((runtime) => buildSketchRevolveMesh(runtime, sketchProfile, sketchRevolveSettings))
.then((mesh) => {
if (sketchRevolvePreviewRequestRef.current === requestId) setSketchRevolvePreview(mesh);
})
.catch(() => {
if (sketchRevolvePreviewRequestRef.current === requestId) setSketchRevolvePreview(null);
});
}, 90);
return () => window.clearTimeout(timer);
}, [sketchActive, sketchOperation, sketchProfile, sketchRevolveSettings]);
useEffect(() => {
setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace));
}, [initialWorkspace]);
@@ -5854,10 +5941,13 @@ export function SketchForgeEditor({
[],
);
const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => {
const beginSketch = useCallback((operation: SketchOperation, profile?: SketchProfile, editingId: string | null = null, revolveSettings?: Partial<SketchRevolveSettings>) => {
const initial = cloneSketchProfile(profile ?? emptySketchProfile());
setToolbarMode("sketch");
setSketchActive(true);
setSketchOperation(operation);
setSketchRevolveSettings(normalizeSketchRevolveSettings(revolveSettings));
setSketchRevolvePreview(null);
setSketchTool(profile?.segments.length ? "select" : "line");
setSketchProfile(initial);
const initialHistory = [cloneSketchProfile(initial)];
@@ -5870,7 +5960,7 @@ export function SketchForgeEditor({
setSketchMeasureStart(null);
setSketchMeasurement(null);
setEditingSketchShapeId(editingId);
setNotice(editingId ? "Editing sketch profile" : "Sketch started: place the first point");
setNotice(editingId ? `Editing ${operation} sketch profile` : operation === "revolve" ? "Revolve sketch started: draw on the left side of the axis" : "Sketch started: place the first point");
}, []);
const beginSketchEdit = useCallback(() => {
@@ -5878,7 +5968,8 @@ export function SketchForgeEditor({
setNotice("Select one shape created from a sketch to edit it");
return;
}
beginSketch(selectedShape.sketchProfile, selectedShape.id);
const operation = selectedShape.sketchOperation ?? (selectedShape.sketchRevolve ? "revolve" : "extrude");
beginSketch(operation, selectedShape.sketchProfile, selectedShape.id, selectedShape.sketchRevolve);
}, [beginSketch, selectedShape, selectedShapes.length]);
const cancelSketch = useCallback(() => {
@@ -5888,6 +5979,7 @@ export function SketchForgeEditor({
setSketchMeasureStart(null);
setSketchMeasurement(null);
setEditingSketchShapeId(null);
setSketchRevolvePreview(null);
setNotice("Sketch cancelled");
}, []);
@@ -6228,23 +6320,27 @@ export function SketchForgeEditor({
const finishSketch = useCallback(async () => {
const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null;
const height = existing?.height ?? 10;
let extruded: WorkplaneShape | null;
let resolved: WorkplaneShape | null;
try {
extruded = await shapeFromSketchProfile(sketchProfile, height, existing);
resolved = sketchOperation === "revolve"
? await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing)
: await shapeFromSketchProfile(sketchProfile, height, existing);
} catch (error) {
setNotice(error instanceof Error ? error.message : "The sketch profile cannot be converted to 3D");
setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`);
return;
}
if (!extruded) {
if (!resolved) {
setNotice("Close at least one profile before finishing the sketch");
return;
}
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? extruded : shape)) : [...shapes, extruded];
commitShapes(nextShapes, extruded.id, existing ? "Sketch updated" : "Sketch created at 10 mm height");
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved];
const action = sketchOperation === "revolve" ? "Revolve sketch" : "Sketch";
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Sketch created at 10 mm height");
setSketchActive(false);
setSketchRevolvePreview(null);
setEditingSketchShapeId(null);
setToolbarMode("geometry");
}, [commitShapes, editingSketchShapeId, shapes, sketchProfile]);
}, [commitShapes, editingSketchShapeId, shapes, sketchOperation, sketchProfile, sketchRevolveSettings]);
useEffect(() => {
if (!projectId) {
@@ -6313,6 +6409,8 @@ export function SketchForgeEditor({
if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current);
}
sketchRevolveUpdateTimerRef.current.forEach((timer) => window.clearTimeout(timer));
sketchRevolveUpdateTimerRef.current.clear();
};
}, []);
@@ -6324,10 +6422,72 @@ export function SketchForgeEditor({
[commitShapes, placementElevation, shapes],
);
const scheduleRevolveShapeUpdate = useCallback((id: string, settings: SketchRevolveSettings) => {
const previousTimer = sketchRevolveUpdateTimerRef.current.get(id);
if (previousTimer !== undefined) window.clearTimeout(previousTimer);
const requestId = (sketchRevolveUpdateRequestRef.current.get(id) ?? 0) + 1;
sketchRevolveUpdateRequestRef.current.set(id, requestId);
const timer = window.setTimeout(() => {
sketchRevolveUpdateTimerRef.current.delete(id);
const source = shapesRef.current.find((shape) => shape.id === id);
if (!source?.sketchProfile || source.sketchOperation !== "revolve") return;
setNotice("Updating revolve preview…");
void shapeFromRevolvedSketchProfile(source.sketchProfile, settings, source)
.then((generated) => {
if (sketchRevolveUpdateRequestRef.current.get(id) !== requestId) return;
const current = shapesRef.current.find((shape) => shape.id === id);
if (!current?.importedMesh || current.sketchOperation !== "revolve") return;
const widthScale = current.width / Math.max(0.001, current.importedMesh.baseWidth);
const depthScale = current.depth / Math.max(0.001, current.importedMesh.baseDepth);
const heightScale = current.height / Math.max(0.001, current.importedMesh.baseHeight);
const width = generated.width * widthScale;
const depth = generated.depth * depthScale;
const height = generated.height * heightScale;
const updated = canonicalizeShape({
...generated,
id: current.id,
name: current.name,
color: current.color,
hole: current.hole,
x: current.x,
z: current.z,
elevation: current.elevation,
width,
depth,
height,
size: Math.max(width, depth),
rotation: current.rotation,
rotationX: current.rotationX,
rotationZ: current.rotationZ,
mirrorX: current.mirrorX,
mirrorY: current.mirrorY,
mirrorZ: current.mirrorZ,
locked: current.locked,
hidden: current.hidden,
sketchRevolve: settings,
});
commitShapes(shapesRef.current.map((shape) => shape.id === id ? updated : shape), selectedIdsRef.current, "Revolve updated");
})
.catch((error) => {
if (sketchRevolveUpdateRequestRef.current.get(id) === requestId) {
setNotice(error instanceof Error ? error.message : "The revolve settings could not be applied");
}
});
}, 120);
sketchRevolveUpdateTimerRef.current.set(id, timer);
}, [commitShapes]);
const updateShape = useCallback(
(id: string, patch: ShapeUpdatePatch) => {
const bakeTransform = Boolean(patch.bakeTransform);
const cleanedPatch = cleanShapePatch(patch);
if (cleanedPatch.sketchRevolve) {
const source = shapesRef.current.find((shape) => shape.id === id);
if (source?.sketchOperation === "revolve" && source.sketchProfile) {
scheduleRevolveShapeUpdate(id, normalizeSketchRevolveSettings(cleanedPatch.sketchRevolve));
return;
}
}
const applyPatch = (current: WorkplaneShape[]) => {
let changed = false;
const next = current.map((shape) => {
@@ -6365,7 +6525,7 @@ export function SketchForgeEditor({
commitShapes(next, selectedIds);
}
},
[commitShapes, selectedIds, shapes],
[commitShapes, scheduleRevolveShapeUpdate, selectedIds, shapes],
);
const deleteSelected = useCallback(() => {
@@ -8309,11 +8469,12 @@ export function SketchForgeEditor({
edgeModifierKind={edgeModifier?.kind ?? null}
mirrorMode={mirrorMode}
sketchActive={sketchActive}
sketchOperation={sketchOperation}
sketchTool={sketchTool}
sketchCanUndo={sketchHistoryIndex > 0}
sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1}
canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)}
onStartSketch={() => beginSketch()}
onStartSketch={(operation) => beginSketch(operation)}
onEditSketch={beginSketchEdit}
onSketchTool={setActiveSketchTool}
onSketchImage={() => {
@@ -8364,6 +8525,8 @@ export function SketchForgeEditor({
{toolbarMode === "sketch" && sketchActive ? (
<SketchWorkspace
profile={sketchProfile}
operation={sketchOperation}
revolvePreviewPositions={sketchRevolvePreview?.positions ?? null}
referenceShapes={shapes.filter((shape) => shape.id !== editingSketchShapeId)}
tool={sketchTool}
activePointId={sketchActivePointId}
@@ -8599,6 +8762,7 @@ function SecondaryToolbar({
hasSelection,
mirrorMode,
sketchActive,
sketchOperation,
sketchTool,
sketchCanUndo,
sketchCanRedo,
@@ -8649,11 +8813,12 @@ function SecondaryToolbar({
hasSelection: boolean;
mirrorMode: boolean;
sketchActive: boolean;
sketchOperation: SketchOperation;
sketchTool: SketchTool;
sketchCanUndo: boolean;
sketchCanRedo: boolean;
canEditSketch: boolean;
onStartSketch: () => void;
onStartSketch: (operation: SketchOperation) => void;
onEditSketch: () => void;
onSketchTool: (tool: SketchTool) => void;
onSketchImage: () => void;
@@ -8685,10 +8850,13 @@ function SecondaryToolbar({
onAddShape: (shape: ShapeAsset) => void;
}) {
const [shapesOpen, setShapesOpen] = useState(false);
const [sketchCreateOpen, setSketchCreateOpen] = useState(false);
const sketchCreateMenuRef = 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);
onTopPanel(null);
onToolbarModeChange(mode);
};
@@ -8696,6 +8864,28 @@ function SecondaryToolbar({
onAddShape(shape);
setShapesOpen(false);
};
const startSketch = (operation: SketchOperation) => {
setSketchCreateOpen(false);
onStartSketch(operation);
};
useEffect(() => {
if (!sketchCreateOpen) return;
const closeOnPointerDown = (event: PointerEvent) => {
if (!sketchCreateMenuRef.current?.contains(event.target as Node)) setSketchCreateOpen(false);
};
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") setSketchCreateOpen(false);
};
window.addEventListener("pointerdown", closeOnPointerDown);
window.addEventListener("keydown", closeOnEscape);
return () => {
window.removeEventListener("pointerdown", closeOnPointerDown);
window.removeEventListener("keydown", closeOnEscape);
};
}, [sketchCreateOpen]);
useEffect(() => {
if (sketchActive) setSketchCreateOpen(false);
}, [sketchActive]);
const leftTools = [
{ label: "Copy", icon: ToolbarCopyIcon, action: onCopy, enabled: hasSelection },
{ label: "Paste", icon: ToolbarPasteIcon, action: onPaste, enabled: hasClipboard },
@@ -8945,7 +9135,7 @@ function SecondaryToolbar({
<div className="toolbar-section-tools">
<button className="sketch-command-button primary" type="button" onClick={onSketchFinish}>
<Check />
<span>Finish sketch</span>
<span>{sketchOperation === "revolve" ? "Finish revolve" : "Finish sketch"}</span>
</button>
<button className="sketch-command-button cancel" type="button" onClick={onSketchCancel}>
<X />
@@ -8958,10 +9148,32 @@ function SecondaryToolbar({
<div className="toolbar-section sketch-start-section">
<div className="toolbar-section-label">Create</div>
<div className="toolbar-section-tools">
<button className="sketch-command-button primary" type="button" onClick={onStartSketch}>
<SketchReferenceIcon name="sketchTo3d" />
<span>Sketch to 3D</span>
</button>
<div className="sketch-create-menu" ref={sketchCreateMenuRef}>
<button
className={`sketch-command-button primary sketch-create-menu-trigger ${sketchCreateOpen ? "active" : ""}`}
type="button"
aria-label="Sketch to 3D options"
aria-haspopup="menu"
aria-expanded={sketchCreateOpen}
onClick={() => setSketchCreateOpen((open) => !open)}
>
<SketchReferenceIcon name="sketchTo3d" />
<span>Sketch to 3D</span>
<ToolbarCaretDownIcon className="sketch-create-menu-chevron" />
</button>
{sketchCreateOpen ? (
<div className="sketch-create-dropdown" role="menu" aria-label="Sketch to 3D method">
<button type="button" role="menuitem" onClick={() => startSketch("extrude")}>
<strong>Extrude sketch</strong>
<span>Raise the profile into a 3D shape</span>
</button>
<button type="button" role="menuitem" onClick={() => startSketch("revolve")}>
<strong>Revolve sketch</strong>
<span>Rotate the profile around an axis</span>
</button>
</div>
) : null}
</div>
<button className={`sketch-command-button ${canEditSketch ? "" : "disabled"}`} type="button" aria-label="Edit Sketch to 3D" title="Edit Sketch to 3D" onClick={onEditSketch} disabled={!canEditSketch}>
<SketchReferenceIcon name="editSketchTo3d" />
<span>Edit</span>
@@ -0,0 +1,72 @@
"use client";
import { useEffect, useRef } from "react";
import * as THREE from "three";
export function SketchRevolvePreview({ positions }: { positions: number[] | null }) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !positions?.length) return;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(34, 1, 0.01, 5000);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.computeVertexNormals();
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
const material = new THREE.MeshStandardMaterial({ color: "#8ccf79", roughness: 0.68, metalness: 0.02, side: THREE.DoubleSide });
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
scene.add(new THREE.HemisphereLight("#ffffff", "#b7cadd", 2.2));
const key = new THREE.DirectionalLight("#ffffff", 3.2);
key.position.set(-3, 5, 4);
key.castShadow = true;
scene.add(key);
const fill = new THREE.DirectionalLight("#b9ddff", 1.2);
fill.position.set(4, 2, -3);
scene.add(fill);
const bounds = geometry.boundingBox ?? new THREE.Box3().setFromObject(mesh);
const center = bounds.getCenter(new THREE.Vector3());
const radius = Math.max(1, geometry.boundingSphere?.radius ?? 1);
camera.position.set(center.x + radius * 1.8, center.y + radius * 1.2, center.z + radius * 2.1);
camera.lookAt(center);
camera.near = Math.max(0.01, radius / 100);
camera.far = radius * 20;
camera.updateProjectionMatrix();
const render = () => {
const width = Math.max(1, canvas.clientWidth);
const height = Math.max(1, canvas.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.render(scene, camera);
};
render();
const observer = new ResizeObserver(render);
observer.observe(canvas);
return () => {
observer.disconnect();
geometry.dispose();
material.dispose();
renderer.dispose();
};
}, [positions]);
return (
<aside className="sketch-revolve-preview" aria-label="Revolve 3D preview">
<div className="sketch-revolve-preview-title">3D preview</div>
{positions?.length ? <canvas ref={canvasRef} /> : <div className="sketch-revolve-preview-empty">Draw a profile left of the axis</div>}
</aside>
);
}
+60 -17
View File
@@ -3,9 +3,12 @@
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
import { parseMeasurementInput } from "@/lib/measurementUnits";
import { WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure";
export type SketchSelection =
@@ -18,6 +21,8 @@ export type SketchMeasurement = { start: SketchPoint; end: SketchPoint } | null;
type SketchWorkspaceProps = {
profile: SketchProfile;
operation?: SketchOperation;
revolvePreviewPositions?: number[] | null;
referenceShapes: WorkplaneShape[];
tool: SketchTool;
activePointId: string | null;
@@ -398,6 +403,8 @@ function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint
export function SketchWorkspace({
profile,
operation = "extrude",
revolvePreviewPositions = null,
referenceShapes,
tool,
activePointId,
@@ -680,7 +687,8 @@ export function SketchWorkspace({
return (
<main className="sketch-workspace-stage">
<div className="sketch-mode-badge">Sketch view</div>
<div className="sketch-mode-badge">{operation === "revolve" ? "Revolve sketch" : "Sketch view"}</div>
{operation === "revolve" ? <SketchRevolvePreview positions={revolvePreviewPositions} /> : null}
<div className="camera-controls sketch-camera-controls" aria-label="Sketch view controls">
<button aria-label="Reset sketch view" onClick={() => { setZoom(1); setPan({ x: 0, z: 0 }); }}><Home size={28} /></button>
<button aria-label="Zoom in" onClick={() => setZoom((value) => clamp(value * 1.25, 0.75, 6))}><Plus size={33} /></button>
@@ -702,8 +710,15 @@ export function SketchWorkspace({
<rect className="sketch-plate-background" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} />
{workspace.showGrid ? (
<g className="sketch-grid" pointerEvents="none">
{verticalLines.map((x, index) => <line className={Math.abs(x) < 0.0001 ? "axis" : index % 4 === 0 ? "major" : "minor"} key={`x-${x}`} x1={x} y1={-workspace.depth / 2} x2={x} y2={workspace.depth / 2} />)}
{horizontalLines.map((z, index) => <line className={Math.abs(z) < 0.0001 ? "axis" : index % 4 === 0 ? "major" : "minor"} key={`z-${z}`} x1={-workspace.width / 2} y1={z} x2={workspace.width / 2} y2={z} />)}
{verticalLines.map((x, index) => <line className={Math.abs(x) < 0.0001 ? "axis" : index % WORKPLANE_MAJOR_GRID_INTERVAL === 0 ? "major" : "minor"} key={`x-${x}`} x1={x} y1={-workspace.depth / 2} x2={x} y2={workspace.depth / 2} />)}
{horizontalLines.map((z, index) => <line className={Math.abs(z) < 0.0001 ? "axis" : index % WORKPLANE_MAJOR_GRID_INTERVAL === 0 ? "major" : "minor"} key={`z-${z}`} x1={-workspace.width / 2} y1={z} x2={workspace.width / 2} y2={z} />)}
</g>
) : null}
{operation === "revolve" ? (
<g className="sketch-revolve-guide" pointerEvents="none">
<rect x={0} y={-workspace.depth / 2} width={workspace.width / 2} height={workspace.depth} />
<line x1={0} y1={-workspace.depth / 2} x2={0} y2={workspace.depth / 2} />
<text x={-5 * screenUnit} y={-workspace.depth / 2 + 18 * screenUnit} fontSize={12 * screenUnit}>REVOLVE AXIS</text>
</g>
) : null}
<g className="sketch-reference-images">
@@ -1027,14 +1042,8 @@ function SketchImageInspector({
<SketchImageRange label="Width" value={image.width} min={0.5} max={200} accuracy={accuracy} onChange={updateWidth} />
<SketchImageRange label="Height" value={image.depth} min={0.5} max={200} accuracy={accuracy} onChange={updateDepth} />
<SketchImageRange label="Opacity" value={(image.opacity ?? 0.55) * 100} min={5} max={100} accuracy={1} suffix="%" onChange={(opacity) => onUpdate({ opacity: opacity / 100 }, "Sketch image opacity updated")} />
<label className="sketch-image-position-field">
<span>Position X</span>
<input type="number" step="0.1" value={Number(image.x.toFixed(accuracy))} onChange={(event) => onUpdate({ x: Number(event.currentTarget.value) || 0 }, "Sketch image moved")} />
</label>
<label className="sketch-image-position-field">
<span>Position Y</span>
<input type="number" step="0.1" value={Number(image.z.toFixed(accuracy))} onChange={(event) => onUpdate({ z: Number(event.currentTarget.value) || 0 }, "Sketch image moved")} />
</label>
<SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
<SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
<button className={`sketch-image-aspect-toggle ${image.lockAspect !== false ? "active" : ""}`} type="button" onClick={() => onUpdate({ lockAspect: image.lockAspect === false }, "Image aspect ratio setting updated")}>
{image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
@@ -1066,7 +1075,7 @@ function SketchImageRange({
const [draft, setDraft] = useState(formatDimension(safeValue, accuracy));
useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]);
const commit = () => {
const parsed = Number(draft);
const parsed = parseMeasurementInput(draft);
onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max));
};
const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100;
@@ -1076,10 +1085,8 @@ function SketchImageRange({
<div className="sketch-image-range-row">
<input
className="sketch-image-number-input"
type="number"
min={min}
max={max}
step={accuracy === 1 ? 0.1 : 0.01}
type="text"
inputMode="decimal"
value={draft}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
@@ -1091,3 +1098,39 @@ function SketchImageRange({
</label>
);
}
function SketchImagePositionField({
label,
value,
accuracy,
onChange,
}: {
label: string;
value: number;
accuracy: 1 | 2 | 3;
onChange: (value: number) => void;
}) {
const formatted = formatDimension(value, accuracy);
const [draft, setDraft] = useState(formatted);
useEffect(() => setDraft(formatted), [formatted]);
const commit = () => {
const parsed = parseMeasurementInput(draft);
const next = Number.isFinite(parsed) ? parsed : value;
onChange(next);
setDraft(formatDimension(next, accuracy));
};
return (
<label className="sketch-image-position-field">
<span>{label}</span>
<input
type="text"
inputMode="decimal"
value={draft}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
/>
</label>
);
}
+30 -7
View File
@@ -17,8 +17,10 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json
import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { createGearGeometry } from "@/lib/gearGeometry";
import { parseMeasurementInput } from "@/lib/measurementUnits";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION } from "@/lib/workplaneGrid";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import { sphereTessellation } from "@/lib/sphereTessellation";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
@@ -68,6 +70,7 @@ const SHAPE_KINDS = new Set<ShapeAsset["kind"]>([
"halfSphere",
"torus",
"tube",
"gear",
"ring",
"wedge",
"polygon",
@@ -566,6 +569,13 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string {
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
centerHoleSize: shape.centerHoleSize,
gearType: shape.gearType,
helixAngle: shape.helixAngle,
helixQuality: shape.helixQuality,
text: shape.text,
font: shape.font,
mesh: [positions.length, positionSample],
@@ -2743,7 +2753,7 @@ export function WorkplaneViewport({
setEditingDimension(null);
return;
}
const value = Number.parseFloat(edit.value);
const value = parseMeasurementInput(edit.value);
if (edit.axis === "elevation") {
if (Number.isFinite(value)) {
const frame = selectionFrameForShapes(shapesRef.current, selectedIdsRef.current);
@@ -2803,7 +2813,7 @@ export function WorkplaneViewport({
if (!edit) {
return;
}
const value = Number.parseFloat(edit.value);
const value = parseMeasurementInput(edit.value);
if (Number.isFinite(value)) {
selectedIdsRef.current.forEach((id) => onUpdateShape(id, { ...rotationPatchForAxis(edit.axis, value), bakeTransform: true }));
}
@@ -3977,14 +3987,13 @@ function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, block
points.push(...from, ...to);
};
const step = clamp(blockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
const majorEvery = 4;
for (const { coordinate: centeredX, index } of interiorWorkplaneGridCoordinates(width, step)) {
const points = centeredX === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints;
const points = centeredX === 0 ? axisPoints : index % WORKPLANE_MAJOR_GRID_INTERVAL === 0 ? majorPoints : minorPoints;
pushLine(points, [centeredX, WORKPLANE_LINE_ELEVATION, -depth / 2], [centeredX, WORKPLANE_LINE_ELEVATION, depth / 2]);
}
for (const { coordinate: centeredZ, index } of interiorWorkplaneGridCoordinates(depth, step)) {
const points = centeredZ === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints;
const points = centeredZ === 0 ? axisPoints : index % WORKPLANE_MAJOR_GRID_INTERVAL === 0 ? majorPoints : minorPoints;
pushLine(points, [-width / 2, WORKPLANE_LINE_ELEVATION, centeredZ], [width / 2, WORKPLANE_LINE_ELEVATION, centeredZ]);
}
@@ -5224,6 +5233,20 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
case "tube":
addMesh(group, createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144), material, shape);
break;
case "gear":
addMesh(group, createGearGeometry({
width,
depth,
height,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
centerHoleSize: shape.centerHoleSize,
gearType: shape.gearType,
helixAngle: shape.helixAngle,
helixQuality: shape.helixQuality,
}), material, shape);
break;
case "wedge":
addMesh(group, createWedgeGeometry(width, height, depth), material, shape);
break;
@@ -5334,7 +5357,7 @@ function addMesh(
const complexEdges =
shape.kind === "mesh" ||
Boolean(shape.importedMesh) ||
["cone", "pyramid", "roof", "roundRoof", "halfSphere", "torus", "tube", "ring", "wedge"].includes(shape.kind);
["cone", "pyramid", "roof", "roundRoof", "halfSphere", "torus", "tube", "ring", "gear", "wedge"].includes(shape.kind);
const importedTriangleCount = shape.importedMesh?.triangleCount ?? 0;
const skipHeavyImportedEdges = Boolean(shape.importedMesh) && importedTriangleCount > IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT;
if ((group.userData.showEdges || complexEdges) && !skipHeavyImportedEdges) {
@@ -2,7 +2,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 { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -71,7 +71,7 @@ function EdgeModifierSlider({
const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
onChange(clamp(toModelValue(finiteNext), safeMin, safeMax));
setEditing(false);
@@ -89,10 +89,7 @@ function EdgeModifierSlider({
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={controlMax}
step={controlStep}
type="text"
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal"
disabled={disabled}
@@ -1,11 +1,30 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen, Split } from "lucide-react";
import { useEffect, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import {
DEFAULT_GEAR_HELIX_ANGLE,
DEFAULT_GEAR_HELIX_QUALITY,
DEFAULT_GEAR_TEETH,
DEFAULT_GEAR_TOOTH_SIZE,
MAX_GEAR_HELIX_ANGLE,
MAX_GEAR_HELIX_QUALITY,
MIN_GEAR_HELIX_ANGLE,
MIN_GEAR_HELIX_QUALITY,
gearCenterHoleLimits,
normalizeGearHelixAngle,
normalizeGearHelixQuality,
normalizeGearCenterHoleSize,
normalizeGearToothSize,
normalizeGearToothWidth,
normalizeGearType,
gearToothPitch,
} from "@/lib/gearGeometry";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_SHAPE_SIZE = 0.01;
@@ -40,6 +59,11 @@ const SOLID_COLORS = [
"#111111",
];
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
const GEAR_TYPE_OPTIONS: Array<{ value: GearType; label: string }> = [
{ value: "spur", label: "Spur gear" },
{ value: "helical", label: "Helical gear" },
{ value: "bevel", label: "Bevel gear" },
];
type RangePropertyConfig = {
type?: "range";
@@ -80,7 +104,7 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step
}
function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness"].includes(label);
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
@@ -95,6 +119,20 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
};
const setHeight = (height: number) => onUpdate({ height }, { resizeAxis: "height" });
if (shape.sketchOperation === "revolve" || shape.sketchRevolve) {
const settings = normalizeSketchRevolveSettings(shape.sketchRevolve);
const updateRevolve = (patch: Partial<typeof settings>) => onUpdate({ sketchRevolve: normalizeSketchRevolveSettings({ ...settings, ...patch }) });
return [
{ label: "Start Angle", value: settings.startAngle, min: 0, max: 359, step: 1, onChange: (startAngle) => updateRevolve({ startAngle }) },
{ label: "Sweep", value: settings.sweepAngle, min: -360, max: 360, step: 1, onChange: (sweepAngle) => updateRevolve({ sweepAngle }) },
{ label: "Sides", value: settings.sides, min: 3, max: 128, step: 1, onChange: (sides) => updateRevolve({ sides }) },
{ label: "Thickness", value: settings.thickness, min: 0.1, max: 20, step: 0.1, onChange: (thickness) => updateRevolve({ thickness }) },
{ 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 },
];
}
if (shape.kind === "box") {
return [
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
@@ -168,6 +206,92 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
];
}
if (shape.kind === "gear") {
const setGearWidth = (value: number) => {
const toothSize = normalizeGearToothSize(shape.toothSize, value, depth);
const toothWidth = normalizeGearToothWidth(shape.toothWidth, value, depth, shape.teeth);
const centerHoleSize = normalizeGearCenterHoleSize(shape.centerHoleSize, value, depth, toothSize);
onUpdate({ width: value, size: resizedShapeSize(value, depth), toothSize, toothWidth, centerHoleSize }, { resizeAxis: "width" });
};
const setGearDepth = (value: number) => {
const toothSize = normalizeGearToothSize(shape.toothSize, width, value);
const toothWidth = normalizeGearToothWidth(shape.toothWidth, width, value, shape.teeth);
const centerHoleSize = normalizeGearCenterHoleSize(shape.centerHoleSize, width, value, toothSize);
onUpdate({ depth: value, size: resizedShapeSize(width, value), toothSize, toothWidth, centerHoleSize }, { resizeAxis: "depth" });
};
const teeth = shape.teeth ?? DEFAULT_GEAR_TEETH;
const toothPitch = gearToothPitch(width, depth, teeth);
const toothSize = normalizeGearToothSize(shape.toothSize ?? DEFAULT_GEAR_TOOTH_SIZE, width, depth);
const centerHoleLimits = gearCenterHoleLimits(width, depth, toothSize);
const properties: ShapePropertyConfig[] = [
{
label: "Teeth",
value: teeth,
min: 6,
max: 64,
step: 1,
onChange: (value) => {
const nextTeeth = Math.round(value);
onUpdate({
teeth: nextTeeth,
toothWidth: normalizeGearToothWidth(shape.toothWidth, width, depth, nextTeeth),
});
},
},
{
label: "Tooth Size",
value: toothSize,
min: 0.2,
max: Math.max(0.2, Math.min(width, depth) * 0.22),
step: 0.1,
onChange: (nextToothSize) => onUpdate({
toothSize: nextToothSize,
centerHoleSize: normalizeGearCenterHoleSize(shape.centerHoleSize, width, depth, nextToothSize),
}),
},
{
label: "Tooth Width",
value: normalizeGearToothWidth(shape.toothWidth, width, depth, teeth),
min: toothPitch * 0.12,
max: toothPitch * 0.82,
step: 0.1,
onChange: (toothWidth) => onUpdate({ toothWidth }),
},
];
if (normalizeGearType(shape.gearType) === "helical") {
properties.push({
label: "Helix Angle",
value: normalizeGearHelixAngle(shape.helixAngle ?? DEFAULT_GEAR_HELIX_ANGLE),
min: MIN_GEAR_HELIX_ANGLE,
max: MAX_GEAR_HELIX_ANGLE,
step: 1,
onChange: (helixAngle) => onUpdate({ helixAngle }),
});
properties.push({
label: "Quality",
value: normalizeGearHelixQuality(shape.helixQuality ?? DEFAULT_GEAR_HELIX_QUALITY),
min: MIN_GEAR_HELIX_QUALITY,
max: MAX_GEAR_HELIX_QUALITY,
step: 1,
onChange: (helixQuality) => onUpdate({ helixQuality: Math.round(helixQuality) }),
});
}
properties.push(
{
label: "Center Hole",
value: normalizeGearCenterHoleSize(shape.centerHoleSize, width, depth, toothSize),
min: centerHoleLimits.min,
max: centerHoleLimits.max,
step: 0.1,
onChange: (centerHoleSize) => onUpdate({ centerHoleSize }),
},
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setGearDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setGearWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
);
return properties;
}
if (shape.kind === "text") {
return [
{
@@ -222,14 +346,31 @@ export function ShapeInspector({
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate);
const gearType = shape.kind === "gear" ? normalizeGearType(shape.gearType) : null;
const primaryProperties = shape.kind === "gear"
? properties.filter((property) => ["Center Hole", "Length", "Width", "Height"].includes(property.label))
: properties;
const gearTeethProperties = shape.kind === "gear"
? properties.filter((property) => ["Teeth", "Tooth Size", "Tooth Width"].includes(property.label))
: [];
const gearHelixProperties = shape.kind === "gear"
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
: [];
const isSketchRevolve = shape.sketchOperation === "revolve" || Boolean(shape.sketchRevolve);
const inspectorRef = useRef<HTMLElement>(null);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [gearTeethOpen, setGearTeethOpen] = useState(true);
const [gearHelixOpen, setGearHelixOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
const [minimized, setMinimized] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
useLayoutEffect(() => {
inspectorRef.current?.scrollTo({ top: 0, left: 0 });
}, [isSketchRevolve, shape.id]);
return (
<aside className={`shape-inspector ${minimized ? "minimized" : ""}`} aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<aside ref={inspectorRef} className={`shape-inspector ${isSketchRevolve ? "sketch-revolve-inspector" : ""} ${shape.kind === "gear" ? "gear-inspector" : ""} ${minimized ? "minimized" : ""}`} aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button
className="inspector-header-icon"
@@ -334,7 +475,7 @@ export function ShapeInspector({
</button>
) : null}
<div className="property-card">
<div className={`property-card ${propertiesOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
@@ -347,18 +488,55 @@ export function ShapeInspector({
</button>
{propertiesOpen ? (
<div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => {
if (property.type === "text") {
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} onInteractionActiveChange={onInteractionActiveChange} />;
})}
{gearType ? (
<GearTypeSelector
value={gearType}
disabled={locked}
onChange={(gearType) => onUpdate({ gearType })}
/>
) : null}
<ShapePropertyRows properties={primaryProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
{shape.kind === "gear" ? (
<div className={`property-card ${gearTeethOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
aria-expanded={gearTeethOpen}
aria-controls={`gear-teeth-${shape.id}`}
onClick={() => setGearTeethOpen((open) => !open)}
>
<span>Teeth</span>
<ChevronUp className={gearTeethOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{gearTeethOpen ? (
<div className="property-list" id={`gear-teeth-${shape.id}`}>
<ShapePropertyRows properties={gearTeethProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
) : null}
{gearType === "helical" ? (
<div className={`property-card ${gearHelixOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
aria-expanded={gearHelixOpen}
aria-controls={`gear-helix-${shape.id}`}
onClick={() => setGearHelixOpen((open) => !open)}
>
<span>Helix</span>
<ChevronUp className={gearHelixOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{gearHelixOpen ? (
<div className="property-list" id={`gear-helix-${shape.id}`}>
<ShapePropertyRows properties={gearHelixProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
) : null}
<div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div>
@@ -368,6 +546,28 @@ export function ShapeInspector({
);
}
function ShapePropertyRows({
properties,
workspace,
disabled,
onInteractionActiveChange,
}: {
properties: ShapePropertyConfig[];
workspace: WorkplaneWorkspaceSettings;
disabled?: boolean;
onInteractionActiveChange?: (active: boolean) => void;
}) {
return properties.map((property) => {
if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={disabled} onInteractionActiveChange={onInteractionActiveChange} />;
}
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={disabled} />;
}
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={disabled} onInteractionActiveChange={onInteractionActiveChange} />;
});
}
export function SnapGridControl({
snap,
snapOpen,
@@ -437,7 +637,7 @@ function RangeProperty({
}, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
@@ -455,10 +655,7 @@ function RangeProperty({
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={allowsAboveSliderMax ? undefined : controlMax}
step={controlStep}
type="text"
value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)}
disabled={disabled}
inputMode="decimal"
@@ -533,3 +730,30 @@ function SelectProperty({ label, value, options, disabled, onChange }: SelectPro
</label>
);
}
function GearTypePreview({ type }: { type: GearType }) {
return <img src={`assets/sketchforge/gear-types/${type}.png`} alt="" aria-hidden="true" />;
}
function GearTypeSelector({ value, disabled, onChange }: { value: GearType; disabled?: boolean; onChange: (value: GearType) => void }) {
return (
<div className="gear-type-property" role="group" aria-label="Gear type">
<span>Gear Type</span>
<div className="gear-type-options">
{GEAR_TYPE_OPTIONS.map((option) => (
<button
key={option.value}
className={value === option.value ? "selected" : ""}
type="button"
disabled={disabled}
aria-pressed={value === option.value}
onClick={() => onChange(option.value)}
>
<GearTypePreview type={option.value} />
<span>{option.label}</span>
</button>
))}
</div>
</div>
);
}
@@ -155,6 +155,7 @@ export function TransformOverlay({
style={{ "--overlay-x": `${editingDimension.x}px`, "--overlay-y": `${editingDimension.y}px` } as CSSProperties}
value={editingDimension.value}
autoFocus
inputMode="decimal"
onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onEditingDimensionChange(event.target.value)}
onBlur={onCommitDimensionEdit}
@@ -2,7 +2,7 @@
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useEffect, useState } from "react";
import { normalizeScaleForUnits, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -56,6 +56,7 @@ export function WorkspaceSettingsModal({
width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy),
}));
const [gridBlockSizeDraft, setGridBlockSizeDraft] = useState(() => workspace.gridBlockSize.toFixed(workspace.accuracy));
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
useEffect(() => {
@@ -64,13 +65,16 @@ export function WorkspaceSettingsModal({
depth: workspace.depth.toFixed(workspace.accuracy),
});
}, [workspace.accuracy, workspace.depth, workspace.width]);
useEffect(() => {
setGridBlockSizeDraft(workspace.gridBlockSize.toFixed(workspace.accuracy));
}, [workspace.accuracy, workspace.gridBlockSize]);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
};
const setDimension = (key: "width" | "depth", value: string) => {
const parsed = Number.parseFloat(value);
const parsed = parseMeasurementInput(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
setDimensionDrafts((current) => ({ ...current, [key]: next.toFixed(workspace.accuracy) }));
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
@@ -87,7 +91,9 @@ export function WorkspaceSettingsModal({
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
};
const setGridBlockSize = (value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
const parsed = parseMeasurementInput(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
setGridBlockSizeDraft(next.toFixed(workspace.accuracy));
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
};
@@ -201,11 +207,9 @@ export function WorkspaceSettingsModal({
<label>
<span>Width</span>
<input
type="number"
type="text"
inputMode="decimal"
value={dimensionDrafts.width}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, width: value }));
@@ -219,11 +223,9 @@ export function WorkspaceSettingsModal({
<label>
<span>Length</span>
<input
type="number"
type="text"
inputMode="decimal"
value={dimensionDrafts.depth}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, depth: value }));
@@ -241,12 +243,14 @@ export function WorkspaceSettingsModal({
<label>
<span>Block size</span>
<input
type="number"
value={workspace.gridBlockSize.toFixed(workspace.accuracy)}
min={MIN_GRID_BLOCK_SIZE}
max={MAX_GRID_BLOCK_SIZE}
step={0.5}
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
type="text"
inputMode="decimal"
value={gridBlockSizeDraft}
onChange={(event) => setGridBlockSizeDraft(event.currentTarget.value)}
onBlur={(event) => setGridBlockSize(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
</div>