Add reversible edge tools and view cube fixes

This commit is contained in:
Formsmith
2026-06-28 16:06:01 +03:00
parent 7c93f627a0
commit c3ed07a32e
16 changed files with 4508 additions and 106 deletions
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+866
View File
@@ -0,0 +1,866 @@
"use client";
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 { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure";
export type SketchSelection =
| { kind: "point"; id: string }
| { kind: "segment"; id: string }
| { kind: "image"; id: string }
| { kind: "multiple"; pointIds: string[]; segmentIds: string[]; imageIds?: string[] }
| null;
export type SketchMeasurement = { start: SketchPoint; end: SketchPoint } | null;
type SketchWorkspaceProps = {
profile: SketchProfile;
referenceShapes: WorkplaneShape[];
tool: SketchTool;
activePointId: string | null;
selected: SketchSelection;
measurement: SketchMeasurement;
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void;
onPointPress: (id: string) => void;
onSelectSegment: (id: string) => void;
onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void;
onSelectImage: (id: string) => void;
onUpdateImage: (id: string, patch: Partial<SketchImage>, message?: string) => void;
onDeleteImage: (id: string) => void;
onDeletePoint: (id: string) => void;
onDeleteSegment: (id: string) => void;
onMovePoint: (id: string, point: { x: number; z: number }) => void;
onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void;
onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void;
onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void;
onClearMeasurement: () => void;
};
type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean };
type PointerAction =
| { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
| { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } }
| { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } }
| { kind: "pan"; pointerId: number; clientX: number; clientY: number }
| { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
| { kind: "move-image"; pointerId: number; imageId: string; origin: { x: number; z: number }; current: { x: number; z: number }; start: SketchImage }
| { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage };
type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
function snapStep(size: GridSize) {
if (size === "Off") return 0;
if (size === "Brick") return 8;
return Number.parseFloat(size) || 1;
}
function snapValue(value: number, step: number) {
return step > 0 ? Math.round(value / step) * step : value;
}
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x: number; z: number }): Partial<SketchImage> {
const minimum = 0.5;
const startsWest = handle.includes("w");
const startsEast = handle.includes("e");
const startsNorth = handle.includes("n");
const startsSouth = handle.includes("s");
const minX = start.x - start.width / 2;
const maxX = start.x + start.width / 2;
const minZ = start.z - start.depth / 2;
const maxZ = start.z + start.depth / 2;
const aspect = start.width / Math.max(minimum, start.depth);
if (start.lockAspect !== false) {
if ((startsWest || startsEast) && (startsNorth || startsSouth)) {
const fixedX = startsWest ? maxX : minX;
const fixedZ = startsNorth ? maxZ : minZ;
const widthScale = Math.abs(point.x - fixedX) / Math.max(minimum, start.width);
const depthScale = Math.abs(point.z - fixedZ) / Math.max(minimum, start.depth);
const scale = Math.max(minimum / Math.min(start.width, start.depth), widthScale, depthScale);
const width = Math.max(minimum, start.width * scale);
const depth = Math.max(minimum, start.depth * scale);
const xDirection = startsWest ? -1 : 1;
const zDirection = startsNorth ? -1 : 1;
return { width, depth, x: fixedX + xDirection * width / 2, z: fixedZ + zDirection * depth / 2 };
}
if (startsWest || startsEast) {
const fixedX = startsWest ? maxX : minX;
const width = Math.max(minimum, Math.abs(point.x - fixedX));
return { width, depth: Math.max(minimum, width / aspect), x: fixedX + (startsWest ? -1 : 1) * width / 2 };
}
const fixedZ = startsNorth ? maxZ : minZ;
const depth = Math.max(minimum, Math.abs(point.z - fixedZ));
return { depth, width: Math.max(minimum, depth * aspect), z: fixedZ + (startsNorth ? -1 : 1) * depth / 2 };
}
let nextMinX = minX;
let nextMaxX = maxX;
let nextMinZ = minZ;
let nextMaxZ = maxZ;
if (startsWest) nextMinX = Math.min(point.x, maxX - minimum);
if (startsEast) nextMaxX = Math.max(point.x, minX + minimum);
if (startsNorth) nextMinZ = Math.min(point.z, maxZ - minimum);
if (startsSouth) nextMaxZ = Math.max(point.z, minZ + minimum);
return {
x: (nextMinX + nextMaxX) / 2,
z: (nextMinZ + nextMaxZ) / 2,
width: nextMaxX - nextMinX,
depth: nextMaxZ - nextMinZ,
};
}
function formatDimension(value: number, accuracy: 1 | 2 | 3) {
const threshold = 0.5 * 10 ** -accuracy;
return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy);
}
function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) {
const inverse = 1 - amount;
return {
x: inverse ** 3 * start.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * end.x,
z: inverse ** 3 * start.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * end.z,
};
}
function segmentDimension(segment: SketchSegment, pointById: Map<string, SketchPoint>) {
const start = pointById.get(segment.startId);
const end = pointById.get(segment.endId);
if (!start || !end) return null;
const first = start.handleOut;
const second = end.handleIn;
if (segment.kind === "line" || !first || !second) {
return {
length: Math.hypot(end.x - start.x, end.z - start.z),
midpoint: { x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 },
};
}
let length = 0;
let previous = start;
for (let index = 1; index <= 32; index += 1) {
const point = cubicPoint(start, first, second, end, index / 32);
length += Math.hypot(point.x - previous.x, point.z - previous.z);
previous = { ...point, id: "curve-sample" };
}
return { length, midpoint: cubicPoint(start, first, second, end, 0.5) };
}
function orderedPaths(profile: SketchProfile): DisplayPath[] {
const pointById = new Map(profile.points.map((point) => [point.id, point]));
const adjacency = new Map<string, Array<{ pointId: string; segment: SketchSegment }>>();
profile.points.forEach((point) => adjacency.set(point.id, []));
const valid = profile.segments.filter((segment) => {
if (!pointById.has(segment.startId) || !pointById.has(segment.endId)) return false;
adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment });
adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment });
return true;
});
const unvisited = new Set(valid.map((segment) => segment.id));
const paths: DisplayPath[] = [];
while (unvisited.size > 0) {
const seedId = unvisited.values().next().value as string;
const seed = valid.find((segment) => segment.id === seedId);
if (!seed) break;
const component = new Set<string>();
const queue = [seed.startId, seed.endId];
while (queue.length) {
const id = queue.pop();
if (!id || component.has(id)) continue;
component.add(id);
adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId));
}
const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId;
const first = pointById.get(startId);
if (!first) break;
const points = [first];
const steps: PathStep[] = [];
let currentId = startId;
for (let guard = 0; guard <= valid.length; guard += 1) {
const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id));
if (!edge) break;
const from = pointById.get(currentId);
const to = pointById.get(edge.pointId);
if (!from || !to) break;
unvisited.delete(edge.segment.id);
steps.push({ segment: edge.segment, from, to });
currentId = to.id;
if (currentId === startId) break;
points.push(to);
}
paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 });
}
return paths;
}
function curveControls(step: PathStep) {
const forward = step.segment.startId === step.from.id;
return {
first: forward ? step.from.handleOut : step.from.handleIn,
second: forward ? step.to.handleIn : step.to.handleOut,
};
}
function pathData(path: DisplayPath) {
const first = path.points[0];
if (!first) return "";
const commands = [`M ${first.x} ${first.z}`];
path.steps.forEach((step) => {
const controls = curveControls(step);
if (step.segment.kind !== "line" && controls.first && controls.second) {
commands.push(`C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${step.to.x} ${step.to.z}`);
} else {
commands.push(`L ${step.to.x} ${step.to.z}`);
}
});
if (path.closed) commands.push("Z");
return commands.join(" ");
}
function segmentData(segment: SketchSegment, pointById: Map<string, SketchPoint>) {
const from = pointById.get(segment.startId);
const to = pointById.get(segment.endId);
if (!from || !to) return "";
const step = { segment, from, to };
const controls = curveControls(step);
return segment.kind !== "line" && controls.first && controls.second
? `M ${from.x} ${from.z} C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${to.x} ${to.z}`
: `M ${from.x} ${from.z} L ${to.x} ${to.z}`;
}
function isRoundReference(shape: WorkplaneShape) {
return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind);
}
export function SketchWorkspace({
profile,
referenceShapes,
tool,
activePointId,
selected,
measurement,
initialSnap,
initialWorkspace,
onPlanePoint,
onPointPress,
onSelectSegment,
onSelectMany,
onSelectImage,
onUpdateImage,
onDeleteImage,
onDeletePoint,
onDeleteSegment,
onMovePoint,
onMoveHandle,
onInsertPoint,
onSetPointMode,
onClearMeasurement,
}: SketchWorkspaceProps) {
const workspace = useMemo(() => normalizeWorkspaceSettings(initialWorkspace, DEFAULT_WORKPLANE_WORKSPACE), [initialWorkspace]);
const [snap, setSnap] = useState<GridSize>(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID));
const [snapOpen, setSnapOpen] = useState(false);
const [zoom, setZoom] = useState(1);
const [pan, setPan] = useState({ x: 0, z: 0 });
const [hover, setHover] = useState<{ x: number; z: number } | null>(null);
const [pointerAction, setPointerAction] = useState<PointerAction | null>(null);
const svgRef = useRef<SVGSVGElement | null>(null);
const width = workspace.width / zoom;
const depth = workspace.depth / zoom;
const displayProfile = useMemo(() => {
if (pointerAction?.kind === "move-point") {
const source = profile.points.find((point) => point.id === pointerAction.pointId);
if (!source) return profile;
const deltaX = pointerAction.current.x - source.x;
const deltaZ = pointerAction.current.z - source.z;
return {
...profile,
points: profile.points.map((point) => point.id === source.id ? {
...point,
...pointerAction.current,
handleIn: point.handleIn ? { x: point.handleIn.x + deltaX, z: point.handleIn.z + deltaZ } : undefined,
handleOut: point.handleOut ? { x: point.handleOut.x + deltaX, z: point.handleOut.z + deltaZ } : undefined,
} : point),
};
}
if (pointerAction?.kind === "move-handle") {
return {
...profile,
points: profile.points.map((point) => {
if (point.id !== pointerAction.pointId) return point;
const next = { ...point, handleIn: point.handleIn ? { ...point.handleIn } : undefined, handleOut: point.handleOut ? { ...point.handleOut } : undefined };
if (pointerAction.handle === "in") next.handleIn = { ...pointerAction.current };
else next.handleOut = { ...pointerAction.current };
if (point.mode === "smooth") {
const opposite = { x: point.x * 2 - pointerAction.current.x, z: point.z * 2 - pointerAction.current.z };
if (pointerAction.handle === "in") next.handleOut = opposite;
else next.handleIn = opposite;
}
return next;
}),
};
}
return profile;
}, [pointerAction, profile]);
const displayImages = useMemo(() => {
const images = profile.images ?? [];
if (pointerAction?.kind === "move-image") {
const deltaX = pointerAction.current.x - pointerAction.origin.x;
const deltaZ = pointerAction.current.z - pointerAction.origin.z;
return images.map((image) => image.id === pointerAction.imageId ? { ...image, x: pointerAction.start.x + deltaX, z: pointerAction.start.z + deltaZ } : image);
}
if (pointerAction?.kind === "resize-image") {
return images.map((image) => image.id === pointerAction.imageId ? { ...image, ...resizeSketchImage(pointerAction.start, pointerAction.handle, pointerAction.current) } : image);
}
return images;
}, [pointerAction, profile.images]);
const pointById = useMemo(() => new Map(displayProfile.points.map((point) => [point.id, point])), [displayProfile.points]);
const paths = useMemo(() => orderedPaths(displayProfile), [displayProfile]);
const activePoint = activePointId ? pointById.get(activePointId) ?? null : null;
const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null;
const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null;
const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false;
const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false;
const gridStep = clamp(workspace.gridBlockSize, 1, 200);
const verticalLines = useMemo(() => {
const lines: number[] = [];
const start = Math.ceil((-workspace.width / 2) / gridStep) * gridStep;
for (let x = start; x <= workspace.width / 2 + 0.0001; x += gridStep) lines.push(Number(x.toFixed(6)));
return lines;
}, [gridStep, workspace.width]);
const horizontalLines = useMemo(() => {
const lines: number[] = [];
const start = Math.ceil((-workspace.depth / 2) / gridStep) * gridStep;
for (let z = start; z <= workspace.depth / 2 + 0.0001; z += gridStep) lines.push(Number(z.toFixed(6)));
return lines;
}, [gridStep, workspace.depth]);
const pointFromEvent = (event: { clientX: number; clientY: number }) => {
const svg = svgRef.current;
const matrix = svg?.getScreenCTM();
if (!svg || !matrix) return null;
const screenPoint = svg.createSVGPoint();
screenPoint.x = event.clientX;
screenPoint.y = event.clientY;
const local = screenPoint.matrixTransform(matrix.inverse());
const step = snapStep(snap);
return {
x: clamp(snapValue(local.x, step), -workspace.width / 2, workspace.width / 2),
z: clamp(snapValue(local.y, step), -workspace.depth / 2, workspace.depth / 2),
};
};
const beginPan = (event: ReactPointerEvent<SVGElement>) => {
event.preventDefault();
event.stopPropagation();
svgRef.current?.setPointerCapture(event.pointerId);
setPointerAction({ kind: "pan", pointerId: event.pointerId, clientX: event.clientX, clientY: event.clientY });
};
const handlePlanePointerDown = (event: ReactPointerEvent<SVGSVGElement>) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || (event.target !== event.currentTarget && (event.target as Element).closest("[data-sketch-entity]"))) return;
const point = pointFromEvent(event);
if (!point) return;
event.preventDefault();
if (tool === "bezier") {
event.currentTarget.setPointerCapture(event.pointerId);
setPointerAction({ kind: "bezier", pointerId: event.pointerId, origin: point, current: point });
} else if (tool === "select") {
event.currentTarget.setPointerCapture(event.pointerId);
setPointerAction({ kind: "marquee", pointerId: event.pointerId, origin: point, current: point });
} else if (tool === "line" || tool === "smooth" || tool === "measure") {
onPlanePoint(point);
}
};
const handlePointerMove = (event: ReactPointerEvent<SVGSVGElement>) => {
if (pointerAction?.kind === "pan") {
const matrix = svgRef.current?.getScreenCTM();
const scaleX = matrix ? Math.max(0.0001, Math.hypot(matrix.a, matrix.b)) : 1;
const scaleY = matrix ? Math.max(0.0001, Math.hypot(matrix.c, matrix.d)) : 1;
const deltaX = event.clientX - pointerAction.clientX;
const deltaY = event.clientY - pointerAction.clientY;
setPan((current) => ({
x: clamp(current.x - deltaX / scaleX, -workspace.width / 2, workspace.width / 2),
z: clamp(current.z - deltaY / scaleY, -workspace.depth / 2, workspace.depth / 2),
}));
setPointerAction({ ...pointerAction, clientX: event.clientX, clientY: event.clientY });
return;
}
const point = pointFromEvent(event);
setHover(point);
if (point && pointerAction) setPointerAction({ ...pointerAction, current: point });
};
const finishPointerAction = (event: ReactPointerEvent<SVGSVGElement>) => {
const action = pointerAction;
if (!action || action.pointerId !== event.pointerId) return;
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
if (action.kind === "pan") {
setPointerAction(null);
return;
}
if (action.kind === "marquee") {
const minX = Math.min(action.origin.x, action.current.x);
const maxX = Math.max(action.origin.x, action.current.x);
const minZ = Math.min(action.origin.z, action.current.z);
const maxZ = Math.max(action.origin.z, action.current.z);
const contains = (point: { x: number; z: number }) => point.x >= minX && point.x <= maxX && point.z >= minZ && point.z <= maxZ;
const pointIds = profile.points.filter(contains).map((point) => point.id);
const segmentIds = profile.segments.filter((segment) => {
const start = pointById.get(segment.startId);
const end = pointById.get(segment.endId);
return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 })));
}).map((segment) => segment.id);
const imageIds = (profile.images ?? []).filter((image) => {
const imageMinX = image.x - image.width / 2;
const imageMaxX = image.x + image.width / 2;
const imageMinZ = image.z - image.depth / 2;
const imageMaxZ = image.z + image.depth / 2;
return imageMaxX >= minX && imageMinX <= maxX && imageMaxZ >= minZ && imageMinZ <= maxZ;
}).map((image) => image.id);
onSelectMany(pointIds, segmentIds, imageIds);
setPointerAction(null);
return;
}
if (action.kind === "bezier") {
const dx = action.current.x - action.origin.x;
const dz = action.current.z - action.origin.z;
onPlanePoint(action.origin, {
handleIn: { x: action.origin.x - dx, z: action.origin.z - dz },
handleOut: { x: action.origin.x + dx, z: action.origin.z + dz },
});
} else if (action.kind === "move-point") {
onMovePoint(action.pointId, action.current);
} else if (action.kind === "move-handle") {
onMoveHandle(action.pointId, action.handle, action.current);
} else if (action.kind === "move-image") {
onUpdateImage(action.imageId, {
x: action.start.x + action.current.x - action.origin.x,
z: action.start.z + action.current.z - action.origin.z,
}, "Sketch image moved");
} else if (action.kind === "resize-image") {
onUpdateImage(action.imageId, resizeSketchImage(action.start, action.handle, action.current), "Sketch image resized");
}
setPointerAction(null);
};
const handleWheel = (event: ReactWheelEvent<SVGSVGElement>) => {
event.preventDefault();
setZoom((current) => clamp(current * (event.deltaY > 0 ? 0.88 : 1.14), 0.75, 6));
};
const beginEntityDrag = (event: ReactPointerEvent<SVGElement>, action: PointerAction) => {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
svgRef.current?.setPointerCapture(event.pointerId);
setPointerAction(action);
};
const measurementLength = measurement ? Math.hypot(measurement.end.x - measurement.start.x, measurement.end.z - measurement.start.z) : 0;
const measurementLabel = formatDimension(measurementLength, workspace.accuracy);
const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0;
const previewLabel = formatDimension(previewLength, workspace.accuracy);
const pillScale = 1 / zoom;
const selectedImageBounds = selectedImage ? {
minX: selectedImage.x - selectedImage.width / 2,
maxX: selectedImage.x + selectedImage.width / 2,
minZ: selectedImage.z - selectedImage.depth / 2,
maxZ: selectedImage.z + selectedImage.depth / 2,
} : null;
const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds ? [
{ id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ },
{ id: "n", x: selectedImage.x, z: selectedImageBounds.minZ },
{ id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ },
{ id: "e", x: selectedImageBounds.maxX, z: selectedImage.z },
{ id: "se", x: selectedImageBounds.maxX, z: selectedImageBounds.maxZ },
{ id: "s", x: selectedImage.x, z: selectedImageBounds.maxZ },
{ id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ },
{ id: "w", x: selectedImageBounds.minX, z: selectedImage.z },
] : [];
return (
<main className="sketch-workspace-stage">
<div className="sketch-mode-badge">Sketch view</div>
<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>
<button aria-label="Zoom out" onClick={() => setZoom((value) => clamp(value / 1.25, 0.75, 6))}><Minus size={33} /></button>
</div>
<section className="sketch-plate-wrap" aria-label="2D sketch plate">
<svg
ref={svgRef}
className={`sketch-plate tool-${tool} ${pointerAction?.kind === "pan" ? "panning" : ""}`}
viewBox={`${pan.x - width / 2} ${pan.z - depth / 2} ${width} ${depth}`}
preserveAspectRatio="xMidYMid meet"
onPointerDown={handlePlanePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={finishPointerAction}
onPointerCancel={() => setPointerAction(null)}
onPointerLeave={() => !pointerAction && setHover(null)}
onWheel={handleWheel}
>
<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} />)}
</g>
) : null}
<g className="sketch-reference-images">
{displayImages.map((image) => (
<image
key={image.id}
data-sketch-entity="image"
aria-label={image.name}
href={image.dataUrl}
x={image.x - image.width / 2}
y={image.z - image.depth / 2}
width={image.width}
height={image.depth}
opacity={image.opacity ?? 0.55}
preserveAspectRatio="none"
pointerEvents={tool === "select" ? "auto" : "none"}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || tool !== "select") return;
const point = pointFromEvent(event);
if (!point) return;
onSelectImage(image.id);
beginEntityDrag(event, {
kind: "move-image",
pointerId: event.pointerId,
imageId: image.id,
origin: point,
current: point,
start: { ...image },
});
}}
/>
))}
</g>
<g className="sketch-reference-shapes" pointerEvents="none">
{referenceShapes.filter((shape) => !shape.hidden).map((shape) => (
<g key={shape.id} transform={`rotate(${shape.rotation ?? 0} ${shape.x} ${shape.z})`}>
{isRoundReference(shape) ? (
<ellipse cx={shape.x} cy={shape.z} rx={shape.width / 2} ry={shape.depth / 2} />
) : (
<rect x={shape.x - shape.width / 2} y={shape.z - shape.depth / 2} width={shape.width} height={shape.depth} />
)}
</g>
))}
</g>
<rect className="sketch-plate-border" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} pointerEvents="none" />
{pointerAction?.kind === "marquee" ? (
<rect
className="sketch-selection-marquee"
x={Math.min(pointerAction.origin.x, pointerAction.current.x)}
y={Math.min(pointerAction.origin.z, pointerAction.current.z)}
width={Math.abs(pointerAction.current.x - pointerAction.origin.x)}
height={Math.abs(pointerAction.current.z - pointerAction.origin.z)}
pointerEvents="none"
/>
) : null}
<g className="sketch-profile-fills" pointerEvents="none">
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
</g>
<g className="sketch-segments">
{displayProfile.segments.map((segment) => (
<path
data-sketch-entity="segment"
className={isSegmentSelected(segment.id) ? "selected" : ""}
key={segment.id}
d={segmentData(segment, pointById)}
onPointerDown={(event) => {
const point = pointFromEvent(event);
event.preventDefault();
event.stopPropagation();
if (event.button === 1) beginPan(event);
else if (tool === "erase") onDeleteSegment(segment.id);
else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point);
else if (event.button === 0) onSelectSegment(segment.id);
}}
/>
))}
</g>
<g className="sketch-segment-dimensions" pointerEvents="none">
{displayProfile.segments.map((segment) => {
const dimension = segmentDimension(segment, pointById);
if (!dimension) return null;
const label = formatDimension(dimension.length, workspace.accuracy);
const pillWidth = Math.max(7.2, label.length * 1.2 + 2.4) * pillScale;
const pillHeight = 4.2 * pillScale;
return (
<g key={`dimension-${segment.id}`} transform={`translate(${dimension.midpoint.x} ${dimension.midpoint.z - 4 * pillScale})`}>
<rect x={-pillWidth / 2} y={-pillHeight / 2} width={pillWidth} height={pillHeight} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{label}</text>
</g>
);
})}
</g>
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? <line className="sketch-preview-line" x1={activePoint.x} y1={activePoint.z} x2={hover.x} y2={hover.z} pointerEvents="none" /> : null}
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? (
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - 4 * pillScale})`}>
<rect x={-(Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{previewLabel}</text>
</g>
) : null}
{pointerAction?.kind === "bezier" ? (
<g className="sketch-drag-handles" pointerEvents="none">
<line x1={pointerAction.origin.x * 2 - pointerAction.current.x} y1={pointerAction.origin.z * 2 - pointerAction.current.z} x2={pointerAction.current.x} y2={pointerAction.current.z} />
<circle cx={pointerAction.origin.x} cy={pointerAction.origin.z} r={1.2 / Math.sqrt(zoom)} />
</g>
) : null}
{measurement ? (
<g className="sketch-measurement">
<line x1={measurement.start.x} y1={measurement.start.z} x2={measurement.end.x} y2={measurement.end.z} />
<g
className="sketch-measurement-pill"
role="button"
aria-label="Remove measurement"
transform={`translate(${(measurement.start.x + measurement.end.x) / 2} ${(measurement.start.z + measurement.end.z) / 2 - 4 * pillScale})`}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
onClearMeasurement();
}}
>
<rect x={-(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text x={-0.9 * pillScale} y={0.78 * pillScale} fontSize={2.25 * pillScale}>{measurementLabel}</text>
<text className="remove" x={(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2 - 1.45 * pillScale} y={0.82 * pillScale} fontSize={2.45 * pillScale}>×</text>
</g>
</g>
) : null}
{selectedPoint && tool === "select" ? (
<g className="sketch-curve-handles">
{selectedPoint.handleIn ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleIn.x} y2={selectedPoint.handleIn.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleIn.x} cy={selectedPoint.handleIn.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /></> : null}
{selectedPoint.handleOut ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleOut.x} y2={selectedPoint.handleOut.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleOut.x} cy={selectedPoint.handleOut.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /></> : null}
</g>
) : null}
<g className="sketch-points">
{displayProfile.points.map((point) => (
<circle
data-sketch-entity="point"
className={`${isPointSelected(point.id) ? "selected" : ""} ${activePointId === point.id ? "active" : ""}`}
key={point.id}
cx={point.x}
cy={point.z}
r={0.82 / Math.sqrt(zoom)}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
if (event.button === 1) {
beginPan(event);
} else if (tool === "erase" || tool === "refine") {
onDeletePoint(point.id);
} else if (event.button === 0 && tool === "select") {
onPointPress(point.id);
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
} else if (event.button === 0) {
onPointPress(point.id);
}
}}
/>
))}
</g>
{selectedImage && selectedImageBounds && tool === "select" ? (
<g className="sketch-image-selection">
<rect
className="sketch-image-selection-box"
x={selectedImageBounds.minX}
y={selectedImageBounds.minZ}
width={selectedImage.width}
height={selectedImage.depth}
pointerEvents="none"
/>
<g className="sketch-image-dimension width" pointerEvents="none" transform={`translate(${selectedImage.x} ${selectedImageBounds.minZ - 4 * pillScale})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.width, workspace.accuracy)}</text>
</g>
<g className="sketch-image-dimension depth" pointerEvents="none" transform={`translate(${selectedImageBounds.maxX + 7 * pillScale} ${selectedImage.z})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.depth, workspace.accuracy)}</text>
</g>
{imageResizeHandles.map((handle) => (
<rect
key={handle.id}
data-sketch-entity="image-handle"
className={`sketch-image-resize-handle handle-${handle.id}`}
x={handle.x - 1.05 * pillScale}
y={handle.z - 1.05 * pillScale}
width={2.1 * pillScale}
height={2.1 * pillScale}
rx={0.2 * pillScale}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0) return;
const point = pointFromEvent(event);
if (!point) return;
beginEntityDrag(event, {
kind: "resize-image",
pointerId: event.pointerId,
imageId: selectedImage.id,
handle: handle.id,
current: point,
start: { ...selectedImage },
});
}}
/>
))}
</g>
) : null}
{hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? <circle className="sketch-cursor-point" cx={hover.x} cy={hover.z} r={0.7 / Math.sqrt(zoom)} pointerEvents="none" /> : null}
</svg>
</section>
{selectedImage && tool === "select" ? (
<SketchImageInspector
image={selectedImage}
accuracy={workspace.accuracy}
onClose={() => onSelectMany([], [], [])}
onUpdate={(patch, message) => onUpdateImage(selectedImage.id, patch, message)}
onDelete={() => onDeleteImage(selectedImage.id)}
/>
) : null}
{selectedPoint && tool === "select" ? (
<div className="sketch-point-actions" aria-label="Point actions">
<button type="button" title="Make corner" onClick={() => onSetPointMode(selectedPoint.id, "corner")}><CornerDownRight /><span>Corner</span></button>
<button type="button" title="Make smooth" onClick={() => onSetPointMode(selectedPoint.id, "smooth")}><Waves /><span>Smooth</span></button>
<button type="button" title="Split handles" onClick={() => onSetPointMode(selectedPoint.id, "split")}><Split /><span>Split</span></button>
</div>
) : null}
<div className="grid-settings sketch-grid-settings">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={setSnap} onSnapOpenChange={setSnapOpen} />
</div>
</main>
);
}
function SketchImageInspector({
image,
accuracy,
onClose,
onUpdate,
onDelete,
}: {
image: SketchImage;
accuracy: 1 | 2 | 3;
onClose: () => void;
onUpdate: (patch: Partial<SketchImage>, message?: string) => void;
onDelete: () => void;
}) {
const aspect = image.width / Math.max(0.5, image.depth);
const updateWidth = (width: number) => onUpdate({
width,
...(image.lockAspect !== false ? { depth: Math.max(0.5, width / aspect) } : {}),
}, "Sketch image width updated");
const updateDepth = (depth: number) => onUpdate({
depth,
...(image.lockAspect !== false ? { width: Math.max(0.5, depth * aspect) } : {}),
}, "Sketch image height updated");
return (
<aside className="shape-inspector sketch-image-inspector" aria-label={`${image.name} image settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button className="inspector-header-icon" type="button" aria-label="Close image settings" onClick={onClose}>
<ChevronUp size={26} strokeWidth={2.8} />
</button>
<strong>{image.name}</strong>
<div className="inspector-header-actions">
<button className="inspector-header-icon danger" type="button" aria-label="Delete sketch image" title="Delete image" onClick={onDelete}>
<Trash2 size={25} strokeWidth={2.2} />
</button>
</div>
</div>
<div className="sketch-image-preview-card">
<img src={image.dataUrl} alt="" />
<span>{image.pixelWidth} × {image.pixelHeight} px</span>
</div>
<div className="property-card">
<div className="property-card-header static"><span>Properties</span></div>
<div className="property-list">
<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>
<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>
</button>
</div>
</div>
</aside>
);
}
function SketchImageRange({
label,
value,
min,
max,
accuracy,
suffix = "mm",
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
accuracy: 1 | 2 | 3;
suffix?: string;
onChange: (value: number) => void;
}) {
const safeValue = clamp(Number.isFinite(value) ? value : min, min, max);
const [draft, setDraft] = useState(formatDimension(safeValue, accuracy));
useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]);
const commit = () => {
const parsed = Number(draft);
onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max));
};
const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100;
return (
<label className="range-property sketch-image-range" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span>{label}</span>
<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}
value={draft}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); }}
/>
<span>{suffix}</span>
</div>
<input type="range" min={min} max={max} step={accuracy === 1 ? 0.1 : 0.01} value={safeValue} onChange={(event) => onChange(Number(event.currentTarget.value))} />
</label>
);
}
+190 -27
View File
@@ -18,7 +18,7 @@ import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlay
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, proportionalResizeScale, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import {
TransformOverlay,
getElevationMeasureKey,
@@ -35,6 +35,7 @@ import {
type TransformOverlayState,
} from "@/components/workplane/TransformOverlay";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, MeasurementAccuracy, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { CadModifierEdge } from "@/lib/cadModifierTypes";
const WORKPLANE_WIDTH = 200;
const WORKPLANE_DEPTH = 140;
@@ -84,8 +85,10 @@ const importedGeometryCache = new WeakMap<
NonNullable<WorkplaneShape["importedMesh"]>,
{ geometry: THREE.BufferGeometry; edges: Map<number, THREE.EdgesGeometry> }
>();
const preservedImportedGeometryCache = new WeakMap<WorkplaneShape, THREE.BufferGeometry>();
const imageTextureLoader = new THREE.TextureLoader();
const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000;
const NORMAL_IMPORTED_SELECTION_EDGE_ANGLE = 60;
function parseDroppedShapeAsset(raw: string): ShapeAsset | null {
try {
@@ -142,12 +145,19 @@ type WorkplaneViewportProps = {
onSelectShape: (id: string | string[] | null, mode?: "replace" | "toggle") => void;
onSetPlacementElevation: (elevation: number, source: "shape" | "base") => void;
onInteractionActiveChange?: (active: boolean) => void;
onEditSketch?: () => void;
onUpdateShape: (id: string, patch: ShapeUpdatePatch) => void;
onWorkspaceSettingsChange?: (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
onWorkplaneModeChange: (active: boolean) => void;
modifierActive?: boolean;
modifierPreviewActive?: boolean;
modifierEdges?: CadModifierEdge[];
selectedModifierEdgeIds?: number[];
onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void;
};
type WorkspaceSettings = WorkplaneWorkspaceSettings;
type ViewCubeFace = "top" | "bottom" | "front" | "back" | "right" | "left";
function readSavedWorkspaceDefault(key: string | null) {
if (!key || typeof window === "undefined") {
@@ -178,6 +188,7 @@ type ThreeState = {
workplaneLayer: THREE.Group;
shapeLayer: THREE.Group;
helperLayer: THREE.Group;
modifierLayer: THREE.Group;
raycaster: THREE.Raycaster;
pointer: THREE.Vector2;
dragPlane: THREE.Plane;
@@ -1100,9 +1111,15 @@ export function WorkplaneViewport({
onSelectShape,
onSetPlacementElevation,
onInteractionActiveChange,
onEditSketch,
onUpdateShape,
onWorkspaceSettingsChange,
onWorkplaneModeChange,
modifierActive = false,
modifierPreviewActive = false,
modifierEdges = [],
selectedModifierEdgeIds = [],
onModifierEdgeToggle,
}: WorkplaneViewportProps) {
const [snapOpen, setSnapOpen] = useState(false);
const [snap, setSnap] = useState<GridSize>(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID));
@@ -1151,6 +1168,8 @@ export function WorkplaneViewport({
const alignAnchorIdRef = useRef(alignAnchorId);
const alignHandlesRef = useRef(alignHandles);
const mirrorModeRef = useRef(mirrorMode);
const modifierActiveRef = useRef(modifierActive);
const modifierPreviewActiveRef = useRef(modifierPreviewActive);
const selectedIdsKeyRef = useRef(selectedIds.join("|"));
const perfRef = useRef({
fps: 0,
@@ -1161,6 +1180,14 @@ export function WorkplaneViewport({
});
const selectedShape = useMemo(() => (selectedIds.length === 1 ? shapes.find((shape) => shape.id === selectedIds[0]) ?? null : null), [selectedIds, shapes]);
const renderSelectionIds = useCallback(
(ids = selectedIdsRef.current) => (modifierActiveRef.current && !modifierPreviewActiveRef.current ? [] : ids),
[],
);
useEffect(() => {
rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive);
}, [modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]);
const placementElevationRef = useRef(placementElevation);
const workplaneModeRef = useRef(workplaneMode);
@@ -1231,7 +1258,7 @@ export function WorkplaneViewport({
useEffect(() => {
shapesRef.current = shapes;
rebuildShapes(threeRef.current, shapes, selectedIdsRef.current, !transformRef.current && !dragRef.current);
rebuildShapes(threeRef.current, shapes, renderSelectionIds(), !transformRef.current && !dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
@@ -1278,7 +1305,7 @@ export function WorkplaneViewport({
setActiveTransformKind(null);
}
selectedIdsRef.current = selectedIds;
rebuildShapes(threeRef.current, shapesRef.current, selectedIds, !transformRef.current && !dragRef.current);
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), !transformRef.current && !dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
@@ -1295,6 +1322,18 @@ export function WorkplaneViewport({
}
}, [selectedIds]);
useEffect(() => {
modifierActiveRef.current = modifierActive;
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current);
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierActive, renderSelectionIds]);
useEffect(() => {
modifierPreviewActiveRef.current = modifierPreviewActive;
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current);
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierPreviewActive, renderSelectionIds]);
useEffect(() => {
alignModeRef.current = alignMode;
alignAnchorIdRef.current = alignAnchorId;
@@ -1374,7 +1413,7 @@ export function WorkplaneViewport({
};
perfRef.current.lastSample = performance.now();
resetCamera(state);
rebuildShapes(state, shapesRef.current, selectedIdsRef.current);
rebuildShapes(state, shapesRef.current, renderSelectionIds());
const animate = () => {
state.animationId = window.requestAnimationFrame(animate);
@@ -1438,6 +1477,7 @@ export function WorkplaneViewport({
disposeChildren(state.workplaneLayer);
disposeChildren(state.shapeLayer);
disposeChildren(state.helperLayer);
disposeChildren(state.modifierLayer);
state.renderer.dispose();
host.replaceChildren();
if (window.sketchforgeCaptureCanvas) {
@@ -1695,6 +1735,9 @@ export function WorkplaneViewport({
const beginTransform = useCallback(
(kind: TransformHandleKind, handleKey: string, event: ReactPointerEvent<Element>) => {
if (kind === "rotate" && event.button !== 0) {
return;
}
const ids = selectedIdsRef.current;
const frame = selectionFrameForShapes(shapesRef.current, ids);
const shape = frame?.singleShape ?? shapesRef.current.find((entry) => entry.id === ids[0]);
@@ -2153,6 +2196,19 @@ export function WorkplaneViewport({
return nearestId;
}, []);
const pickModifierEdge = useCallback((clientX: number, clientY: number) => {
const state = threeRef.current;
if (!state) return null;
const rect = state.renderer.domElement.getBoundingClientRect();
state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
state.raycaster.setFromCamera(state.pointer, state.camera);
const hit = state.raycaster
.intersectObjects(state.modifierLayer.children, true)
.find((entry) => typeof entry.object.userData.modifierEdgeId === "number");
return hit ? hit.object.userData.modifierEdgeId as number : null;
}, []);
const pickTransformHandle = useCallback((clientX: number, clientY: number) => {
const state = threeRef.current;
if (!state || selectedIdsRef.current.length !== 1) {
@@ -2189,6 +2245,13 @@ export function WorkplaneViewport({
}
const rect = state.renderer.domElement.getBoundingClientRect();
if (modifierActive) {
event.preventDefault();
const edgeId = pickModifierEdge(event.clientX, event.clientY);
if (edgeId !== null) onModifierEdgeToggle?.(edgeId, event.shiftKey);
return;
}
if (rulerModeRef.current) {
event.preventDefault();
const candidate = resolveRulerCandidate(event.clientX, event.clientY);
@@ -2413,11 +2476,14 @@ export function WorkplaneViewport({
onInteractionActiveChange?.(true);
},
[
modifierActive,
onAlignAnchorChange,
onInteractionActiveChange,
onModifierEdgeToggle,
onSelectShape,
onSetPlacementElevation,
onWorkplaneModeChange,
pickModifierEdge,
pickShape,
pickTransformHandle,
resolveRulerCandidate,
@@ -2640,6 +2706,15 @@ export function WorkplaneViewport({
}
}, []);
const setViewCubeFace = useCallback((face: ViewCubeFace) => {
const state = threeRef.current;
if (!state) {
return;
}
setCameraToViewFace(state, face);
syncViewCube(state, viewCubeRef.current);
}, []);
const zoomCamera = useCallback((scale: number) => {
const state = threeRef.current;
if (!state) {
@@ -2745,14 +2820,14 @@ export function WorkplaneViewport({
return (
<main className="workplane-stage">
<div className="view-cube" aria-hidden="true">
<div className="view-cube-inner" ref={viewCubeRef}>
<div className="cube-face cube-top">TOP</div>
<div className="cube-face cube-bottom">BOTTOM</div>
<div className="cube-face cube-front">FRONT</div>
<div className="cube-face cube-back">BACK</div>
<div className="cube-face cube-right">RIGHT</div>
<div className="cube-face cube-left">LEFT</div>
<div className="view-cube" aria-label="View orientation cube" onPointerDown={(event) => event.stopPropagation()}>
<div className="view-cube-inner" ref={viewCubeRef}>
<button type="button" className="cube-face cube-top" aria-label="Bottom view" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
<button type="button" className="cube-face cube-bottom" aria-label="Top view" onClick={() => setViewCubeFace("top")}>TOP</button>
<button type="button" className="cube-face cube-front" aria-label="Front view" onClick={() => setViewCubeFace("front")}>FRONT</button>
<button type="button" className="cube-face cube-back" aria-label="Back view" onClick={() => setViewCubeFace("back")}>BACK</button>
<button type="button" className="cube-face cube-right" aria-label="Right view" onClick={() => setViewCubeFace("right")}>RIGHT</button>
<button type="button" className="cube-face cube-left" aria-label="Left view" onClick={() => setViewCubeFace("left")}>LEFT</button>
</div>
</div>
@@ -2787,7 +2862,7 @@ export function WorkplaneViewport({
onPointerCancel={finishDrag}
/>
{marqueeRect ? <div className="selection-marquee" style={marqueeRect} /> : null}
{transformOverlay && !alignMode && !mirrorMode && !rulerMode ? (
{transformOverlay && !alignMode && !mirrorMode && !rulerMode && !modifierActive ? (
<TransformOverlay
box={transformOverlay}
measureKey={pinnedMeasureKey ?? hoverMeasureKey}
@@ -2829,7 +2904,7 @@ export function WorkplaneViewport({
</div>
</section>
{selectedShape ? (
{selectedShape && !modifierActive ? (
<ShapeInspector
shape={selectedShape}
snap={snap}
@@ -2839,6 +2914,7 @@ export function WorkplaneViewport({
onClose={() => onSelectShape(null)}
onSnapChange={setSnap}
onSnapOpenChange={setSnapOpen}
onEditSketch={selectedShape.sketchProfile ? onEditSketch : undefined}
/>
) : null}
@@ -2891,7 +2967,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState {
controls.minDistance = 18;
controls.maxDistance = 4200;
controls.minPolarAngle = 0.06;
controls.maxPolarAngle = Math.PI * 0.68;
controls.maxPolarAngle = Math.PI - 0.06;
controls.target.copy(CAMERA_TARGET);
const ambient = new THREE.HemisphereLight("#ffffff", "#d6edf5", 2.1);
@@ -2919,9 +2995,12 @@ function createThreeScene(host: HTMLDivElement): ThreeState {
shapeLayer.name = "Shapes";
const helperLayer = new THREE.Group();
helperLayer.name = "SelectionHelpers";
scene.add(workplaneLayer, shapeLayer, helperLayer);
const modifierLayer = new THREE.Group();
modifierLayer.name = "EdgeModifier";
scene.add(workplaneLayer, shapeLayer, helperLayer, modifierLayer);
const raycaster = new THREE.Raycaster();
raycaster.params.Line = { threshold: 1.15 };
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
@@ -2942,6 +3021,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState {
workplaneLayer,
shapeLayer,
helperLayer,
modifierLayer,
raycaster,
pointer,
dragPlane,
@@ -2991,6 +3071,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState {
}
function resetCamera(state: ThreeState) {
state.camera.up.set(0, 1, 0);
state.camera.position.copy(CAMERA_HOME);
state.controls.target.copy(CAMERA_TARGET);
state.camera.lookAt(CAMERA_TARGET);
@@ -2998,6 +3079,27 @@ function resetCamera(state: ThreeState) {
state.controls.update();
}
function setCameraToViewFace(state: ThreeState, face: ViewCubeFace) {
const offset = state.camera.position.clone().sub(state.controls.target);
const distance = clamp(offset.length(), 22, 4200);
const directionByFace: Record<ViewCubeFace, THREE.Vector3> = {
top: new THREE.Vector3(0, 1, 0),
bottom: new THREE.Vector3(0, -1, 0),
front: new THREE.Vector3(0, 0, 1),
back: new THREE.Vector3(0, 0, -1),
right: new THREE.Vector3(1, 0, 0),
left: new THREE.Vector3(-1, 0, 0),
};
const direction = directionByFace[face].clone().normalize();
state.camera.up.set(0, 1, 0);
state.camera.position.copy(state.controls.target).add(direction.multiplyScalar(distance));
state.camera.lookAt(state.controls.target);
state.camera.updateProjectionMatrix();
state.controls.update();
state.needsRender = true;
}
function constrainCamera(state: ThreeState, workspace: WorkspaceSettings) {
const target = state.controls.target;
const previousTarget = target.clone();
@@ -3021,7 +3123,7 @@ function syncViewCube(state: ThreeState, cube: HTMLDivElement | null) {
const horizontalDistance = Math.max(0.001, Math.hypot(offset.x, offset.z));
const pitch = THREE.MathUtils.radToDeg(Math.atan2(offset.y, horizontalDistance));
const yaw = THREE.MathUtils.radToDeg(Math.atan2(offset.x, offset.z));
cube.style.transform = `rotateX(${pitch}deg) rotateY(${-yaw}deg)`;
cube.style.transform = `rotateX(${-pitch}deg) rotateY(${-yaw}deg)`;
}
function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings) {
@@ -3340,6 +3442,31 @@ function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selec
rebuildSelectionHelpers(state, shapes, selectedIds);
}
function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false) {
if (!state) return;
disposeChildren(state.modifierLayer);
const selected = new Set(selectedIds);
edges.forEach((edge) => {
if (edge.points.length < 6) return;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(edge.points, 3));
const active = selected.has(edge.id);
const subduedSelectedPreviewEdge = previewActive && active;
const material = new THREE.LineBasicMaterial({
color: active ? "#ff8a1d" : "#17b7e5",
depthTest: false,
depthWrite: false,
transparent: true,
opacity: subduedSelectedPreviewEdge ? 0.18 : active ? 1 : 0.82,
});
const line = new THREE.Line(geometry, material);
line.userData.modifierEdgeId = edge.id;
line.renderOrder = active ? 1002 : 1001;
state.modifierLayer.add(line);
});
state.needsRender = true;
}
function rebuildSelectionHelpers(state: ThreeState | null, shapes: WorkplaneShape[], selectedIds: string[]) {
if (!state) {
return;
@@ -4201,7 +4328,9 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
case "box":
addMesh(
group,
shape.radius && shape.radius > 0 ? new RoundedBoxGeometry(width, height, depth, shape.steps ?? 10, shape.radius) : new THREE.BoxGeometry(width, height, depth),
shape.radius && shape.radius > 0
? new RoundedBoxGeometry(width, height, depth, Math.max(1, shape.steps ?? 10), shape.radius)
: new THREE.BoxGeometry(width, height, depth),
shape.imagePlate && !shape.hole ? createImagePlateMaterials(shape, material, onTextureReady) : material,
shape,
);
@@ -4258,14 +4387,15 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
break;
case "mesh":
if (shape.importedMesh) {
const preserveEdgeSize = preservesEdgeTreatmentSize(shape);
addMesh(
group,
getImportedMeshGeometry(shape.importedMesh),
preserveEdgeSize ? getPreservedImportedMeshGeometry(shape) : getImportedMeshGeometry(shape.importedMesh),
material,
shape,
undefined,
undefined,
new THREE.Vector3(
preserveEdgeSize ? undefined : new THREE.Vector3(
width / Math.max(0.001, shape.importedMesh.baseWidth),
height / Math.max(0.001, shape.importedMesh.baseHeight),
depth / Math.max(0.001, shape.importedMesh.baseDepth),
@@ -4361,15 +4491,36 @@ function addMesh(
const selectedRoundedBox = selectedOutline && shape.kind === "box" && Boolean(shape.radius && shape.radius > 0);
const edgeColor = selectedOutline ? "#00aeea" : shape.hole ? "#697989" : complexEdges ? "#141b21" : darkenHex(shape.color, 0.34);
const edgeOpacity = selectedRoundedBox ? 0 : selectedOutline ? 0.98 : shape.hole ? 0.44 : complexEdges ? 0.38 : shape.kind === "text" ? 0.86 : 0.2;
const edges = new THREE.LineSegments(getEdgesGeometry(shape, prepared, selectedOutline ? 1 : complexEdges ? 14 : 25), new THREE.LineBasicMaterial({ color: edgeColor, transparent: true, opacity: edgeOpacity }));
edges.userData.complexEdge = complexEdges;
edges.position.copy(mesh.position);
edges.rotation.copy(mesh.rotation);
edges.scale.copy(mesh.scale);
group.add(edges);
if (selectedOutline && shape.importedMesh && shape.cadDisplayEdgesVersion === 2 && Boolean(shape.cadDisplayEdges?.length)) {
addCadDisplayEdges(group, shape, edgeColor, edgeOpacity);
} else {
const selectedThreshold = shape.importedMesh ? NORMAL_IMPORTED_SELECTION_EDGE_ANGLE : 1;
const edges = new THREE.LineSegments(getEdgesGeometry(shape, prepared, selectedOutline ? selectedThreshold : complexEdges ? 14 : 25), new THREE.LineBasicMaterial({ color: edgeColor, transparent: true, opacity: edgeOpacity }));
edges.userData.complexEdge = complexEdges;
edges.position.copy(mesh.position);
edges.rotation.copy(mesh.rotation);
edges.scale.copy(mesh.scale);
group.add(edges);
}
}
}
function addCadDisplayEdges(group: THREE.Group, shape: WorkplaneShape, color: string, opacity: number) {
if (!shape.cadDisplayEdges?.length) return;
const material = new THREE.LineBasicMaterial({ color, depthWrite: false, transparent: true, opacity });
shape.cadDisplayEdges.forEach((edge) => {
if (edge.points.length < 6) return;
const positions = resizedImportedCoordinates(shape, edge.points);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const line = new THREE.Line(geometry, material);
line.position.y -= shape.height / 2;
line.renderOrder = 1003;
line.userData.complexEdge = true;
group.add(line);
});
}
function getImportedMeshCache(mesh: NonNullable<WorkplaneShape["importedMesh"]>) {
const cached = importedGeometryCache.get(mesh);
if (cached) {
@@ -4394,8 +4545,20 @@ function getImportedMeshGeometry(mesh: NonNullable<WorkplaneShape["importedMesh"
return getImportedMeshCache(mesh).geometry;
}
function getPreservedImportedMeshGeometry(shape: WorkplaneShape) {
const cached = preservedImportedGeometryCache.get(shape);
if (cached) return cached;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(resizedImportedMeshPositions(shape), 3));
geometry.computeVertexNormals();
putGeometryOnBase(geometry);
geometry.userData.cached = true;
preservedImportedGeometryCache.set(shape, geometry);
return geometry;
}
function getEdgesGeometry(shape: WorkplaneShape, geometry: THREE.BufferGeometry, threshold: number) {
if (!shape.importedMesh) {
if (!shape.importedMesh || preservesEdgeTreatmentSize(shape)) {
return new THREE.EdgesGeometry(geometry, threshold);
}
+31
View File
@@ -148,6 +148,37 @@ export function ToolbarMirrorIcon() {
return <ToolbarCommandImage file="toolbar-mirror.png" className="toolbar-user-art-icon" />;
}
export function ToolbarChamferIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17 18 11h18v18l-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
}
export function ToolbarFilletIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17c0-3.3 2.7-6 6-6h18v18c0 3.9-3.1 7-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="M12 17c0-3.3 2.7-6 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
}
export function ToolbarPreserveEdgeIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M10 35V17c0-4 3-7 7-7h18" fill="none" stroke="currentColor" strokeWidth="2.7" strokeLinecap="round" />
<path d="M10 35h25V10" fill="none" stroke="currentColor" strokeWidth="2.7" strokeLinejoin="round" />
<path d="M17 29h13M17 25v8M30 25v8" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
<path d="M18 17a7 7 0 0 1 7-7" fill="none" stroke="currentColor" strokeWidth="4" strokeLinecap="round" />
</svg>
);
}
export function ToolbarSnapGridIcon() {
return <ToolbarCommandImage file="toolbar-snap-grid.png" className="toolbar-user-art-icon" />;
}
@@ -0,0 +1,169 @@
"use client";
import { Check, LoaderCircle, X } from "lucide-react";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
export function EdgeModifierPanel({
kind,
amount,
maxAmount,
chamferAngle,
quality,
sharpAngle,
tangentChain,
preserveEdgeSize,
targetName,
groupedCount,
appliedFeatureCount,
reversibleFeatureCount,
selectedCount,
availableCount,
busy,
error,
onAmountChange,
onChamferAngleChange,
onQualityChange,
onSharpAngleChange,
onTangentChainChange,
onPreserveEdgeSizeChange,
onSelectAll,
onClear,
onRemoveLastFeature,
onApply,
onCancel,
}: {
kind: CadModifierKind;
amount: number;
maxAmount: number;
chamferAngle: number;
quality: CadModifierQuality;
sharpAngle: number;
tangentChain: boolean;
preserveEdgeSize: boolean;
targetName: string;
groupedCount: number;
appliedFeatureCount: number;
reversibleFeatureCount: number;
selectedCount: number;
availableCount: number;
busy: boolean;
error: string | null;
onAmountChange: (value: number) => void;
onChamferAngleChange: (value: number) => void;
onQualityChange: (value: CadModifierQuality) => void;
onSharpAngleChange: (value: number) => void;
onTangentChainChange: (value: boolean) => void;
onPreserveEdgeSizeChange: (value: boolean) => void;
onSelectAll: () => void;
onClear: () => void;
onRemoveLastFeature: () => void;
onApply: () => void;
onCancel: () => void;
}) {
const title = kind === "fillet" ? "Fillet edges" : "Chamfer edges";
return (
<aside className="edge-modifier-panel" aria-label={title}>
<div className="edge-modifier-header">
<div>
<strong>{title}</strong>
<span>{selectedCount} of {availableCount} sharp edges selected</span>
</div>
<button type="button" aria-label={`Cancel ${kind}`} onClick={onCancel}><X size={20} /></button>
</div>
<div className={`edge-modifier-target ${groupedCount > 0 ? "grouped" : ""}`}>
<strong>{targetName}</strong>
<span>{groupedCount > 0 ? `${groupedCount} grouped objects` : "Single object"}{appliedFeatureCount > 0 ? ` · ${appliedFeatureCount} existing edge feature${appliedFeatureCount === 1 ? "" : "s"}` : ""}</span>
</div>
<div className="edge-modifier-selection-help">
Click highlighted model edges to toggle them. Hold Shift to add or remove a single edge.
</div>
<div className="edge-modifier-quick-actions">
<button type="button" onClick={onSelectAll}>All sharp edges</button>
<button type="button" onClick={onClear}>Clear</button>
</div>
{appliedFeatureCount > 0 ? (
<div className="edge-modifier-history-actions">
<button type="button" disabled={reversibleFeatureCount === 0} onClick={onRemoveLastFeature}>
Remove last edge feature
</button>
{reversibleFeatureCount === 0 ? <span>Older edge features do not have stored undo history.</span> : null}
</div>
) : null}
<label className="edge-modifier-field">
<span>{kind === "fillet" ? "Radius" : "Distance"}</span>
<div className="edge-modifier-value-row">
<input
type="range"
min="0.05"
max={Math.max(0.05, maxAmount)}
step="0.05"
value={Math.min(amount, maxAmount)}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
/>
<input
type="number"
min="0.05"
max={maxAmount}
step="0.05"
value={amount}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
/>
<span>mm</span>
</div>
</label>
{kind === "chamfer" ? (
<label className="edge-modifier-field">
<span>Angle</span>
<div className="edge-modifier-value-row">
<input type="range" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
) : null}
<label className="edge-modifier-field">
<span>Sharp-edge threshold</span>
<div className="edge-modifier-value-row">
<input type="range" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
<label className="edge-modifier-check">
<input type="checkbox" checked={tangentChain} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
<span>Select tangent chains</span>
</label>
<label className="edge-modifier-check">
<input type="checkbox" checked={preserveEdgeSize} 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} onChange={(event) => onQualityChange(event.currentTarget.value as CadModifierQuality)}>
<option value="draft">Draft</option>
<option value="standard">Standard</option>
<option value="fine">Fine</option>
</select>
</label>
{error ? <div className="edge-modifier-error" role="alert">{error}</div> : null}
<div className="edge-modifier-footer">
<button type="button" className="secondary" onClick={onCancel}>Cancel</button>
<button type="button" className="primary" disabled={busy || selectedCount === 0 || Boolean(error)} onClick={onApply}>
{busy ? <LoaderCircle className="edge-modifier-spinner" size={17} /> : <Check size={17} />}
Apply
</button>
</div>
</aside>
);
}
@@ -202,6 +202,7 @@ export function ShapeInspector({
onClose,
onSnapChange,
onSnapOpenChange,
onEditSketch,
}: {
shape: WorkplaneShape;
snap: GridSize;
@@ -211,6 +212,7 @@ export function ShapeInspector({
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
onEditSketch?: () => void;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
@@ -302,6 +304,12 @@ export function ShapeInspector({
</div>
) : null}
{shape.sketchProfile && onEditSketch ? (
<button className="edit-sketch-button" type="button" disabled={locked} onClick={onEditSketch}>
Edit sketch
</button>
) : null}
<div className="property-card">
<button
className="property-card-header"
+51
View File
@@ -0,0 +1,51 @@
export type CadModifierKind = "chamfer" | "fillet";
export type CadModifierEdge = {
id: number;
points: number[];
angle: number;
boundary: boolean;
manifold: boolean;
};
export type CadModifierQuality = "draft" | "standard" | "fine";
export type CadModifierDisplayEdge = {
points: number[];
};
export type CadModifierMeshPart = {
positions?: Float32Array;
indices?: Uint32Array;
brep?: string;
brepTransform?: number[];
hole: boolean;
};
export type CadModifierWorkerRequest =
| { type: "prepare"; requestId: number; parts: CadModifierMeshPart[]; sharpAngle: number }
| {
type: "preview";
requestId: number;
kind: CadModifierKind;
edgeIds: number[];
amount: number;
quality: CadModifierQuality;
chamferAngle: number;
}
| { type: "dispose"; requestId: number };
export type CadModifierWorkerResponse =
| { type: "ready"; requestId: number; edges: CadModifierEdge[]; selectableEdgeIds: number[]; sourceType: string }
| {
type: "preview";
requestId: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
triangleCount: number;
brep: string;
displayEdges: CadModifierDisplayEdge[];
}
| { type: "disposed"; requestId: number }
| { type: "error"; requestId: number; message: string };
+62
View File
@@ -29,6 +29,54 @@ export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
export function preservesEdgeTreatmentSize(shape: WorkplaneShape) {
return shape.edgeResizeMode === "preserve" && Boolean(shape.importedMesh && shape.edgeTreatments?.length);
}
function edgePreservedCoordinate(value: number, baseSize: number, targetSize: number, centered: boolean, requestedZone: number) {
const oldMin = centered ? -baseSize / 2 : 0;
const oldMax = oldMin + baseSize;
const newMin = centered ? -targetSize / 2 : 0;
const zone = Math.max(0, Math.min(requestedZone, baseSize / 2, targetSize / 2));
if (zone <= 1e-6 || Math.abs(baseSize - targetSize) <= 1e-9) {
return newMin + (value - oldMin) * targetSize / Math.max(0.001, baseSize);
}
const distanceFromMin = value - oldMin;
const distanceFromMax = oldMax - value;
if (distanceFromMin <= zone) return newMin + distanceFromMin;
if (distanceFromMax <= zone) return newMin + targetSize - distanceFromMax;
const oldInterior = Math.max(1e-6, baseSize - zone * 2);
const newInterior = Math.max(0, targetSize - zone * 2);
return newMin + zone + (distanceFromMin - zone) * newInterior / oldInterior;
}
export function resizedImportedCoordinates(shape: WorkplaneShape, sourcePositions: number[]) {
const mesh = shape.importedMesh;
if (!mesh) return [];
const width = shapeWidth(shape);
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 positions = new Array<number>(sourcePositions.length);
for (let index = 0; index + 2 < sourcePositions.length; index += 3) {
if (preserve) {
positions[index] = edgePreservedCoordinate(sourcePositions[index], mesh.baseWidth, width, true, zone);
positions[index + 1] = edgePreservedCoordinate(sourcePositions[index + 1], mesh.baseHeight, height, false, zone);
positions[index + 2] = edgePreservedCoordinate(sourcePositions[index + 2], mesh.baseDepth, depth, true, zone);
} else {
positions[index] = sourcePositions[index] * width / Math.max(0.001, mesh.baseWidth);
positions[index + 1] = sourcePositions[index + 1] * height / Math.max(0.001, mesh.baseHeight);
positions[index + 2] = sourcePositions[index + 2] * depth / Math.max(0.001, mesh.baseDepth);
}
}
return positions;
}
export function resizedImportedMeshPositions(shape: WorkplaneShape) {
return shape.importedMesh ? resizedImportedCoordinates(shape, shape.importedMesh.positions) : [];
}
export function resizedShapeSize(width: number, depth: number) {
return Math.max(width, depth);
}
@@ -71,6 +119,12 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
}
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: canonicalizeShape(entry.before),
}));
}
return next;
}
@@ -105,6 +159,14 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.font === b.font &&
a.importedMesh === b.importedMesh &&
a.imagePlate === b.imagePlate &&
a.sketchProfile === b.sketchProfile &&
a.edgeTreatments === b.edgeTreatments &&
a.edgeTreatmentHistory === b.edgeTreatmentHistory &&
a.cadDisplayEdges === b.cadDisplayEdges &&
a.cadDisplayEdgesVersion === b.cadDisplayEdgesVersion &&
a.edgeResizeMode === b.edgeResizeMode &&
a.cadBrep === b.cadBrep &&
a.cadBrepFrame === b.cadBrepFrame &&
a.groupedShapes === b.groupedShapes &&
a.groupedBaseWidth === b.groupedBaseWidth &&
a.groupedBaseDepth === b.groupedBaseDepth &&
+72
View File
@@ -56,6 +56,70 @@ export type AlignHandleStatus = {
title: string;
};
export type SketchPoint = {
id: string;
x: number;
z: number;
handleIn?: { x: number; z: number };
handleOut?: { x: number; z: number };
mode?: "corner" | "smooth" | "split";
};
export type SketchSegment = {
id: string;
startId: string;
endId: string;
kind?: "line" | "bezier" | "smooth";
};
export type SketchImage = {
id: string;
name: string;
dataUrl: string;
mimeType: string;
pixelWidth: number;
pixelHeight: number;
x: number;
z: number;
width: number;
depth: number;
opacity?: number;
lockAspect?: boolean;
};
export type SketchProfile = {
points: SketchPoint[];
segments: SketchSegment[];
images?: SketchImage[];
};
export type EdgeTreatmentFeature = {
kind: "fillet" | "chamfer";
amount: number;
edgeCount: number;
chamferAngle?: number;
};
export type EdgeTreatmentHistoryEntry = {
id: string;
createdAt: number;
feature: EdgeTreatmentFeature;
before: WorkplaneShape;
};
export type CadDisplayEdge = {
points: number[];
};
export type CadBrepFrame = {
x: number;
z: number;
elevation: number;
width: number;
depth: number;
height: number;
};
export type WorkplaneShape = {
id: string;
name: string;
@@ -99,6 +163,14 @@ export type WorkplaneShape = {
pixelWidth: number;
pixelHeight: number;
};
sketchProfile?: SketchProfile;
edgeTreatments?: EdgeTreatmentFeature[];
edgeTreatmentHistory?: EdgeTreatmentHistoryEntry[];
cadDisplayEdges?: CadDisplayEdge[];
cadDisplayEdgesVersion?: 2;
edgeResizeMode?: "scale" | "preserve";
cadBrep?: string;
cadBrepFrame?: CadBrepFrame;
groupedShapes?: WorkplaneShape[];
groupedBaseWidth?: number;
groupedBaseDepth?: number;
+324
View File
@@ -0,0 +1,324 @@
/// <reference lib="webworker" />
import { OcctKernel, type ShapeHandle } from "occt-wasm";
import type { CadModifierDisplayEdge, CadModifierEdge, CadModifierMeshPart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
const HASH_UPPER_BOUND = 2_147_483_647;
const CAD_EDGE_WIREFRAME_DEFLECTION = 0.035;
const CAD_DISPLAY_EDGE_MIN_ANGLE = 0.75;
const CURVED_SURFACE_TYPES = new Set(["cylinder", "cone", "sphere", "torus", "bspline", "bezier", "offset", "revolution", "extrusion"]);
let kernelPromise: Promise<OcctKernel> | null = null;
let baseShape: ShapeHandle | null = null;
let baseSolids: ShapeHandle[] = [];
let edgeHandles: ShapeHandle[] = [];
let edgeOwners: number[] = [];
type CollectedCadEdge = CadModifierEdge & {
curveType: string;
surfaceTypes: string[];
};
function post(message: CadModifierWorkerResponse, transfer: Transferable[] = []) {
self.postMessage(message, { transfer });
}
function kernel() {
const moduleUrl = "/assets/occt/occt-wasm.js";
kernelPromise ??= import(/* webpackIgnore: true */ moduleUrl).then((imported: { default: (options?: { locateFile?: (path: string) => string }) => Promise<unknown> }) => imported.default({
locateFile: (path) => path.endsWith(".wasm") ? "/assets/occt/occt-wasm.wasm" : path,
})).then((module) => {
const KernelConstructor = OcctKernel as unknown as new (rawModule: unknown) => OcctKernel;
return new KernelConstructor(module);
});
return kernelPromise;
}
function releaseSession(cad: OcctKernel) {
try {
cad.releaseAll();
} catch {
// The arena may already be empty after an operation failure.
}
baseShape = null;
baseSolids = [];
edgeHandles = [];
edgeOwners = [];
}
function orientedFaceNormal(cad: OcctKernel, face: ShapeHandle, point: { x: number; y: number; z: number }) {
const uv = cad.uvFromPoint(face, point);
const normal = cad.surfaceNormal(face, uv.u, uv.v);
if (cad.shapeOrientation(face) === "reversed") {
normal.x *= -1;
normal.y *= -1;
normal.z *= -1;
}
const length = Math.hypot(normal.x, normal.y, normal.z) || 1;
return { x: normal.x / length, y: normal.y / length, z: normal.z / length };
}
function parseEdgeFaceMap(values: number[]) {
const map = new Map<number, number[]>();
for (let index = 0; index + 1 < values.length; ) {
const edgeHash = values[index++];
const count = values[index++];
const faces = values.slice(index, index + count);
index += count;
const current = map.get(edgeHash) ?? [];
faces.forEach((hash) => {
if (!current.includes(hash)) current.push(hash);
});
map.set(edgeHash, current);
}
return map;
}
function edgeAngle(cad: OcctKernel, points: number[], faceHashes: number[], faceByHash: Map<number, ShapeHandle>) {
if (faceHashes.length !== 2 || points.length < 6) return { angle: 0, boundary: faceHashes.length < 2, manifold: false };
const offset = Math.max(0, Math.floor(points.length / 6) * 3);
const point = { x: points[offset], y: points[offset + 1], z: points[offset + 2] };
const faceA = faceByHash.get(faceHashes[0]);
const faceB = faceByHash.get(faceHashes[1]);
if (faceA === undefined || faceB === undefined) return { angle: 0, boundary: false, manifold: false };
try {
const a = orientedFaceNormal(cad, faceA, point);
const b = orientedFaceNormal(cad, faceB, point);
const dot = Math.max(-1, Math.min(1, a.x * b.x + a.y * b.y + a.z * b.z));
const rawAngle = (Math.acos(dot) * 180) / Math.PI;
return { angle: Math.min(rawAngle, 180 - rawAngle), boundary: false, manifold: true };
} catch {
return { angle: 0, boundary: false, manifold: false };
}
}
function meshPartToAsciiStl(part: CadModifierMeshPart) {
if (!part.positions || !part.indices) throw new Error("The selected object has no mesh data");
const lines = new Array<string>(part.indices.length / 3 + 2);
lines[0] = "solid sketchforge";
const { positions, indices } = part;
for (let offset = 0, face = 1; offset + 2 < indices.length; offset += 3, face += 1) {
const ai = indices[offset] * 3;
const bi = indices[offset + 1] * 3;
const ci = indices[offset + 2] * 3;
const ax = positions[ai];
const ay = positions[ai + 1];
const az = positions[ai + 2];
const bx = positions[bi];
const by = positions[bi + 1];
const bz = positions[bi + 2];
const cx = positions[ci];
const cy = positions[ci + 1];
const cz = positions[ci + 2];
const abx = bx - ax;
const aby = by - ay;
const abz = bz - az;
const acx = cx - ax;
const acy = cy - ay;
const acz = cz - az;
let nx = aby * acz - abz * acy;
let ny = abz * acx - abx * acz;
let nz = abx * acy - aby * acx;
const length = Math.hypot(nx, ny, nz) || 1;
nx /= length;
ny /= length;
nz /= length;
lines[face] = `facet normal ${nx} ${ny} ${nz}\n outer loop\n vertex ${ax} ${ay} ${az}\n vertex ${bx} ${by} ${bz}\n vertex ${cx} ${cy} ${cz}\n endloop\nendfacet`;
}
lines[lines.length - 1] = "endsolid sketchforge";
return lines.join("\n");
}
function reconstructSolid(cad: OcctKernel, part: CadModifierMeshPart) {
if (part.brep) {
let exact = cad.fromBREP(part.brep);
if (part.brepTransform?.length === 12) exact = cad.generalTransform(exact, part.brepTransform);
const restoredSolids = cad.getSubShapes(exact, "solid");
if (cad.isValid(exact) && (cad.isSolid(exact) || restoredSolids.length > 0)) {
return restoredSolids.length === 1 ? restoredSolids[0] : exact;
}
exact = cad.fixShape(exact);
exact = cad.fixFaceOrientations(exact);
if (cad.isSolid(exact)) exact = cad.healSolid(exact, 1e-5);
const healedSolids = cad.getSubShapes(exact, "solid");
if (cad.isValid(exact) && (cad.isSolid(exact) || healedSolids.length > 0)) {
return healedSolids.length === 1 ? healedSolids[0] : exact;
}
throw new Error("The stored CAD feature could not be restored as a valid solid");
}
const imported = cad.importStl(meshPartToAsciiStl(part));
let shape = cad.fixShape(imported);
if (cad.isSolid(shape)) {
try {
shape = cad.healSolid(shape, 1e-4);
shape = cad.fixFaceOrientations(shape);
shape = cad.removeDegenerateEdges(shape);
shape = cad.unifySameDomain(shape);
} catch {
// Fall through to face sewing when the imported solid cannot be healed directly.
}
if (cad.isSolid(shape) && cad.isValid(shape)) return shape;
}
const faces = cad.getSubShapes(imported, "face");
if (faces.length === 0) throw new Error("The selected object has no closed faces");
for (const tolerance of [1e-5, 1e-4, 1e-3, 1e-2]) {
try {
let candidate = cad.sewAndSolidify(faces, tolerance);
candidate = cad.fixShape(candidate);
if (cad.isSolid(candidate)) candidate = cad.healSolid(candidate, tolerance);
candidate = cad.fixFaceOrientations(candidate);
candidate = cad.removeDegenerateEdges(candidate);
candidate = cad.unifySameDomain(candidate);
if (cad.isSolid(candidate) && cad.isValid(candidate)) return candidate;
} catch {
// Try the next tolerance. Curved tessellations can need looser vertex sewing.
}
}
throw new Error("The selected mesh is open or non-manifold. Repair it before adding edge treatments.");
}
function reconstructParts(cad: OcctKernel, parts: CadModifierMeshPart[]) {
const solids = parts.filter((part) => !part.hole).map((part) => reconstructSolid(cad, part));
const holes = parts.filter((part) => part.hole).map((part) => reconstructSolid(cad, part));
if (solids.length === 0) throw new Error("The group has no solid body to modify");
let result = solids[0];
for (let index = 1; index < solids.length; index += 1) {
result = cad.fuse(result, solids[index]);
result = cad.simplify(result);
result = cad.unifySameDomain(result);
}
for (const hole of holes) {
result = cad.cut(result, hole);
result = cad.simplify(result);
result = cad.unifySameDomain(result);
}
result = cad.fixShape(result);
result = cad.simplify(result);
result = cad.unifySameDomain(result);
if (!cad.isValid(result)) throw new Error("The grouped solid could not be repaired into valid topology");
return result;
}
function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number) {
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 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 edges: CollectedCadEdge[] = 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 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 };
}).filter((edge) => edge.points.length >= 6);
const selectableEdgeIds = edges.filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const displayEdges = cadDisplayEdgesFromCollected(edges);
return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, ...edge }) => edge), selectableEdgeIds, displayEdges };
}
function cadDisplayEdgesFromCollected(edges: CollectedCadEdge[]): CadModifierDisplayEdge[] {
return edges
.filter((edge) => {
if (!edge.manifold || edge.boundary || edge.points.length < 6) return false;
const effectiveAngle = Math.min(edge.angle, 180 - edge.angle);
const touchesCurvedSurface = edge.surfaceTypes.some((surfaceType) => CURVED_SURFACE_TYPES.has(surfaceType));
const isCurvedEdge = edge.curveType !== "line";
return effectiveAngle + 1e-3 >= CAD_DISPLAY_EDGE_MIN_ANGLE || touchesCurvedSurface || isCurvedEdge;
})
.map((edge) => ({ points: edge.points }));
}
function tessellationOptions(quality: CadModifierQuality, amount: number) {
if (quality === "draft") return { linearDeflection: Math.max(0.12, amount / 3), angularDeflection: 0.42 };
if (quality === "fine") return { linearDeflection: Math.max(0.025, amount / 12), angularDeflection: 0.1 };
return { linearDeflection: Math.max(0.055, amount / 7), angularDeflection: 0.2 };
}
self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
const request = event.data;
try {
const cad = await kernel();
if (request.type === "dispose") {
releaseSession(cad);
post({ type: "disposed", requestId: request.requestId });
return;
}
if (request.type === "prepare") {
releaseSession(cad);
baseShape = reconstructParts(cad, request.parts);
const collected = collectEdges(cad, baseShape, request.sharpAngle);
edgeHandles = collected.handles;
baseSolids = cad.isSolid(baseShape) ? [baseShape] : cad.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(cad.getSubShapes(solid, "edge").map((edge) => cad.hashCode(edge, HASH_UPPER_BOUND))));
edgeOwners = edgeHandles.map((edge) => {
const hash = cad.hashCode(edge, HASH_UPPER_BOUND);
return Math.max(0, ownerHashes.findIndex((hashes) => hashes.has(hash)));
});
post({
type: "ready",
requestId: request.requestId,
edges: collected.edges,
selectableEdgeIds: collected.selectableEdgeIds,
sourceType: cad.getShapeType(baseShape),
});
return;
}
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 cad.copy(solid);
return request.kind === "fillet"
? cad.fillet(solid, componentEdges, request.amount)
: Math.abs(request.chamferAngle - 45) < 0.001
? cad.chamfer(solid, componentEdges, request.amount)
: cad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
});
const result = componentResults.length === 1 ? componentResults[0] : cad.makeCompound(componentResults);
if (!cad.isValid(result)) throw new Error("The chosen size creates invalid or overlapping edge geometry");
const mesh = cad.tessellate(result, tessellationOptions(request.quality, request.amount));
const displayEdges = collectEdges(cad, result, request.chamferAngle).displayEdges;
const brep = cad.toBREP(result);
componentResults.forEach((component) => cad.release(component));
if (componentResults.length > 1) cad.release(result);
post(
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges },
[mesh.positions.buffer, mesh.normals.buffer, mesh.indices.buffer],
);
} catch (error) {
const rawMessage = error instanceof Error ? error.message : "";
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";
post({ type: "error", requestId: request.requestId, message });
}
};
export {};