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
+3 -1
View File
@@ -82,7 +82,7 @@ On Windows, you can open PowerShell in the folder by opening the folder, clickin
## Docker / FabLab Server (Recommended) ## Docker / FabLab Server (Recommended)
Docker is the easiest way to run SketchForge for a classroom, workshop, or FabLab. It packages the build tools, static website, Nginx server, health check, and restart behavior together. Docker is the easiest way to run SketchForge for a classroom, workshop, or FabLab. It packages the build tools, Next.js server, health check, persistent shared-project storage, and restart behavior together.
### What You Need ### What You Need
@@ -130,6 +130,8 @@ http://127.0.0.1:3000/
If that works, SketchForge is running. If that works, SketchForge is running.
The container listens on port `3000`. It also accepts connections on port `80` for backward compatibility with older UnRAID templates and forwards them to the same server. New Docker and UnRAID configurations should use container port `3000`.
### Shared Docker Projects ### Shared Docker Projects
Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there. Docker deployments include a shared `.skf` project library. Private projects still autosave in each user's browser. The **Shared** dashboard section lists files stored in `/data/projects`, and **Export → SKF → Save to shared** writes the current project there.
Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

+222 -1
View File
@@ -877,6 +877,22 @@ button {
background: #edf2f6; background: #edf2f6;
} }
.dashboard-version-row {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 13px;
color: #52697d;
border-top: 1px solid #dce5ec;
font-size: 13px;
font-weight: 800;
}
.dashboard-version-row strong {
color: #263f57;
font-size: 14px;
}
@media (max-width: 860px) { @media (max-width: 860px) {
.dashboard-topbar { .dashboard-topbar {
grid-template-columns: 1fr auto; grid-template-columns: 1fr auto;
@@ -1363,7 +1379,7 @@ button {
} }
.sketch-start-section { .sketch-start-section {
min-width: 250px; min-width: 260px;
} }
.sketch-finish-section { .sketch-finish-section {
@@ -1477,6 +1493,75 @@ button {
cursor: default; cursor: default;
} }
.sketch-create-menu {
position: relative;
height: 43px;
}
.sketch-create-menu-trigger {
position: relative;
min-width: 112px;
padding-right: 20px;
}
.sketch-create-menu-trigger.active {
color: #17405d;
background: #e7f5fb;
border-color: #bcdce8;
}
.sketch-command-button .sketch-create-menu-chevron {
position: absolute;
right: 4px;
bottom: 5px;
width: 13px;
height: 13px;
}
.sketch-create-dropdown {
position: absolute;
top: calc(100% + 5px);
left: 0;
z-index: 70;
display: grid;
width: 232px;
padding: 5px;
background: rgba(250, 252, 253, 0.99);
border: 1px solid #cbd9e3;
border-radius: 7px;
box-shadow: 0 12px 28px rgba(26, 47, 66, 0.22);
}
.sketch-create-dropdown button {
display: grid;
gap: 3px;
width: 100%;
padding: 9px 10px;
color: #314b61;
background: transparent;
border: 0;
border-radius: 5px;
cursor: pointer;
text-align: left;
}
.sketch-create-dropdown button:hover,
.sketch-create-dropdown button:focus-visible {
background: #e7f5fb;
outline: none;
}
.sketch-create-dropdown strong {
font-size: 12px;
font-weight: 900;
}
.sketch-create-dropdown span {
color: #708395;
font-size: 10px;
font-weight: 700;
}
.toolbar-icon.disabled .sketch-reference-icon, .toolbar-icon.disabled .sketch-reference-icon,
.toolbar-icon:disabled .sketch-reference-icon, .toolbar-icon:disabled .sketch-reference-icon,
.sketch-command-button.disabled .sketch-reference-icon, .sketch-command-button.disabled .sketch-reference-icon,
@@ -2683,6 +2768,51 @@ button {
pointer-events: none; pointer-events: none;
} }
.sketch-revolve-preview {
position: absolute;
top: 18px;
right: 22px;
z-index: 8;
width: clamp(210px, 25vw, 330px);
height: clamp(170px, 28vh, 270px);
overflow: hidden;
background: rgba(250, 253, 254, 0.94);
border: 1px solid rgba(166, 190, 204, 0.9);
border-radius: 12px;
box-shadow: 0 12px 34px rgba(34, 67, 86, 0.16);
pointer-events: none;
}
.sketch-revolve-preview-title {
position: absolute;
top: 10px;
left: 12px;
z-index: 1;
color: #49647a;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.sketch-revolve-preview canvas {
display: block;
width: 100%;
height: 100%;
background: radial-gradient(circle at 50% 48%, rgba(255, 255, 255, 0.98), rgba(229, 240, 245, 0.92));
}
.sketch-revolve-preview-empty {
display: grid;
height: 100%;
place-items: center;
padding: 34px;
color: #718696;
font-size: 13px;
font-weight: 750;
text-align: center;
}
.sketch-plate-wrap { .sketch-plate-wrap {
position: absolute; position: absolute;
inset: 14px 14px 42px; inset: 14px 14px 42px;
@@ -2746,6 +2876,24 @@ button {
stroke-width: 1.6; stroke-width: 1.6;
} }
.sketch-revolve-guide rect {
fill: rgba(248, 251, 252, 0.66);
}
.sketch-revolve-guide line {
stroke: #c838bc;
stroke-width: 2.5;
stroke-dasharray: 8 5;
vector-effect: non-scaling-stroke;
}
.sketch-revolve-guide text {
fill: #9e2996;
font-weight: 900;
letter-spacing: 0.08em;
text-anchor: end;
}
.sketch-reference-shapes rect, .sketch-reference-shapes rect,
.sketch-reference-shapes ellipse { .sketch-reference-shapes ellipse {
fill: rgba(207, 142, 42, 0.22); fill: rgba(207, 142, 42, 0.22);
@@ -3971,6 +4119,17 @@ button {
overflow: hidden; overflow: hidden;
} }
.shape-inspector.sketch-revolve-inspector,
.shape-inspector.gear-inspector {
overflow-anchor: none;
scrollbar-width: none;
}
.shape-inspector.sketch-revolve-inspector::-webkit-scrollbar,
.shape-inspector.gear-inspector::-webkit-scrollbar {
display: none;
}
.shape-inspector-header { .shape-inspector-header {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -4185,6 +4344,8 @@ button {
gap: 8px; gap: 8px;
width: calc(100% - 20px); width: calc(100% - 20px);
height: 38px; height: 38px;
min-height: 38px;
flex-shrink: 0;
margin: 0 10px 12px; margin: 0 10px 12px;
color: #28516d; color: #28516d;
background: #ffffff; background: #ffffff;
@@ -4215,6 +4376,10 @@ button {
border-radius: 8px; border-radius: 8px;
} }
.property-card.collapsed {
padding-bottom: 0;
}
.property-card-header { .property-card-header {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -4247,6 +4412,62 @@ button {
gap: 17px; gap: 17px;
} }
.gear-type-property {
display: grid;
gap: 8px;
color: #586a7d;
font-size: 15px;
font-weight: 650;
}
.gear-type-options {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.gear-type-options button {
display: grid;
min-width: 0;
min-height: 84px;
place-items: center;
gap: 3px;
padding: 5px 3px 7px;
color: #53687a;
background: #f6f9fb;
border: 1px solid #cbd7e0;
border-radius: 7px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: background 120ms ease, border-color 120ms ease, box-shadow 120ms ease, color 120ms ease;
}
.gear-type-options button:hover:not(:disabled) {
color: #176f94;
background: #eef9fc;
border-color: #8fc9dc;
}
.gear-type-options button.selected {
color: #0b789f;
background: #eaf8fc;
border-color: #40aad0;
box-shadow: 0 0 0 2px rgba(0, 159, 211, 0.12);
}
.gear-type-options button:disabled {
cursor: default;
opacity: 0.5;
}
.gear-type-options img {
display: block;
width: 62px;
height: 62px;
object-fit: contain;
}
.range-property { .range-property {
display: grid; display: grid;
gap: 7px; gap: 7px;
+9 -5
View File
@@ -6,7 +6,7 @@ import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds"; import { createLocalId } from "@/lib/localIds";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { importSkfProject } from "@/lib/skfProject"; import { importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
import { importExtensionSupported } from "@/lib/stlImport"; import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -1062,7 +1062,7 @@ function Dashboard({
<span>Challenges</span> <span>Challenges</span>
</button> </button>
</div> </div>
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Download settings" title="Download settings" onClick={onOpenSettings}> <button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Settings" title="Settings" onClick={onOpenSettings}>
<Settings size={20} /> <Settings size={20} />
<span>Settings</span> <span>Settings</span>
</button> </button>
@@ -1275,10 +1275,10 @@ function Dashboard({
) : null} ) : null}
{settingsOpen ? ( {settingsOpen ? (
<section className="dashboard-settings-panel" role="dialog" aria-modal="true" aria-label="Download settings"> <section className="dashboard-settings-panel" role="dialog" aria-modal="true" aria-label="Settings">
<header> <header>
<strong>Download settings</strong> <strong>Settings</strong>
<button type="button" aria-label="Close download settings" onClick={onCloseSettings}> <button type="button" aria-label="Close settings" onClick={onCloseSettings}>
<X size={18} /> <X size={18} />
</button> </button>
</header> </header>
@@ -1301,6 +1301,10 @@ function Dashboard({
placeholder="C:\\Users\\username\\Downloads" placeholder="C:\\Users\\username\\Downloads"
/> />
</label> </label>
<div className="dashboard-version-row">
<span>SketchForge version</span>
<strong>{SKF_CREATED_WITH_VERSION}</strong>
</div>
</section> </section>
) : null} ) : null}
</main> </main>
+228 -16
View File
@@ -18,6 +18,7 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json
import { manifoldModuleSource } from "@/generated/manifoldModuleSource"; import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64"; import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation"; import { sphereTessellation } from "@/lib/sphereTessellation";
import { createGearGeometry } from "@/lib/gearGeometry";
import { import {
ToolbarAlignIcon, ToolbarAlignIcon,
ToolbarChamferIcon, ToolbarChamferIcon,
@@ -80,6 +81,7 @@ import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames"; import { projectExportFileName } from "@/lib/exportNames";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation"; 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 { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
@@ -95,7 +97,7 @@ import {
type SketchForgeMcpViewFace, type SketchForgeMcpViewFace,
} from "@/lib/sketchforgeMcpProtocol"; } from "@/lib/sketchforgeMcpProtocol";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; 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 }; export { importedShapeFromStl, importedShapeFromSvg };
@@ -390,6 +392,7 @@ async function shapeFromResolvedSketchProfile(
sourceFormat: "json", sourceFormat: "json",
}, },
sketchProfile: cloneSketchProfile(profile), sketchProfile: cloneSketchProfile(profile),
sketchOperation: "extrude",
} satisfies WorkplaneShape); } satisfies WorkplaneShape);
} finally { } finally {
[...new Set(disposable)].reverse().forEach(disposeManifold); [...new Set(disposable)].reverse().forEach(disposeManifold);
@@ -505,6 +508,50 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex
sourceFormat: "json", sourceFormat: "json",
}, },
sketchProfile: cloneSketchProfile(profile), 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); } satisfies WorkplaneShape);
} }
@@ -2029,6 +2076,20 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null {
case "tube": case "tube":
geometry = createBooleanHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144); geometry = createBooleanHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144);
break; 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": case "wedge":
geometry = createBooleanWedgeGeometry(width, height, depth); geometry = createBooleanWedgeGeometry(width, height, depth);
break; break;
@@ -5229,6 +5290,12 @@ export function SketchForgeEditor({
const [projectInteractionActive, setProjectInteractionActive] = useState(false); const [projectInteractionActive, setProjectInteractionActive] = useState(false);
const [toolbarMode, setToolbarMode] = useState<ToolbarMode>("geometry"); const [toolbarMode, setToolbarMode] = useState<ToolbarMode>("geometry");
const [sketchActive, setSketchActive] = useState(false); 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 [sketchTool, setSketchTool] = useState<SketchTool>("line");
const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile()); const [sketchProfile, setSketchProfile] = useState<SketchProfile>(() => emptySketchProfile());
const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]); const [sketchHistory, setSketchHistory] = useState<SketchProfile[]>([emptySketchProfile()]);
@@ -5532,6 +5599,26 @@ export function SketchForgeEditor({
edgeModifierRef.current = edgeModifier; edgeModifierRef.current = edgeModifier;
}, [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(() => { useEffect(() => {
setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace)); setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace));
}, [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()); const initial = cloneSketchProfile(profile ?? emptySketchProfile());
setToolbarMode("sketch"); setToolbarMode("sketch");
setSketchActive(true); setSketchActive(true);
setSketchOperation(operation);
setSketchRevolveSettings(normalizeSketchRevolveSettings(revolveSettings));
setSketchRevolvePreview(null);
setSketchTool(profile?.segments.length ? "select" : "line"); setSketchTool(profile?.segments.length ? "select" : "line");
setSketchProfile(initial); setSketchProfile(initial);
const initialHistory = [cloneSketchProfile(initial)]; const initialHistory = [cloneSketchProfile(initial)];
@@ -5870,7 +5960,7 @@ export function SketchForgeEditor({
setSketchMeasureStart(null); setSketchMeasureStart(null);
setSketchMeasurement(null); setSketchMeasurement(null);
setEditingSketchShapeId(editingId); 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(() => { const beginSketchEdit = useCallback(() => {
@@ -5878,7 +5968,8 @@ export function SketchForgeEditor({
setNotice("Select one shape created from a sketch to edit it"); setNotice("Select one shape created from a sketch to edit it");
return; 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]); }, [beginSketch, selectedShape, selectedShapes.length]);
const cancelSketch = useCallback(() => { const cancelSketch = useCallback(() => {
@@ -5888,6 +5979,7 @@ export function SketchForgeEditor({
setSketchMeasureStart(null); setSketchMeasureStart(null);
setSketchMeasurement(null); setSketchMeasurement(null);
setEditingSketchShapeId(null); setEditingSketchShapeId(null);
setSketchRevolvePreview(null);
setNotice("Sketch cancelled"); setNotice("Sketch cancelled");
}, []); }, []);
@@ -6228,23 +6320,27 @@ export function SketchForgeEditor({
const finishSketch = useCallback(async () => { const finishSketch = useCallback(async () => {
const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null; const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null;
const height = existing?.height ?? 10; const height = existing?.height ?? 10;
let extruded: WorkplaneShape | null; let resolved: WorkplaneShape | null;
try { try {
extruded = await shapeFromSketchProfile(sketchProfile, height, existing); resolved = sketchOperation === "revolve"
? await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing)
: await shapeFromSketchProfile(sketchProfile, height, existing);
} catch (error) { } 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; return;
} }
if (!extruded) { if (!resolved) {
setNotice("Close at least one profile before finishing the sketch"); setNotice("Close at least one profile before finishing the sketch");
return; return;
} }
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? extruded : shape)) : [...shapes, extruded]; const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved];
commitShapes(nextShapes, extruded.id, existing ? "Sketch updated" : "Sketch created at 10 mm height"); 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); setSketchActive(false);
setSketchRevolvePreview(null);
setEditingSketchShapeId(null); setEditingSketchShapeId(null);
setToolbarMode("geometry"); setToolbarMode("geometry");
}, [commitShapes, editingSketchShapeId, shapes, sketchProfile]); }, [commitShapes, editingSketchShapeId, shapes, sketchOperation, sketchProfile, sketchRevolveSettings]);
useEffect(() => { useEffect(() => {
if (!projectId) { if (!projectId) {
@@ -6313,6 +6409,8 @@ export function SketchForgeEditor({
if (interactionHistoryTimerRef.current !== null) { if (interactionHistoryTimerRef.current !== null) {
window.clearTimeout(interactionHistoryTimerRef.current); window.clearTimeout(interactionHistoryTimerRef.current);
} }
sketchRevolveUpdateTimerRef.current.forEach((timer) => window.clearTimeout(timer));
sketchRevolveUpdateTimerRef.current.clear();
}; };
}, []); }, []);
@@ -6324,10 +6422,72 @@ export function SketchForgeEditor({
[commitShapes, placementElevation, shapes], [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( const updateShape = useCallback(
(id: string, patch: ShapeUpdatePatch) => { (id: string, patch: ShapeUpdatePatch) => {
const bakeTransform = Boolean(patch.bakeTransform); const bakeTransform = Boolean(patch.bakeTransform);
const cleanedPatch = cleanShapePatch(patch); 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[]) => { const applyPatch = (current: WorkplaneShape[]) => {
let changed = false; let changed = false;
const next = current.map((shape) => { const next = current.map((shape) => {
@@ -6365,7 +6525,7 @@ export function SketchForgeEditor({
commitShapes(next, selectedIds); commitShapes(next, selectedIds);
} }
}, },
[commitShapes, selectedIds, shapes], [commitShapes, scheduleRevolveShapeUpdate, selectedIds, shapes],
); );
const deleteSelected = useCallback(() => { const deleteSelected = useCallback(() => {
@@ -8309,11 +8469,12 @@ export function SketchForgeEditor({
edgeModifierKind={edgeModifier?.kind ?? null} edgeModifierKind={edgeModifier?.kind ?? null}
mirrorMode={mirrorMode} mirrorMode={mirrorMode}
sketchActive={sketchActive} sketchActive={sketchActive}
sketchOperation={sketchOperation}
sketchTool={sketchTool} sketchTool={sketchTool}
sketchCanUndo={sketchHistoryIndex > 0} sketchCanUndo={sketchHistoryIndex > 0}
sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1} sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1}
canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)} canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)}
onStartSketch={() => beginSketch()} onStartSketch={(operation) => beginSketch(operation)}
onEditSketch={beginSketchEdit} onEditSketch={beginSketchEdit}
onSketchTool={setActiveSketchTool} onSketchTool={setActiveSketchTool}
onSketchImage={() => { onSketchImage={() => {
@@ -8364,6 +8525,8 @@ export function SketchForgeEditor({
{toolbarMode === "sketch" && sketchActive ? ( {toolbarMode === "sketch" && sketchActive ? (
<SketchWorkspace <SketchWorkspace
profile={sketchProfile} profile={sketchProfile}
operation={sketchOperation}
revolvePreviewPositions={sketchRevolvePreview?.positions ?? null}
referenceShapes={shapes.filter((shape) => shape.id !== editingSketchShapeId)} referenceShapes={shapes.filter((shape) => shape.id !== editingSketchShapeId)}
tool={sketchTool} tool={sketchTool}
activePointId={sketchActivePointId} activePointId={sketchActivePointId}
@@ -8599,6 +8762,7 @@ function SecondaryToolbar({
hasSelection, hasSelection,
mirrorMode, mirrorMode,
sketchActive, sketchActive,
sketchOperation,
sketchTool, sketchTool,
sketchCanUndo, sketchCanUndo,
sketchCanRedo, sketchCanRedo,
@@ -8649,11 +8813,12 @@ function SecondaryToolbar({
hasSelection: boolean; hasSelection: boolean;
mirrorMode: boolean; mirrorMode: boolean;
sketchActive: boolean; sketchActive: boolean;
sketchOperation: SketchOperation;
sketchTool: SketchTool; sketchTool: SketchTool;
sketchCanUndo: boolean; sketchCanUndo: boolean;
sketchCanRedo: boolean; sketchCanRedo: boolean;
canEditSketch: boolean; canEditSketch: boolean;
onStartSketch: () => void; onStartSketch: (operation: SketchOperation) => void;
onEditSketch: () => void; onEditSketch: () => void;
onSketchTool: (tool: SketchTool) => void; onSketchTool: (tool: SketchTool) => void;
onSketchImage: () => void; onSketchImage: () => void;
@@ -8685,10 +8850,13 @@ function SecondaryToolbar({
onAddShape: (shape: ShapeAsset) => void; onAddShape: (shape: ShapeAsset) => void;
}) { }) {
const [shapesOpen, setShapesOpen] = useState(false); 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 touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null);
const suppressNextShapeClickRef = useRef(false); const suppressNextShapeClickRef = useRef(false);
const selectToolbarMode = (mode: "geometry" | "sketch") => { const selectToolbarMode = (mode: "geometry" | "sketch") => {
setShapesOpen(false); setShapesOpen(false);
setSketchCreateOpen(false);
onTopPanel(null); onTopPanel(null);
onToolbarModeChange(mode); onToolbarModeChange(mode);
}; };
@@ -8696,6 +8864,28 @@ function SecondaryToolbar({
onAddShape(shape); onAddShape(shape);
setShapesOpen(false); 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 = [ const leftTools = [
{ label: "Copy", icon: ToolbarCopyIcon, action: onCopy, enabled: hasSelection }, { label: "Copy", icon: ToolbarCopyIcon, action: onCopy, enabled: hasSelection },
{ label: "Paste", icon: ToolbarPasteIcon, action: onPaste, enabled: hasClipboard }, { label: "Paste", icon: ToolbarPasteIcon, action: onPaste, enabled: hasClipboard },
@@ -8945,7 +9135,7 @@ function SecondaryToolbar({
<div className="toolbar-section-tools"> <div className="toolbar-section-tools">
<button className="sketch-command-button primary" type="button" onClick={onSketchFinish}> <button className="sketch-command-button primary" type="button" onClick={onSketchFinish}>
<Check /> <Check />
<span>Finish sketch</span> <span>{sketchOperation === "revolve" ? "Finish revolve" : "Finish sketch"}</span>
</button> </button>
<button className="sketch-command-button cancel" type="button" onClick={onSketchCancel}> <button className="sketch-command-button cancel" type="button" onClick={onSketchCancel}>
<X /> <X />
@@ -8958,10 +9148,32 @@ function SecondaryToolbar({
<div className="toolbar-section sketch-start-section"> <div className="toolbar-section sketch-start-section">
<div className="toolbar-section-label">Create</div> <div className="toolbar-section-label">Create</div>
<div className="toolbar-section-tools"> <div className="toolbar-section-tools">
<button className="sketch-command-button primary" type="button" onClick={onStartSketch}> <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" /> <SketchReferenceIcon name="sketchTo3d" />
<span>Sketch to 3D</span> <span>Sketch to 3D</span>
<ToolbarCaretDownIcon className="sketch-create-menu-chevron" />
</button> </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}> <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" /> <SketchReferenceIcon name="editSketchTo3d" />
<span>Edit</span> <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 { 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 { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
import { SnapGridControl } from "@/components/workplane/ShapeInspector"; 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 { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; 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 SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure";
export type SketchSelection = export type SketchSelection =
@@ -18,6 +21,8 @@ export type SketchMeasurement = { start: SketchPoint; end: SketchPoint } | null;
type SketchWorkspaceProps = { type SketchWorkspaceProps = {
profile: SketchProfile; profile: SketchProfile;
operation?: SketchOperation;
revolvePreviewPositions?: number[] | null;
referenceShapes: WorkplaneShape[]; referenceShapes: WorkplaneShape[];
tool: SketchTool; tool: SketchTool;
activePointId: string | null; activePointId: string | null;
@@ -398,6 +403,8 @@ function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint
export function SketchWorkspace({ export function SketchWorkspace({
profile, profile,
operation = "extrude",
revolvePreviewPositions = null,
referenceShapes, referenceShapes,
tool, tool,
activePointId, activePointId,
@@ -680,7 +687,8 @@ export function SketchWorkspace({
return ( return (
<main className="sketch-workspace-stage"> <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"> <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="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 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} /> <rect className="sketch-plate-background" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} />
{workspace.showGrid ? ( {workspace.showGrid ? (
<g className="sketch-grid" pointerEvents="none"> <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} />)} {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 % 4 === 0 ? "major" : "minor"} key={`z-${z}`} x1={-workspace.width / 2} y1={z} x2={workspace.width / 2} y2={z} />)} {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> </g>
) : null} ) : null}
<g className="sketch-reference-images"> <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="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="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")} /> <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"> <SketchImagePositionField label="Position X" value={image.x} accuracy={accuracy} onChange={(x) => onUpdate({ x }, "Sketch image moved")} />
<span>Position X</span> <SketchImagePositionField label="Position Y" value={image.z} accuracy={accuracy} onChange={(z) => onUpdate({ z }, "Sketch image moved")} />
<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")}> <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} />} {image.lockAspect !== false ? <Link size={17} /> : <Link2Off size={17} />}
<span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span> <span>{image.lockAspect !== false ? "Aspect ratio locked" : "Aspect ratio unlocked"}</span>
@@ -1066,7 +1075,7 @@ function SketchImageRange({
const [draft, setDraft] = useState(formatDimension(safeValue, accuracy)); const [draft, setDraft] = useState(formatDimension(safeValue, accuracy));
useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]); useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]);
const commit = () => { const commit = () => {
const parsed = Number(draft); const parsed = parseMeasurementInput(draft);
onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max)); onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max));
}; };
const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100; const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100;
@@ -1076,10 +1085,8 @@ function SketchImageRange({
<div className="sketch-image-range-row"> <div className="sketch-image-range-row">
<input <input
className="sketch-image-number-input" className="sketch-image-number-input"
type="number" type="text"
min={min} inputMode="decimal"
max={max}
step={accuracy === 1 ? 0.1 : 0.01}
value={draft} value={draft}
onChange={(event) => setDraft(event.currentTarget.value)} onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit} onBlur={commit}
@@ -1091,3 +1098,39 @@ function SketchImageRange({
</label> </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 { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector"; import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; 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 { 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 { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import { sphereTessellation } from "@/lib/sphereTessellation"; import { sphereTessellation } from "@/lib/sphereTessellation";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol"; import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
@@ -68,6 +70,7 @@ const SHAPE_KINDS = new Set<ShapeAsset["kind"]>([
"halfSphere", "halfSphere",
"torus", "torus",
"tube", "tube",
"gear",
"ring", "ring",
"wedge", "wedge",
"polygon", "polygon",
@@ -566,6 +569,13 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string {
segments: shape.segments, segments: shape.segments,
topRadius: shape.topRadius, topRadius: shape.topRadius,
baseRadius: shape.baseRadius, 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, text: shape.text,
font: shape.font, font: shape.font,
mesh: [positions.length, positionSample], mesh: [positions.length, positionSample],
@@ -2743,7 +2753,7 @@ export function WorkplaneViewport({
setEditingDimension(null); setEditingDimension(null);
return; return;
} }
const value = Number.parseFloat(edit.value); const value = parseMeasurementInput(edit.value);
if (edit.axis === "elevation") { if (edit.axis === "elevation") {
if (Number.isFinite(value)) { if (Number.isFinite(value)) {
const frame = selectionFrameForShapes(shapesRef.current, selectedIdsRef.current); const frame = selectionFrameForShapes(shapesRef.current, selectedIdsRef.current);
@@ -2803,7 +2813,7 @@ export function WorkplaneViewport({
if (!edit) { if (!edit) {
return; return;
} }
const value = Number.parseFloat(edit.value); const value = parseMeasurementInput(edit.value);
if (Number.isFinite(value)) { if (Number.isFinite(value)) {
selectedIdsRef.current.forEach((id) => onUpdateShape(id, { ...rotationPatchForAxis(edit.axis, value), bakeTransform: true })); 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); points.push(...from, ...to);
}; };
const step = clamp(blockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE); const step = clamp(blockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
const majorEvery = 4;
for (const { coordinate: centeredX, index } of interiorWorkplaneGridCoordinates(width, step)) { 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]); pushLine(points, [centeredX, WORKPLANE_LINE_ELEVATION, -depth / 2], [centeredX, WORKPLANE_LINE_ELEVATION, depth / 2]);
} }
for (const { coordinate: centeredZ, index } of interiorWorkplaneGridCoordinates(depth, step)) { 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]); 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": case "tube":
addMesh(group, createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144), material, shape); addMesh(group, createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144), material, shape);
break; 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": case "wedge":
addMesh(group, createWedgeGeometry(width, height, depth), material, shape); addMesh(group, createWedgeGeometry(width, height, depth), material, shape);
break; break;
@@ -5334,7 +5357,7 @@ function addMesh(
const complexEdges = const complexEdges =
shape.kind === "mesh" || shape.kind === "mesh" ||
Boolean(shape.importedMesh) || 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 importedTriangleCount = shape.importedMesh?.triangleCount ?? 0;
const skipHeavyImportedEdges = Boolean(shape.importedMesh) && importedTriangleCount > IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT; const skipHeavyImportedEdges = Boolean(shape.importedMesh) && importedTriangleCount > IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT;
if ((group.userData.showEdges || complexEdges) && !skipHeavyImportedEdges) { if ((group.userData.showEdges || complexEdges) && !skipHeavyImportedEdges) {
@@ -2,7 +2,7 @@
import { useEffect, useState, type CSSProperties } from "react"; import { useEffect, useState, type CSSProperties } from "react";
import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react"; import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits"; import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes"; import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime"; import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -71,7 +71,7 @@ function EdgeModifierSlider({
const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue; const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => { const commitDraft = () => {
const next = Number(draft); const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue; const finiteNext = Number.isFinite(next) ? next : controlValue;
onChange(clamp(toModelValue(finiteNext), safeMin, safeMax)); onChange(clamp(toModelValue(finiteNext), safeMin, safeMax));
setEditing(false); setEditing(false);
@@ -89,10 +89,7 @@ function EdgeModifierSlider({
<span className="range-property-name">{label}</span> <span className="range-property-name">{label}</span>
<span className="range-value-control"> <span className="range-value-control">
<input <input
type="number" type="text"
min={controlMin}
max={controlMax}
step={controlStep}
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)} value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal" inputMode="decimal"
disabled={disabled} disabled={disabled}
@@ -1,11 +1,30 @@
"use client"; "use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen, Split } from "lucide-react"; 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 { 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 { 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 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; const MIN_SHAPE_SIZE = 0.01;
@@ -40,6 +59,11 @@ const SOLID_COLORS = [
"#111111", "#111111",
]; ];
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"]; 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 RangePropertyConfig = {
type?: "range"; type?: "range";
@@ -80,7 +104,7 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step
} }
function propertyUsesLengthUnit(label: string) { 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[] { 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" }); 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") { if (shape.kind === "box") {
return [ return [
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth }, { 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") { if (shape.kind === "text") {
return [ return [
{ {
@@ -222,14 +346,31 @@ export function ShapeInspector({
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color; const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked); const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate); 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 [propertiesOpen, setPropertiesOpen] = useState(true);
const [gearTeethOpen, setGearTeethOpen] = useState(true);
const [gearHelixOpen, setGearHelixOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false); const [colorOpen, setColorOpen] = useState(false);
const [minimized, setMinimized] = useState(false); const [minimized, setMinimized] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]); useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
useLayoutEffect(() => {
inspectorRef.current?.scrollTo({ top: 0, left: 0 });
}, [isSketchRevolve, shape.id]);
return ( 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"> <div className="shape-inspector-header">
<button <button
className="inspector-header-icon" className="inspector-header-icon"
@@ -334,7 +475,7 @@ export function ShapeInspector({
</button> </button>
) : null} ) : null}
<div className="property-card"> <div className={`property-card ${propertiesOpen ? "" : "collapsed"}`}>
<button <button
className="property-card-header" className="property-card-header"
type="button" type="button"
@@ -347,18 +488,55 @@ export function ShapeInspector({
</button> </button>
{propertiesOpen ? ( {propertiesOpen ? (
<div className="property-list" id={`properties-${shape.id}`}> <div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => { {gearType ? (
if (property.type === "text") { <GearTypeSelector
return <TextProperty key={property.label} {...property} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />; value={gearType}
} disabled={locked}
if (property.type === "select") { onChange={(gearType) => onUpdate({ gearType })}
return <SelectProperty key={property.label} {...property} disabled={locked} />; />
} ) : null}
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />; <ShapePropertyRows properties={primaryProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
})}
</div> </div>
) : null} ) : null}
</div> </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"> <div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} /> <SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div> </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({ export function SnapGridControl({
snap, snap,
snapOpen, snapOpen,
@@ -437,7 +637,7 @@ function RangeProperty({
}, [accuracy, controlStep, controlValue, editing]); }, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue; const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => { const commitDraft = () => {
const next = Number(draft); const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue; const finiteNext = Number.isFinite(next) ? next : controlValue;
const nextModelValue = toModelValue(finiteNext); const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max)); onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
@@ -455,10 +655,7 @@ function RangeProperty({
<span className="range-property-name">{label}</span> <span className="range-property-name">{label}</span>
<span className="range-value-control"> <span className="range-value-control">
<input <input
type="number" type="text"
min={controlMin}
max={allowsAboveSliderMax ? undefined : controlMax}
step={controlStep}
value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)} value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)}
disabled={disabled} disabled={disabled}
inputMode="decimal" inputMode="decimal"
@@ -533,3 +730,30 @@ function SelectProperty({ label, value, options, disabled, onChange }: SelectPro
</label> </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} style={{ "--overlay-x": `${editingDimension.x}px`, "--overlay-y": `${editingDimension.y}px` } as CSSProperties}
value={editingDimension.value} value={editingDimension.value}
autoFocus autoFocus
inputMode="decimal"
onPointerDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onEditingDimensionChange(event.target.value)} onChange={(event) => onEditingDimensionChange(event.target.value)}
onBlur={onCommitDimensionEdit} onBlur={onCommitDimensionEdit}
@@ -2,7 +2,7 @@
import { Grid3X3, Palette, Ruler, X } from "lucide-react"; import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useEffect, useState } from "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 { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -56,6 +56,7 @@ export function WorkspaceSettingsModal({
width: workspace.width.toFixed(workspace.accuracy), width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy), depth: workspace.depth.toFixed(workspace.accuracy),
})); }));
const [gridBlockSizeDraft, setGridBlockSizeDraft] = useState(() => workspace.gridBlockSize.toFixed(workspace.accuracy));
const scaleOptions = scaleOptionsForUnits(workspace.units); const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale); const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
useEffect(() => { useEffect(() => {
@@ -64,13 +65,16 @@ export function WorkspaceSettingsModal({
depth: workspace.depth.toFixed(workspace.accuracy), depth: workspace.depth.toFixed(workspace.accuracy),
}); });
}, [workspace.accuracy, workspace.depth, workspace.width]); }, [workspace.accuracy, workspace.depth, workspace.width]);
useEffect(() => {
setGridBlockSizeDraft(workspace.gridBlockSize.toFixed(workspace.accuracy));
}, [workspace.accuracy, workspace.gridBlockSize]);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => { const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false); setDefaultSaved(false);
const next = { ...workspace, ...patch }; const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) }); onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
}; };
const setDimension = (key: "width" | "depth", value: string) => { 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); const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
setDimensionDrafts((current) => ({ ...current, [key]: next.toFixed(workspace.accuracy) })); setDimensionDrafts((current) => ({ ...current, [key]: next.toFixed(workspace.accuracy) }));
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>); patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
@@ -87,7 +91,9 @@ export function WorkspaceSettingsModal({
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) }); patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
}; };
const setGridBlockSize = (value: string) => { 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 }); patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
}; };
@@ -201,11 +207,9 @@ export function WorkspaceSettingsModal({
<label> <label>
<span>Width</span> <span>Width</span>
<input <input
type="number" type="text"
inputMode="decimal"
value={dimensionDrafts.width} value={dimensionDrafts.width}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => { onChange={(event) => {
const value = event.currentTarget.value; const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, width: value })); setDimensionDrafts((current) => ({ ...current, width: value }));
@@ -219,11 +223,9 @@ export function WorkspaceSettingsModal({
<label> <label>
<span>Length</span> <span>Length</span>
<input <input
type="number" type="text"
inputMode="decimal"
value={dimensionDrafts.depth} value={dimensionDrafts.depth}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => { onChange={(event) => {
const value = event.currentTarget.value; const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, depth: value })); setDimensionDrafts((current) => ({ ...current, depth: value }));
@@ -241,12 +243,14 @@ export function WorkspaceSettingsModal({
<label> <label>
<span>Block size</span> <span>Block size</span>
<input <input
type="number" type="text"
value={workspace.gridBlockSize.toFixed(workspace.accuracy)} inputMode="decimal"
min={MIN_GRID_BLOCK_SIZE} value={gridBlockSizeDraft}
max={MAX_GRID_BLOCK_SIZE} onChange={(event) => setGridBlockSizeDraft(event.currentTarget.value)}
step={0.5} onBlur={(event) => setGridBlockSize(event.currentTarget.value)}
onChange={(event) => setGridBlockSize(event.currentTarget.value)} onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/> />
</label> </label>
</div> </div>
+240
View File
@@ -0,0 +1,240 @@
import * as THREE from "three";
import { toCreasedNormals } from "three/examples/jsm/utils/BufferGeometryUtils.js";
import type { GearType, WorkplaneShape } from "@/types/sketchforge";
export const DEFAULT_GEAR_TEETH = 12;
export const DEFAULT_GEAR_TOOTH_SIZE = 2.5;
export const DEFAULT_GEAR_CENTER_HOLE_SIZE = 6;
export const DEFAULT_GEAR_TYPE: GearType = "spur";
export const DEFAULT_GEAR_HELIX_ANGLE = 22.5;
export const DEFAULT_GEAR_HELIX_QUALITY = 16;
export const MIN_GEAR_TEETH = 6;
export const MAX_GEAR_TEETH = 64;
export const MIN_GEAR_HELIX_ANGLE = -45;
export const MAX_GEAR_HELIX_ANGLE = 45;
export const MIN_GEAR_HELIX_QUALITY = 4;
export const MAX_GEAR_HELIX_QUALITY = 32;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
export function normalizeGearTeeth(value?: number) {
return clamp(Math.round(Number.isFinite(value) ? value as number : DEFAULT_GEAR_TEETH), MIN_GEAR_TEETH, MAX_GEAR_TEETH);
}
export function normalizeGearType(value?: string): GearType {
return value === "helical" || value === "bevel" ? value : DEFAULT_GEAR_TYPE;
}
export function normalizeGearToothSize(value: number | undefined, width: number, depth: number) {
const maximum = Math.max(0.2, Math.min(width, depth) * 0.22);
return clamp(Number.isFinite(value) ? value as number : DEFAULT_GEAR_TOOTH_SIZE, 0.2, maximum);
}
export function gearToothPitch(width: number, depth: number, teeth?: number) {
return Math.PI * Math.max(0.01, Math.min(width, depth)) / normalizeGearTeeth(teeth);
}
export function normalizeGearToothWidth(value: number | undefined, width: number, depth: number, teeth?: number) {
const pitch = gearToothPitch(width, depth, teeth);
return clamp(Number.isFinite(value) ? value as number : pitch * 0.54, pitch * 0.12, pitch * 0.82);
}
export function gearCenterHoleLimits(width: number, depth: number, toothSize?: number) {
const outerRadius = Math.max(0.005, Math.min(width, depth) / 2);
const normalizedToothSize = normalizeGearToothSize(toothSize, width, depth);
const rootRadius = Math.max(outerRadius * 0.34, outerRadius - normalizedToothSize);
const max = Math.max(0.01, rootRadius * 1.5);
return { min: 0, max };
}
export function normalizeGearCenterHoleSize(value: number | undefined, width: number, depth: number, toothSize?: number) {
const limits = gearCenterHoleLimits(width, depth, toothSize);
const outerRadius = Math.max(0.005, Math.min(width, depth) / 2);
const normalizedToothSize = normalizeGearToothSize(toothSize, width, depth);
const rootRadius = Math.max(outerRadius * 0.34, outerRadius - normalizedToothSize);
const defaultSize = Math.min(outerRadius * 0.4, rootRadius * 1.1);
return clamp(Number.isFinite(value) ? value as number : defaultSize, limits.min, limits.max);
}
export function normalizeGearHelixAngle(value?: number) {
return clamp(
Number.isFinite(value) ? value as number : DEFAULT_GEAR_HELIX_ANGLE,
MIN_GEAR_HELIX_ANGLE,
MAX_GEAR_HELIX_ANGLE,
);
}
export function normalizeGearHelixQuality(value?: number) {
return clamp(
Math.round(Number.isFinite(value) ? value as number : DEFAULT_GEAR_HELIX_QUALITY),
MIN_GEAR_HELIX_QUALITY,
MAX_GEAR_HELIX_QUALITY,
);
}
export function gearSettings(shape: Pick<WorkplaneShape, "width" | "depth" | "teeth" | "toothSize" | "toothWidth" | "centerHoleSize" | "gearType" | "helixAngle" | "helixQuality">) {
return {
teeth: normalizeGearTeeth(shape.teeth),
toothSize: normalizeGearToothSize(shape.toothSize, shape.width, shape.depth),
toothWidth: normalizeGearToothWidth(shape.toothWidth, shape.width, shape.depth, shape.teeth),
centerHoleSize: normalizeGearCenterHoleSize(shape.centerHoleSize, shape.width, shape.depth, shape.toothSize),
gearType: normalizeGearType(shape.gearType),
helixAngle: normalizeGearHelixAngle(shape.helixAngle),
helixQuality: normalizeGearHelixQuality(shape.helixQuality),
};
}
type GearGeometryOptions = {
width: number;
depth: number;
height: number;
teeth?: number;
toothSize?: number;
toothWidth?: number;
centerHoleSize?: number;
gearType?: GearType;
helixAngle?: number;
helixQuality?: number;
};
export function createGearGeometry({
width,
depth,
height,
teeth: requestedTeeth,
toothSize: requestedToothSize,
toothWidth: requestedToothWidth,
centerHoleSize: requestedCenterHoleSize,
gearType: requestedType,
helixAngle: requestedHelixAngle,
helixQuality: requestedHelixQuality,
}: GearGeometryOptions) {
const safeWidth = Math.max(0.01, width);
const safeDepth = Math.max(0.01, depth);
const safeHeight = Math.max(0.01, height);
const teeth = normalizeGearTeeth(requestedTeeth);
const toothSize = normalizeGearToothSize(requestedToothSize, safeWidth, safeDepth);
const toothPitch = gearToothPitch(safeWidth, safeDepth, teeth);
const toothWidth = normalizeGearToothWidth(requestedToothWidth, safeWidth, safeDepth, teeth);
const toothFraction = toothWidth / toothPitch;
const centerHoleSize = normalizeGearCenterHoleSize(requestedCenterHoleSize, safeWidth, safeDepth, toothSize);
const hasCenterHole = centerHoleSize > 0;
const gearType = normalizeGearType(requestedType);
const helixAngle = normalizeGearHelixAngle(requestedHelixAngle);
const helixQuality = normalizeGearHelixQuality(requestedHelixQuality);
const outlineCount = teeth * 4;
const ringCount = gearType === "helical" ? helixQuality : 2;
const twist = gearType === "helical" ? THREE.MathUtils.degToRad(helixAngle) : 0;
const topScale = gearType === "bevel" ? 0.68 : 1;
const outerX = safeWidth / 2;
const outerZ = safeDepth / 2;
const rootX = Math.max(outerX * 0.34, outerX - toothSize);
const rootZ = Math.max(outerZ * 0.34, outerZ - toothSize);
const boreX = centerHoleSize / 2;
const boreZ = centerHoleSize / 2;
const toothPhases = [0.05, (1 - toothFraction) / 2, (1 + toothFraction) / 2, 0.95] as const;
const positions: number[] = [];
const indices: number[] = [];
const outerIndex = (ring: number, point: number) => ring * outlineCount * 2 + point;
const innerIndex = (ring: number, point: number) => ring * outlineCount * 2 + outlineCount + point;
for (let ring = 0; ring < ringCount; ring += 1) {
const progress = ring / (ringCount - 1);
const y = progress * safeHeight;
const ringTwist = progress * twist;
const scale = 1 + (topScale - 1) * progress;
for (let tooth = 0; tooth < teeth; tooth += 1) {
for (let phaseIndex = 0; phaseIndex < toothPhases.length; phaseIndex += 1) {
const phase = toothPhases[phaseIndex];
const angle = ((tooth + phase) / teeth) * Math.PI * 2 + ringTwist;
const isOuter = phaseIndex === 1 || phaseIndex === 2;
const radiusX = (isOuter ? outerX : rootX) * scale;
const radiusZ = (isOuter ? outerZ : rootZ) * scale;
positions.push(Math.cos(angle) * radiusX, y, Math.sin(angle) * radiusZ);
}
}
for (let point = 0; point < outlineCount; point += 1) {
const angle = (point / outlineCount) * Math.PI * 2;
positions.push(Math.cos(angle) * boreX, y, Math.sin(angle) * boreZ);
}
}
let outlineMinX = Number.POSITIVE_INFINITY;
let outlineMaxX = Number.NEGATIVE_INFINITY;
let outlineMinZ = Number.POSITIVE_INFINITY;
let outlineMaxZ = Number.NEGATIVE_INFINITY;
for (let ring = 0; ring < ringCount; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const offset = outerIndex(ring, point) * 3;
outlineMinX = Math.min(outlineMinX, positions[offset]);
outlineMaxX = Math.max(outlineMaxX, positions[offset]);
outlineMinZ = Math.min(outlineMinZ, positions[offset + 2]);
outlineMaxZ = Math.max(outlineMaxZ, positions[offset + 2]);
}
}
const outlineScaleX = safeWidth / Math.max(Number.EPSILON, outlineMaxX - outlineMinX);
const outlineScaleZ = safeDepth / Math.max(Number.EPSILON, outlineMaxZ - outlineMinZ);
for (let ring = 0; ring < ringCount; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const offset = outerIndex(ring, point) * 3;
positions[offset] *= outlineScaleX;
positions[offset + 2] *= outlineScaleZ;
}
}
for (let ring = 0; ring < ringCount - 1; ring += 1) {
for (let point = 0; point < outlineCount; point += 1) {
const next = (point + 1) % outlineCount;
const outerBottom = outerIndex(ring, point);
const outerNextBottom = outerIndex(ring, next);
const outerTop = outerIndex(ring + 1, point);
const outerNextTop = outerIndex(ring + 1, next);
indices.push(outerBottom, outerTop, outerNextTop, outerBottom, outerNextTop, outerNextBottom);
if (hasCenterHole) {
const innerBottom = innerIndex(ring, point);
const innerNextBottom = innerIndex(ring, next);
const innerTop = innerIndex(ring + 1, point);
const innerNextTop = innerIndex(ring + 1, next);
indices.push(innerBottom, innerNextBottom, innerNextTop, innerBottom, innerNextTop, innerTop);
}
}
}
const topRing = ringCount - 1;
for (let point = 0; point < outlineCount; point += 1) {
const next = (point + 1) % outlineCount;
const bottomOuter = outerIndex(0, point);
const bottomOuterNext = outerIndex(0, next);
const bottomInner = innerIndex(0, point);
const bottomInnerNext = innerIndex(0, next);
if (hasCenterHole) {
indices.push(bottomOuter, bottomOuterNext, bottomInnerNext, bottomOuter, bottomInnerNext, bottomInner);
} else {
indices.push(bottomOuter, bottomOuterNext, innerIndex(0, 0));
}
const topOuter = outerIndex(topRing, point);
const topOuterNext = outerIndex(topRing, next);
const topInner = innerIndex(topRing, point);
const topInnerNext = innerIndex(topRing, next);
if (hasCenterHole) {
indices.push(topOuter, topInner, topInnerNext, topOuter, topInnerNext, topOuterNext);
} else {
indices.push(topOuter, innerIndex(topRing, 0), topOuterNext);
}
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
indexed.setIndex(indices);
const geometry = toCreasedNormals(indexed, THREE.MathUtils.degToRad(12));
indexed.dispose();
geometry.computeBoundingBox();
return geometry;
}
+20
View File
@@ -75,6 +75,26 @@ export function displayStepFromMillimeters(step: number, workspace: Pick<Workpla
return step / lengthDisplayUnit(workspace).millimetersPerUnit; return step / lengthDisplayUnit(workspace).millimetersPerUnit;
} }
export function parseMeasurementInput(value: string | number) {
if (typeof value === "number") return Number.isFinite(value) ? value : Number.NaN;
const compact = value.trim().replace(/[\s\u00a0]/g, "");
if (!compact) return Number.NaN;
const commaIndex = compact.lastIndexOf(",");
const dotIndex = compact.lastIndexOf(".");
let normalized = compact;
if (commaIndex >= 0 && dotIndex >= 0) {
normalized = commaIndex > dotIndex
? compact.replace(/\./g, "").replace(",", ".")
: compact.replace(/,/g, "");
} else if (commaIndex >= 0) {
normalized = compact.replace(",", ".");
}
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : Number.NaN;
}
export function formatMeasurementNumber(value: number, accuracy: MeasurementAccuracy, _step?: number) { export function formatMeasurementNumber(value: number, accuracy: MeasurementAccuracy, _step?: number) {
let decimals = accuracy; let decimals = accuracy;
while (decimals < 6 && value !== 0 && Math.abs(value) < 0.5 * 10 ** -decimals) { while (decimals < 6 && value !== 0 && Math.abs(value) < 0.5 * 10 ** -decimals) {
+21 -3
View File
@@ -1,5 +1,6 @@
import { canonicalizeShape } from "@/lib/workplaneShapes"; import { canonicalizeShape } from "@/lib/workplaneShapes";
import { createLocalId } from "@/lib/localIds"; import { createLocalId } from "@/lib/localIds";
import { DEFAULT_GEAR_CENTER_HOLE_SIZE, DEFAULT_GEAR_HELIX_ANGLE, DEFAULT_GEAR_HELIX_QUALITY, DEFAULT_GEAR_TEETH, DEFAULT_GEAR_TOOTH_SIZE, DEFAULT_GEAR_TYPE } from "@/lib/gearGeometry";
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge"; import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string }; export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
@@ -16,6 +17,7 @@ export const toolbarShapeAssets: ToolbarShapeAsset[] = [
{ id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" }, { id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" },
{ id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" }, { id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" },
{ id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" }, { id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" },
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
]; ];
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape { export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
@@ -45,10 +47,20 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
segments: shape.segments, segments: shape.segments,
topRadius: shape.topRadius, topRadius: shape.topRadius,
baseRadius: shape.baseRadius, 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, text: shape.text,
font: shape.font, font: shape.font,
importedMesh: shape.importedMesh, importedMesh: shape.importedMesh,
imagePlate: shape.imagePlate, imagePlate: shape.imagePlate,
sketchProfile: shape.sketchProfile,
sketchOperation: shape.sketchOperation,
sketchRevolve: shape.sketchRevolve,
groupedShapes: shape.groupedShapes, groupedShapes: shape.groupedShapes,
groupedBaseWidth: shape.groupedBaseWidth, groupedBaseWidth: shape.groupedBaseWidth,
groupedBaseDepth: shape.groupedBaseDepth, groupedBaseDepth: shape.groupedBaseDepth,
@@ -61,9 +73,9 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape { export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere"; const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text"; const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text" || asset.kind === "gear";
const size = roundProfile ? 22 : 20; const size = asset.kind === "gear" ? 30 : roundProfile ? 22 : 20;
const height = asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20; const height = asset.kind === "gear" ? 6 : asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
const width = asset.kind === "text" ? 86 : size; const width = asset.kind === "text" ? 86 : size;
const depth = asset.kind === "text" ? 28 : size; const depth = asset.kind === "text" ? 28 : size;
@@ -92,6 +104,12 @@ export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: nu
segments: asset.kind === "cylinder" ? 1 : undefined, segments: asset.kind === "cylinder" ? 1 : undefined,
topRadius: asset.kind === "cone" ? 0 : undefined, topRadius: asset.kind === "cone" ? 0 : undefined,
baseRadius: asset.kind === "cone" ? size / 2 : undefined, baseRadius: asset.kind === "cone" ? size / 2 : undefined,
teeth: asset.kind === "gear" ? DEFAULT_GEAR_TEETH : undefined,
toothSize: asset.kind === "gear" ? DEFAULT_GEAR_TOOTH_SIZE : undefined,
centerHoleSize: asset.kind === "gear" ? DEFAULT_GEAR_CENTER_HOLE_SIZE : undefined,
gearType: asset.kind === "gear" ? DEFAULT_GEAR_TYPE : undefined,
helixAngle: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_ANGLE : undefined,
helixQuality: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_QUALITY : undefined,
locked: false, locked: false,
hidden: false, hidden: false,
}; };
+320
View File
@@ -0,0 +1,320 @@
import type { ManifoldToplevel } from "manifold-3d";
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
startAngle: 0,
sweepAngle: 360,
sides: 64,
quality: 6,
thickness: 1,
};
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
type OrderedPath = { steps: OrderedStep[]; closed: boolean };
type Point2 = [number, number];
type SampledPoint = { x: number; z: number };
export type SketchRevolveMesh = {
positions: number[];
width: number;
depth: number;
height: number;
triangleCount: number;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function finiteOr(value: number | undefined, fallback: number) {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
export function normalizeSketchRevolveSettings(settings?: Partial<SketchRevolveSettings>): SketchRevolveSettings {
const rawSweep = clamp(finiteOr(settings?.sweepAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.sweepAngle), -360, 360);
const sweepAngle = Math.abs(rawSweep) < 1 ? (rawSweep < 0 ? -1 : 1) : rawSweep;
return {
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
sweepAngle,
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, 128)),
quality: Math.round(clamp(finiteOr(settings?.quality, DEFAULT_SKETCH_REVOLVE_SETTINGS.quality), 1, 10)),
thickness: clamp(finiteOr(settings?.thickness, DEFAULT_SKETCH_REVOLVE_SETTINGS.thickness), 0.1, 20),
};
}
function orderedPaths(profile: SketchProfile): OrderedPath[] {
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 validSegments = 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(validSegments.map((segment) => segment.id));
const paths: OrderedPath[] = [];
while (unvisited.size > 0) {
const seed = validSegments.find((segment) => unvisited.has(segment.id));
if (!seed) break;
const componentIds = new Set<string>();
const queue = [seed.startId, seed.endId];
while (queue.length > 0) {
const id = queue.pop();
if (!id || componentIds.has(id)) continue;
componentIds.add(id);
adjacency.get(id)?.forEach((entry) => queue.push(entry.pointId));
}
const startId = [...componentIds].find((id) => (adjacency.get(id)?.filter((entry) => unvisited.has(entry.segment.id)).length ?? 0) === 1) ?? seed.startId;
const steps: OrderedStep[] = [];
let currentId = startId;
for (let guard = 0; guard <= validSegments.length; guard += 1) {
const edge = adjacency.get(currentId)?.find((entry) => unvisited.has(entry.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;
}
if (steps.length > 0) paths.push({ steps, closed: currentId === startId && steps.length >= 3 });
}
return paths;
}
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 samplePath(path: OrderedPath, quality: number) {
const first = path.steps[0]?.from;
if (!first) return [];
const sampled = [{ x: first.x, z: first.z }];
const curveSamples = 4 + quality * 6;
path.steps.forEach(({ segment, from, to }) => {
const forward = segment.startId === from.id;
const firstControl = forward ? from.handleOut : from.handleIn;
const secondControl = forward ? to.handleIn : to.handleOut;
if (segment.kind !== "line" && firstControl && secondControl) {
for (let index = 1; index <= curveSamples; index += 1) {
sampled.push(cubicPoint(from, firstControl, secondControl, to, index / curveSamples));
}
} else {
sampled.push({ x: to.x, z: to.z });
}
});
if (path.closed && sampled.length > 1) sampled.pop();
return sampled;
}
function compactSampledPath(points: SampledPoint[]) {
const compact: SampledPoint[] = [];
points.forEach((point) => {
const previous = compact[compact.length - 1];
if (!previous || Math.hypot(point.x - previous.x, point.z - previous.z) > 1e-7) compact.push(point);
});
if (compact.length > 2) {
const first = compact[0];
const last = compact[compact.length - 1];
if (Math.hypot(first.x - last.x, first.z - last.z) <= 1e-7) compact.pop();
}
return compact;
}
function axisIntersection(from: SampledPoint, to: SampledPoint): SampledPoint {
const deltaX = to.x - from.x;
const amount = Math.abs(deltaX) <= 1e-12 ? 0 : clamp(-from.x / deltaX, 0, 1);
return { x: 0, z: from.z + (to.z - from.z) * amount };
}
function clipClosedPathToRevolveSide(points: SampledPoint[]) {
if (points.length < 3) return [];
const clipped: SampledPoint[] = [];
for (let index = 0; index < points.length; index += 1) {
const from = points[index];
const to = points[(index + 1) % points.length];
const fromInside = from.x <= 0;
const toInside = to.x <= 0;
if (fromInside && toInside) {
clipped.push(to);
} else if (fromInside) {
clipped.push(axisIntersection(from, to));
} else if (toInside) {
clipped.push(axisIntersection(from, to), to);
}
}
return compactSampledPath(clipped);
}
function clipOpenPathToRevolveSide(points: SampledPoint[]) {
const paths: SampledPoint[][] = [];
let current: SampledPoint[] = [];
const finishCurrent = () => {
const compact = compactSampledPath(current);
if (compact.length >= 2) paths.push(compact);
current = [];
};
for (let index = 0; index < points.length - 1; index += 1) {
const from = points[index];
const to = points[index + 1];
const fromInside = from.x <= 0;
const toInside = to.x <= 0;
if (fromInside && toInside) {
if (current.length === 0) current.push(from);
current.push(to);
} else if (fromInside) {
if (current.length === 0) current.push(from);
current.push(axisIntersection(from, to));
finishCurrent();
} else if (toInside) {
current = [axisIntersection(from, to), to];
}
}
finishCurrent();
return paths;
}
function distance(a: Point2, b: Point2) {
return Math.hypot(b[0] - a[0], b[1] - a[1]);
}
function compactPolygon(points: Point2[]) {
const compact: Point2[] = [];
points.forEach((point) => {
if (!compact.length || distance(compact[compact.length - 1], point) > 1e-7) compact.push(point);
});
if (compact.length > 2 && distance(compact[0], compact[compact.length - 1]) <= 1e-7) compact.pop();
return compact;
}
function strokeOpenPath(points: Point2[], thickness: number) {
if (points.length < 2) return [];
const half = thickness / 2;
const normals: Point2[] = [];
for (let index = 0; index < points.length - 1; index += 1) {
const dx = points[index + 1][0] - points[index][0];
const dy = points[index + 1][1] - points[index][1];
const length = Math.hypot(dx, dy);
normals.push(length > 1e-8 ? [-dy / length, dx / length] : [0, 0]);
}
const offsetAt = (index: number): Point2 => {
const previous = normals[Math.max(0, index - 1)];
const next = normals[Math.min(normals.length - 1, index)];
const sumX = previous[0] + next[0];
const sumY = previous[1] + next[1];
const sumLength = Math.hypot(sumX, sumY);
if (sumLength <= 1e-8) return [next[0] * half, next[1] * half];
const unit: Point2 = [sumX / sumLength, sumY / sumLength];
const projection = Math.abs(unit[0] * next[0] + unit[1] * next[1]);
const miter = Math.min(half * 4, half / Math.max(0.25, projection));
return [unit[0] * miter, unit[1] * miter];
};
const left: Point2[] = [];
const right: Point2[] = [];
points.forEach((point, index) => {
const offset = offsetAt(index);
left.push([point[0] + offset[0], point[1] + offset[1]]);
right.push([point[0] - offset[0], point[1] - offset[1]]);
});
return compactPolygon([...left, ...right.reverse()]);
}
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial<SketchRevolveSettings>) {
const normalized = normalizeSketchRevolveSettings(settings);
const paths = orderedPaths(profile).flatMap((path) => {
const sampled = samplePath(path, normalized.quality);
if (path.closed) {
const clipped = clipClosedPathToRevolveSide(sampled);
return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
}
return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
});
if (paths.length === 0) return [];
const maxZ = Math.max(...paths.flatMap((entry) => entry.points.map((point) => point.z)));
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
return paths.flatMap(({ closed, points }) => {
const sectionPoints = compactPolygon(points.map(toSectionPoint));
const polygon = closed ? sectionPoints : strokeOpenPath(sectionPoints, normalized.thickness).map((point) => [Math.max(0, point[0]), point[1]] as Point2);
return polygon.length >= 3 ? [compactPolygon(polygon)] : [];
});
}
function manifoldMeshPositions(mesh: InstanceType<ManifoldToplevel["Mesh"]>) {
const positions: number[] = [];
for (let index = 0; index < mesh.triVerts.length; index += 1) {
const offset = mesh.triVerts[index] * mesh.numProp;
positions.push(mesh.vertProperties[offset], mesh.vertProperties[offset + 1], mesh.vertProperties[offset + 2]);
}
return positions;
}
function dispose(value: unknown) {
(value as { delete?: () => void } | null)?.delete?.();
}
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
const settings = normalizeSketchRevolveSettings(requestedSettings);
const polygons = sketchProfileToRevolvePolygons(profile, settings);
if (polygons.length === 0) throw new Error("Draw at least one connected profile on the left side of the revolve axis");
const disposable: unknown[] = [];
try {
const section = new runtime.CrossSection(polygons, "EvenOdd");
disposable.push(section);
const scale = polygons.reduce((largest, polygon) => polygon.reduce((current, point) => Math.max(current, Math.abs(point[0]), Math.abs(point[1])), largest), 1);
const simplified = section.simplify(Math.max(1e-7, scale * 1e-8));
disposable.push(simplified);
if (simplified.toPolygons().length === 0) throw new Error("The revolve profile has no filled area");
const sweep = Math.abs(settings.sweepAngle);
const solid = simplified.revolve(settings.sides, sweep);
disposable.push(solid);
const rotation = settings.sweepAngle < 0 ? settings.startAngle + settings.sweepAngle : settings.startAngle;
const revolved = Math.abs(rotation) > 1e-8 ? solid.rotate([0, 0, rotation]) : solid;
if (revolved !== solid) disposable.push(revolved);
if (revolved.status() !== "NoError" || revolved.numTri() < 1) throw new Error("The profile could not be revolved into a valid solid");
const manifoldPositions = manifoldMeshPositions(revolved.getMesh());
const positions = new Array<number>(manifoldPositions.length);
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let index = 0; index + 2 < manifoldPositions.length; index += 3) {
const x = manifoldPositions[index];
const y = manifoldPositions[index + 2];
const z = -manifoldPositions[index + 1];
positions[index] = x;
positions[index + 1] = y;
positions[index + 2] = z;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
}
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
for (let index = 0; index + 2 < positions.length; index += 3) {
positions[index] -= centerX;
positions[index + 1] -= minY;
positions[index + 2] -= centerZ;
}
return {
positions,
width: Math.max(0.01, maxX - minX),
depth: Math.max(0.01, maxZ - minZ),
height: Math.max(0.01, maxY - minY),
triangleCount: Math.floor(positions.length / 9),
};
} finally {
[...new Set(disposable)].reverse().forEach(dispose);
}
}
+55 -10
View File
@@ -5,12 +5,12 @@ import { canonicalizeShape } from "@/lib/workplaneShapes";
import { importedShapeFromStl } from "@/lib/stlImport"; import { importedShapeFromStl } from "@/lib/stlImport";
import { importedShapeFromSvg } from "@/lib/svgImport"; import { importedShapeFromSvg } from "@/lib/svgImport";
import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import { normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, SketchRevolveSettings, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const SKF_SCHEMA_ID = "com.sketchforge.project"; export const SKF_SCHEMA_ID = "com.sketchforge.project";
export const SKF_FORMAT_VERSION = 1; export const SKF_FORMAT_VERSION = 1;
export const SKF_MINIMUM_READER_VERSION = 1; export const SKF_MINIMUM_READER_VERSION = 1;
export const SKF_CREATED_WITH_VERSION = "0.6.0"; export const SKF_CREATED_WITH_VERSION = "0.7.0";
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip"; export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
export const SKF_LIMITS = { export const SKF_LIMITS = {
@@ -27,11 +27,11 @@ export const SKF_LIMITS = {
const SHAPE_KINDS = new Set([ const SHAPE_KINDS = new Set([
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof", "box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
"halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron", "mesh", "halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron", "mesh",
]); ]);
const FEATURE_TYPES = new Set([ const FEATURE_TYPES = new Set([
"group", "boolean-subtraction", "boolean-intersection", "mirror", "sketch-extrusion", "fillet", "chamfer", "group", "boolean-subtraction", "boolean-intersection", "mirror", "sketch-extrusion", "sketch-revolve", "fillet", "chamfer",
]); ]);
type SkfAssetKind = "source" | "derived-mesh" | "brep" | "image"; type SkfAssetKind = "source" | "derived-mesh" | "brep" | "image";
@@ -110,7 +110,7 @@ export type SkfProjectDocumentV1 = {
entries: Array<{ stateId: string; selectedObjectIds: string[] }>; entries: Array<{ stateId: string; selectedObjectIds: string[] }>;
index: number; index: number;
}; };
sketches: Array<{ id: string; nodeId: string; objectId: string; extrusionDepth: number }>; sketches: Array<{ id: string; nodeId: string; objectId: string; operation?: SketchOperation; extrusionDepth: number; revolve?: SketchRevolveSettings }>;
features: SkfFeatureV1[]; features: SkfFeatureV1[];
groups: Array<{ id: string; nodeId: string; objectId: string; memberNodeIds: string[]; operation: string }>; groups: Array<{ id: string; nodeId: string; objectId: string; memberNodeIds: string[]; operation: string }>;
workplanes: Array<{ id: string; kind: "base" | "offset"; elevation: number }>; workplanes: Array<{ id: string; kind: "base" | "offset"; elevation: number }>;
@@ -451,6 +451,8 @@ async function serializeShapeNode(
const objectType = groupedShapeNodeIds.length const objectType = groupedShapeNodeIds.length
? "group" ? "group"
: sketchProfile
? "sketch"
: importedReference : importedReference
? "imported" ? "imported"
: shape.kind === "sketch" : shape.kind === "sketch"
@@ -511,17 +513,28 @@ function activeProjectIndexes(state: SkfStateV1) {
if (!node) return; if (!node) return;
(node.groupedShapeNodeIds ?? []).forEach(visit); (node.groupedShapeNodeIds ?? []).forEach(visit);
let previous: string | undefined; let previous: string | undefined;
if (node.definition.sketchProfile && node.definition.kind === "sketch") { if (node.definition.sketchProfile) {
const featureId = `feature/${safeNodeToken(node.nodeId)}/sketch-extrusion`; const operation = node.definition.sketchOperation === "revolve" ? "revolve" : "extrude";
const featureType = operation === "revolve" ? "sketch-revolve" : "sketch-extrusion";
const featureId = `feature/${safeNodeToken(node.nodeId)}/${featureType}`;
features.push({ features.push({
id: featureId, id: featureId,
type: "sketch-extrusion", type: featureType,
outputObjectId: node.objectId, outputObjectId: node.objectId,
inputObjectIds: [], inputObjectIds: [],
dependsOnFeatureIds: [], dependsOnFeatureIds: [],
parameters: { depth: node.definition.height, direction: "positive-y", mode: "create" }, parameters: operation === "revolve"
? { ...(node.definition.sketchRevolve as Record<string, unknown> | undefined), axis: "vertical-sketch-axis", mode: "create" }
: { depth: node.definition.height, direction: "positive-y", mode: "create" },
});
sketches.push({
id: `sketch/${safeNodeToken(node.objectId)}`,
nodeId: node.nodeId,
objectId: node.objectId,
operation,
extrusionDepth: operation === "extrude" ? Number(node.definition.height) : 0,
...(operation === "revolve" && node.definition.sketchRevolve ? { revolve: node.definition.sketchRevolve as SketchRevolveSettings } : {}),
}); });
sketches.push({ id: `sketch/${safeNodeToken(node.objectId)}`, nodeId: node.nodeId, objectId: node.objectId, extrusionDepth: Number(node.definition.height) });
previous = featureId; previous = featureId;
} }
if (node.groupedShapeNodeIds?.length) { if (node.groupedShapeNodeIds?.length) {
@@ -776,6 +789,38 @@ function validateShapeDefinition(definition: Record<string, unknown>, label: str
throw new Error(`${label} contains inline package-only geometry fields`); throw new Error(`${label} contains inline package-only geometry fields`);
} }
if (definition.sketchProfile) validateSketchProfile(definition.sketchProfile, `${label}.sketchProfile`); if (definition.sketchProfile) validateSketchProfile(definition.sketchProfile, `${label}.sketchProfile`);
if (definition.sketchOperation !== undefined && definition.sketchOperation !== "extrude" && definition.sketchOperation !== "revolve") {
throw new Error(`${label}.sketchOperation is invalid`);
}
if (definition.sketchRevolve !== undefined) {
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
["startAngle", "sweepAngle", "sides", "quality", "thickness"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
}
if (kind === "gear") {
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
if (!Number.isInteger(teeth) || teeth < 6 || teeth > 64) throw new Error(`${label}.teeth is outside the supported range`);
const toothSize = finiteNumber(definition.toothSize, `${label}.toothSize`);
if (toothSize <= 0) throw new Error(`${label}.toothSize must be positive`);
if (definition.toothWidth !== undefined) {
const toothWidth = finiteNumber(definition.toothWidth, `${label}.toothWidth`);
if (toothWidth <= 0) throw new Error(`${label}.toothWidth must be positive`);
}
if (definition.centerHoleSize !== undefined) {
const centerHoleSize = finiteNumber(definition.centerHoleSize, `${label}.centerHoleSize`);
if (centerHoleSize < 0) throw new Error(`${label}.centerHoleSize cannot be negative`);
}
if (!["spur", "helical", "bevel"].includes(definition.gearType as string)) throw new Error(`${label}.gearType is invalid`);
if (definition.helixAngle !== undefined) {
const helixAngle = finiteNumber(definition.helixAngle, `${label}.helixAngle`);
if (helixAngle < -45 || helixAngle > 45) throw new Error(`${label}.helixAngle is outside the supported range`);
}
if (definition.helixQuality !== undefined) {
const helixQuality = finiteNumber(definition.helixQuality, `${label}.helixQuality`);
if (!Number.isInteger(helixQuality) || helixQuality < 4 || helixQuality > 32) {
throw new Error(`${label}.helixQuality is outside the supported range`);
}
}
}
return id; return id;
} }
+1
View File
@@ -1,6 +1,7 @@
const WORKPLANE_BOUNDARY_EPSILON = 0.0001; const WORKPLANE_BOUNDARY_EPSILON = 0.0001;
export const WORKPLANE_LINE_ELEVATION = 0; export const WORKPLANE_LINE_ELEVATION = 0;
export const WORKPLANE_MAJOR_GRID_INTERVAL = 5;
export type WorkplaneGridCoordinate = { export type WorkplaneGridCoordinate = {
coordinate: number; coordinate: number;
+11
View File
@@ -114,10 +114,12 @@ export function proportionalResizeScale(startWidth: number, startDepth: number,
} }
export function fallbackSolidColor(shape: WorkplaneShape) { export function fallbackSolidColor(shape: WorkplaneShape) {
if (shape.sketchOperation === "revolve") return "#78b96b";
if (shape.kind === "cylinder") return "#d97813"; if (shape.kind === "cylinder") return "#d97813";
if (shape.kind === "sphere") return "#0098c7"; if (shape.kind === "sphere") return "#0098c7";
if (shape.kind === "cone") return "#6e2786"; if (shape.kind === "cone") return "#6e2786";
if (shape.kind === "pyramid") return "#f2cf10"; if (shape.kind === "pyramid") return "#f2cf10";
if (shape.kind === "gear") return "#6f7f8d";
return "#d41721"; return "#d41721";
} }
@@ -188,11 +190,20 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.segments === b.segments && a.segments === b.segments &&
a.topRadius === b.topRadius && a.topRadius === b.topRadius &&
a.baseRadius === b.baseRadius && a.baseRadius === b.baseRadius &&
a.teeth === b.teeth &&
a.toothSize === b.toothSize &&
a.toothWidth === b.toothWidth &&
a.centerHoleSize === b.centerHoleSize &&
a.gearType === b.gearType &&
a.helixAngle === b.helixAngle &&
a.helixQuality === b.helixQuality &&
a.text === b.text && a.text === b.text &&
a.font === b.font && a.font === b.font &&
a.importedMesh === b.importedMesh && a.importedMesh === b.importedMesh &&
a.imagePlate === b.imagePlate && a.imagePlate === b.imagePlate &&
a.sketchProfile === b.sketchProfile && a.sketchProfile === b.sketchProfile &&
a.sketchOperation === b.sketchOperation &&
a.sketchRevolve === b.sketchRevolve &&
a.edgeTreatments === b.edgeTreatments && a.edgeTreatments === b.edgeTreatments &&
a.edgeTreatmentHistory === b.edgeTreatmentHistory && a.edgeTreatmentHistory === b.edgeTreatmentHistory &&
a.cadDisplayEdges === b.cadDisplayEdges && a.cadDisplayEdges === b.cadDisplayEdges &&
+22
View File
@@ -12,6 +12,7 @@ export type ShapeKind =
| "halfSphere" | "halfSphere"
| "torus" | "torus"
| "tube" | "tube"
| "gear"
| "ring" | "ring"
| "wedge" | "wedge"
| "polygon" | "polygon"
@@ -105,6 +106,18 @@ export type SketchProfile = {
images?: SketchImage[]; images?: SketchImage[];
}; };
export type SketchOperation = "extrude" | "revolve";
export type GearType = "spur" | "helical" | "bevel";
export type SketchRevolveSettings = {
startAngle: number;
sweepAngle: number;
sides: number;
quality: number;
thickness: number;
};
export type EdgeTreatmentFeature = { export type EdgeTreatmentFeature = {
kind: "fillet" | "chamfer"; kind: "fillet" | "chamfer";
amount: number; amount: number;
@@ -181,6 +194,13 @@ export type WorkplaneShape = {
segments?: number; segments?: number;
topRadius?: number; topRadius?: number;
baseRadius?: number; baseRadius?: number;
teeth?: number;
toothSize?: number;
toothWidth?: number;
centerHoleSize?: number;
gearType?: GearType;
helixAngle?: number;
helixQuality?: number;
text?: string; text?: string;
font?: string; font?: string;
importedMesh?: { importedMesh?: {
@@ -206,6 +226,8 @@ export type WorkplaneShape = {
pixelHeight: number; pixelHeight: number;
}; };
sketchProfile?: SketchProfile; sketchProfile?: SketchProfile;
sketchOperation?: SketchOperation;
sketchRevolve?: SketchRevolveSettings;
edgeTreatments?: EdgeTreatmentFeature[]; edgeTreatments?: EdgeTreatmentFeature[];
edgeTreatmentHistory?: EdgeTreatmentHistoryEntry[]; edgeTreatmentHistory?: EdgeTreatmentHistoryEntry[];
cadDisplayEdges?: CadDisplayEdge[]; cadDisplayEdges?: CadDisplayEdge[];
+7 -3
View File
@@ -23,18 +23,22 @@ ENV HOSTNAME=0.0.0.0
ENV PORT=3000 ENV PORT=3000
ENV SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects ENV SKETCHFORGE_SHARED_PROJECTS_DIR=/data/projects
RUN mkdir -p /data/projects && chown node:node /data/projects RUN apk add --no-cache libcap \
&& setcap cap_net_bind_service=+ep /usr/local/bin/node \
&& mkdir -p /data/projects \
&& chown node:node /data/projects
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./ COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
COPY --chown=node:node deploy/docker/start-server.mjs ./deploy/docker/start-server.mjs
USER node USER node
EXPOSE 3000 EXPOSE 80 3000
VOLUME ["/data/projects"] VOLUME ["/data/projects"]
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget -q -O - http://127.0.0.1:3000/api/shared-projects | grep -q '"enabled":true' || exit 1 CMD wget -q -O - http://127.0.0.1:3000/api/shared-projects | grep -q '"enabled":true' || exit 1
CMD ["node", "apps/web/server.js"] CMD ["node", "deploy/docker/start-server.mjs"]
+85
View File
@@ -0,0 +1,85 @@
import { spawn } from "node:child_process";
import net from "node:net";
const parsePort = (value, fallback, name) => {
const port = Number.parseInt(value ?? "", 10);
if (Number.isInteger(port) && port > 0 && port <= 65_535) {
return port;
}
if (value) {
console.warn(`Ignoring invalid ${name} value "${value}"; using ${fallback}.`);
}
return fallback;
};
const appPort = parsePort(process.env.PORT, 3000, "PORT");
const legacyPort = parsePort(process.env.SKETCHFORGE_LEGACY_PORT, 80, "SKETCHFORGE_LEGACY_PORT");
const app = spawn(process.execPath, ["apps/web/server.js"], {
env: {
...process.env,
HOSTNAME: process.env.HOSTNAME || "0.0.0.0",
PORT: String(appPort),
},
stdio: "inherit",
});
let proxy;
let shuttingDown = false;
if (legacyPort !== appPort) {
proxy = net.createServer((client) => {
const upstream = net.createConnection({
host: "127.0.0.1",
port: appPort,
});
client.on("error", () => upstream.destroy());
upstream.on("error", () => client.destroy());
client.pipe(upstream);
upstream.pipe(client);
});
proxy.on("error", (error) => {
console.error(`Legacy port ${legacyPort} proxy failed:`, error);
app.kill("SIGTERM");
});
proxy.listen(legacyPort, "0.0.0.0", () => {
console.log(`Legacy Docker port ${legacyPort} forwards to SketchForge on port ${appPort}.`);
});
}
const finish = (code) => {
if (proxy?.listening) {
proxy.close(() => process.exit(code));
setTimeout(() => process.exit(code), 5_000).unref();
return;
}
process.exit(code);
};
const shutdown = (signal) => {
if (shuttingDown) {
return;
}
shuttingDown = true;
if (!app.killed) {
app.kill(signal);
}
};
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => shutdown(signal));
}
app.on("error", (error) => {
console.error("Unable to start SketchForge:", error);
finish(1);
});
app.on("exit", (code, signal) => {
if (!shuttingDown && signal) {
console.error(`SketchForge exited from ${signal}.`);
}
finish(shuttingDown ? 0 : code ?? 1);
});
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "sketchforge", "name": "sketchforge",
"version": "0.6.0", "version": "0.7.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sketchforge", "name": "sketchforge",
"version": "0.6.0", "version": "0.7.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@tailwindcss/postcss": "^4.1.8", "@tailwindcss/postcss": "^4.1.8",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "sketchforge", "name": "sketchforge",
"version": "0.6.0", "version": "0.7.0",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { createGearGeometry, gearSettings, normalizeGearTeeth, normalizeGearToothSize } from "@/lib/gearGeometry";
import type { GearType } from "@/types/sketchforge";
function edgeUseCounts(position: { count: number; getX: (index: number) => number; getY: (index: number) => number; getZ: (index: number) => number }) {
const uses = new Map<string, number>();
const keyForPoint = (index: number) => [position.getX(index), position.getY(index), position.getZ(index)]
.map((value) => value.toFixed(5))
.join(",");
for (let index = 0; index + 2 < position.count; index += 3) {
const triangle = [keyForPoint(index), keyForPoint(index + 1), keyForPoint(index + 2)];
for (let edge = 0; edge < 3; edge += 1) {
const a = triangle[edge];
const b = triangle[(edge + 1) % 3];
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
uses.set(key, (uses.get(key) ?? 0) + 1);
}
}
return uses;
}
describe("gear geometry", () => {
it.each<GearType>(["spur", "helical", "bevel"])("creates a closed %s gear with the requested bounds", (gearType) => {
const geometry = createGearGeometry({
width: 30,
depth: 24,
height: 8,
teeth: 14,
toothSize: 2.5,
gearType,
});
const position = geometry.getAttribute("position");
expect(position.count).toBeGreaterThan(100);
expect(geometry.getIndex()).toBeNull();
expect([...edgeUseCounts(position).values()].every((uses) => uses === 2)).toBe(true);
expect(geometry.boundingBox?.min.y).toBeCloseTo(0, 5);
expect(geometry.boundingBox?.max.y).toBeCloseTo(8, 5);
expect((geometry.boundingBox?.max.x ?? 0) - (geometry.boundingBox?.min.x ?? 0)).toBeCloseTo(30, 4);
expect((geometry.boundingBox?.max.z ?? 0) - (geometry.boundingBox?.min.z ?? 0)).toBeCloseTo(24, 4);
});
it("creates a closed solid center when the center hole is zero", () => {
const geometry = createGearGeometry({
width: 30,
depth: 30,
height: 6,
teeth: 8,
toothSize: 4,
centerHoleSize: 0,
gearType: "spur",
});
const position = geometry.getAttribute("position");
expect([...edgeUseCounts(position).values()].every((uses) => uses === 2)).toBe(true);
expect((geometry.boundingBox?.max.x ?? 0) - (geometry.boundingBox?.min.x ?? 0)).toBeCloseTo(30, 4);
expect((geometry.boundingBox?.max.z ?? 0) - (geometry.boundingBox?.min.z ?? 0)).toBeCloseTo(30, 4);
});
it("normalizes editable gear settings to supported values", () => {
expect(normalizeGearTeeth(2)).toBe(6);
expect(normalizeGearTeeth(200)).toBe(64);
expect(normalizeGearToothSize(20, 30, 20)).toBe(4.4);
expect(gearSettings({ width: 30, depth: 30, teeth: 20, toothSize: 3, toothWidth: 2.4, centerHoleSize: 7, gearType: "bevel", helixAngle: -30, helixQuality: 24 })).toEqual({
teeth: 20,
toothSize: 3,
toothWidth: 2.4,
centerHoleSize: 7,
gearType: "bevel",
helixAngle: -30,
helixQuality: 24,
});
});
});
+13
View File
@@ -36,9 +36,22 @@ describe("shape catalog", () => {
it("uses shape-specific defaults for text and round profiles", () => { it("uses shape-specific defaults for text and round profiles", () => {
const text = makeShapeFromAsset({ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" }); const text = makeShapeFromAsset({ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" });
const torus = makeShapeFromAsset({ id: "torus", name: "Torus", src: "torus.png", kind: "torus", color: "#0098c7" }); const torus = makeShapeFromAsset({ id: "torus", name: "Torus", src: "torus.png", kind: "torus", color: "#0098c7" });
const gear = makeShapeFromAsset({ id: "gear", name: "Gear", src: "gear.svg", kind: "gear", color: "#6f7f8d" });
expect(text).toMatchObject({ width: 86, depth: 28, height: 10, text: "TEXT", font: "Multilanguage" }); expect(text).toMatchObject({ width: 86, depth: 28, height: 10, text: "TEXT", font: "Multilanguage" });
expect(torus).toMatchObject({ size: 22, width: 22, depth: 22, height: 5 }); expect(torus).toMatchObject({ size: 22, width: 22, depth: 22, height: 5 });
expect(gear).toMatchObject({
size: 30,
width: 30,
depth: 30,
height: 6,
teeth: 12,
toothSize: 2.5,
centerHoleSize: 6,
gearType: "spur",
helixAngle: 22.5,
helixQuality: 16,
});
}); });
it("creates canonical scene shapes with stable defaults", () => { it("creates canonical scene shapes with stable defaults", () => {
+93
View File
@@ -0,0 +1,93 @@
import { beforeAll, describe, expect, it } from "vitest";
import manifoldModule, { type ManifoldToplevel } from "manifold-3d";
import {
buildSketchRevolveMesh,
normalizeSketchRevolveSettings,
sketchProfileToRevolvePolygons,
} from "@/lib/sketchRevolve";
import type { SketchProfile } from "@/types/sketchforge";
function rectangleProfile(innerRadius = 5, outerRadius = 10, height = 20): SketchProfile {
return {
points: [
{ id: "a", x: -innerRadius, z: 0 },
{ id: "b", x: -outerRadius, z: 0 },
{ id: "c", x: -outerRadius, z: height },
{ id: "d", x: -innerRadius, z: height },
],
segments: [
{ id: "ab", startId: "a", endId: "b", kind: "line" },
{ id: "bc", startId: "b", endId: "c", kind: "line" },
{ id: "cd", startId: "c", endId: "d", kind: "line" },
{ id: "da", startId: "d", endId: "a", kind: "line" },
],
};
}
describe("sketch revolve", () => {
let runtime: ManifoldToplevel;
beforeAll(async () => {
runtime = await manifoldModule();
runtime.setup();
});
it("revolves a closed left-side profile around the center axis", () => {
const mesh = buildSketchRevolveMesh(runtime, rectangleProfile(), { sides: 32 });
expect(mesh.triangleCount).toBeGreaterThan(100);
expect(mesh.width).toBeCloseTo(20, 4);
expect(mesh.depth).toBeCloseTo(20, 4);
expect(mesh.height).toBeCloseTo(20, 4);
expect(Math.min(...mesh.positions.filter((_value, index) => index % 3 === 1))).toBeCloseTo(0, 6);
});
it("creates thickness automatically for an open profile", () => {
const profile: SketchProfile = {
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
};
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 2 });
expect(polygons).toHaveLength(1);
expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(7, 6);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(9, 6);
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 2, sides: 24 });
expect(mesh.triangleCount).toBeGreaterThan(0);
expect(mesh.width).toBeCloseTo(18, 4);
expect(mesh.height).toBeCloseTo(20, 4);
});
it("allows construction points across the axis but only revolves the working-side segment", () => {
const profile: SketchProfile = {
points: [{ id: "construction", x: 10, z: 0 }, { id: "profile", x: -10, z: 20 }],
segments: [{ id: "crossing", startId: "construction", endId: "profile", kind: "line" }],
};
const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 1 });
expect(polygons).toHaveLength(1);
expect(Math.max(...polygons[0].map((point) => point[1]))).toBeLessThan(11);
expect(Math.max(...polygons[0].map((point) => point[0]))).toBeGreaterThan(10);
const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 1, sides: 24 });
expect(mesh.triangleCount).toBeGreaterThan(0);
expect(mesh.height).toBeGreaterThan(9);
expect(mesh.height).toBeLessThan(11);
});
it("supports partial and reverse sweeps", () => {
const quarter = buildSketchRevolveMesh(runtime, rectangleProfile(), { startAngle: 30, sweepAngle: 90, sides: 48 });
const reverse = buildSketchRevolveMesh(runtime, rectangleProfile(), { startAngle: 120, sweepAngle: -90, sides: 48 });
expect(quarter.triangleCount).toBeGreaterThan(0);
expect(reverse.triangleCount).toBeGreaterThan(0);
expect(quarter.width).toBeLessThanOrEqual(20.001);
expect(quarter.depth).toBeLessThanOrEqual(20.001);
});
it("normalizes unsafe revolve settings", () => {
expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 500, quality: 0, thickness: -2 })).toEqual({
startAngle: 330,
sweepAngle: 1,
sides: 128,
quality: 1,
thickness: 0.1,
});
});
});
+38 -1
View File
@@ -74,7 +74,7 @@ describe("SketchForge .skf project packages", () => {
it("round-trips every supported native shape kind and editable properties", async () => { it("round-trips every supported native shape kind and editable properties", async () => {
const nativeKinds: ShapeKind[] = [ const nativeKinds: ShapeKind[] = [
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof", "box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
"halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron", "halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron",
]; ];
const shapes = nativeKinds.map((kind, index) => shape(kind, `${kind}-${index}`, { const shapes = nativeKinds.map((kind, index) => shape(kind, `${kind}-${index}`, {
hole: index === 2, hole: index === 2,
@@ -82,6 +82,13 @@ describe("SketchForge .skf project packages", () => {
hidden: index === 4, hidden: index === 4,
mirrorX: index === 5, mirrorX: index === 5,
sides: index + 3, sides: index + 3,
teeth: kind === "gear" ? 18 : undefined,
toothSize: kind === "gear" ? 3.25 : undefined,
toothWidth: kind === "gear" ? 2.75 : undefined,
centerHoleSize: kind === "gear" ? 7.5 : undefined,
gearType: kind === "gear" ? "helical" : undefined,
helixAngle: kind === "gear" ? -30 : undefined,
helixQuality: kind === "gear" ? 24 : undefined,
text: kind === "text" ? "Editable" : undefined, text: kind === "text" ? "Editable" : undefined,
sketchProfile: kind === "sketch" ? { sketchProfile: kind === "sketch" ? {
points: [ points: [
@@ -117,6 +124,36 @@ describe("SketchForge .skf project packages", () => {
expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0); expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0);
}); });
it("preserves editable revolve sketch settings and generated geometry", async () => {
const revolve = shape("mesh", "revolve-sketch", {
name: "Sketch revolve",
sketchOperation: "revolve",
sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8, thickness: 1.5 },
sketchProfile: {
points: [{ id: "p1", x: -4, z: 0 }, { id: "p2", x: -8, z: 0 }, { id: "p3", x: -8, z: 16 }, { id: "p4", x: -4, z: 16 }],
segments: [
{ id: "s1", startId: "p1", endId: "p2", kind: "line" },
{ id: "s2", startId: "p2", endId: "p3", kind: "line" },
{ id: "s3", startId: "p3", endId: "p4", kind: "line" },
{ id: "s4", startId: "p4", endId: "p1", kind: "line" },
],
},
importedMesh: {
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 16,
baseDepth: 16,
baseHeight: 16,
triangleCount: 1,
sourceFormat: "json",
},
});
const restored = await importSkfProject(await exportSkfProject(input([revolve])));
expect(restored.shapes[0].sketchOperation).toBe("revolve");
expect(restored.shapes[0].sketchRevolve).toEqual(revolve.sketchRevolve);
expect(restored.shapes[0].sketchProfile).toEqual(revolve.sketchProfile);
expect(restored.shapes[0].importedMesh?.positions).toEqual(revolve.importedMesh?.positions);
});
it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => { it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => {
const solid = shape("box", "solid", { x: 0 }); const solid = shape("box", "solid", { x: 0 });
const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 }); const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 });
+5 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION } from "@/lib/workplaneGrid"; import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
describe("workplane grid geometry", () => { describe("workplane grid geometry", () => {
it("excludes both perimeter coordinates when spacing divides the workplane", () => { it("excludes both perimeter coordinates when spacing divides the workplane", () => {
@@ -22,6 +22,10 @@ describe("workplane grid geometry", () => {
expect(WORKPLANE_LINE_ELEVATION).toBe(0); expect(WORKPLANE_LINE_ELEVATION).toBe(0);
}); });
it("groups minor grid blocks into five-by-five major sections", () => {
expect(WORKPLANE_MAJOR_GRID_INTERVAL).toBe(5);
});
it("preserves the minor, major, and axis line hierarchy", () => { it("preserves the minor, major, and axis line hierarchy", () => {
const palette = workplaneGridPalette(); const palette = workplaneGridPalette();
+9 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, scaleOptionsForUnits } from "@/lib/measurementUnits"; import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits } from "@/lib/measurementUnits";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
describe("workplane settings helpers", () => { describe("workplane settings helpers", () => {
@@ -78,6 +78,14 @@ describe("workplane settings helpers", () => {
expect(formatMeasurementNumber(0.0004, 1, 0.001)).toBe("0.0004"); expect(formatMeasurementNumber(0.0004, 1, 0.001)).toBe("0.0004");
}); });
it("accepts dot and comma decimal measurement input", () => {
expect(parseMeasurementInput("12.5")).toBe(12.5);
expect(parseMeasurementInput("12,5")).toBe(12.5);
expect(parseMeasurementInput("1.234,5")).toBe(1234.5);
expect(parseMeasurementInput("1,234.5")).toBe(1234.5);
expect(parseMeasurementInput("not a measurement")).toBeNaN();
});
it("fingerprints workspace and snap settings together", () => { it("fingerprints workspace and snap settings together", () => {
const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm"); const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
const equivalentNewReference = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE }, "1.0 mm"); const equivalentNewReference = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE }, "1.0 mm");