release: publish v1.0.0

This commit is contained in:
Formsmith
2026-08-10 16:15:32 +03:00
parent decf33521a
commit a42922c4f3
56 changed files with 3914 additions and 125 deletions
+121 -60
View File
@@ -16,6 +16,7 @@ import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.js
import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json";
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
import type { ChallengeTutorialId } from "@/lib/challenges";
import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
@@ -84,12 +85,14 @@ import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEn
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { exportMeshesToObj } from "@/lib/objExport";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
import { exportMeshesToStl } from "@/lib/stlExport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
@@ -113,6 +116,7 @@ import {
type SketchForgeMcpViewFace,
} from "@/lib/sketchforgeMcpProtocol";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl, importedShapeFromSvg };
@@ -529,6 +533,76 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex
} satisfies WorkplaneShape);
}
let sketchCadWorker: Worker | null = null;
let sketchCadRequestId = 0;
const sketchCadPending = new Map<number, {
resolve: (response: SketchCadBuildResponse) => void;
reject: (error: Error) => void;
timer: number;
}>();
function ensureSketchCadWorker() {
if (sketchCadWorker) return sketchCadWorker;
const worker = new Worker(new URL("../workers/sketchCad.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (event: MessageEvent<SketchCadBuildResponse>) => {
const pending = sketchCadPending.get(event.data.requestId);
if (!pending) return;
window.clearTimeout(pending.timer);
sketchCadPending.delete(event.data.requestId);
pending.resolve(event.data);
};
worker.onerror = () => {
sketchCadPending.forEach((pending) => {
window.clearTimeout(pending.timer);
pending.reject(new Error("The OpenCascade sketch worker failed to start"));
});
sketchCadPending.clear();
worker.terminate();
sketchCadWorker = null;
};
sketchCadWorker = worker;
return worker;
}
async function cadShapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) {
const safeHeight = Math.max(MIN_SHAPE_DIMENSION, height);
const worker = ensureSketchCadWorker();
const requestId = ++sketchCadRequestId;
const response = await new Promise<SketchCadBuildResponse>((resolve, reject) => {
const timer = window.setTimeout(() => {
sketchCadPending.delete(requestId);
reject(new Error("OpenCascade timed out while building the sketch"));
}, 30_000);
sketchCadPending.set(requestId, { resolve, reject, timer });
worker.postMessage({ type: "build", requestId, profile: cloneSketchProfile(profile), height: safeHeight });
});
if (response.type === "error") throw new Error(response.message);
const source = canonicalizeShape({
...(existing ?? {
id: createLocalId("sketch-extrusion"),
name: "Sketch extrusion",
kind: "mesh" as const,
color: "#d41721",
x: 0,
z: 0,
size: 1,
width: 1,
depth: 1,
height: safeHeight,
rotation: 0,
}),
sketchProfile: cloneSketchProfile(profile),
sketchOperation: "extrude",
edgeTreatments: undefined,
edgeTreatmentHistory: undefined,
cadDisplayEdges: undefined,
cadDisplayEdgesVersion: undefined,
});
const shape = shapeFromCadMesh(source, response.positions, response.normals, response.indices, response.brep);
if (!shape) throw new Error("OpenCascade returned an empty sketch solid");
return { ...shape, sketchProfile: cloneSketchProfile(profile), sketchOperation: "extrude" as const };
}
async function shapeFromRevolvedSketchProfile(
profile: SketchProfile,
settings: Partial<SketchRevolveSettings>,
@@ -2263,7 +2337,10 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
}
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
if (!shapeHasTransformToBake(shape)) {
// Rotation is a non-destructive transform for editable text. Baking it would
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
// though the user never grouped or otherwise converted the object.
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
return shape;
}
@@ -2459,53 +2536,6 @@ async function importedShapeFromImage(file: File): Promise<WorkplaneShape> {
};
}
function normalFor(a: Vec3, b: Vec3, c: Vec3): Vec3 {
const ux = b[0] - a[0];
const uy = b[1] - a[1];
const uz = b[2] - a[2];
const vx = c[0] - a[0];
const vy = c[1] - a[1];
const vz = c[2] - a[2];
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const length = Math.hypot(nx, ny, nz) || 1;
return [nx / length, ny / length, nz / length];
}
function toStl(meshes: MeshData[]) {
const lines = ["solid sketchforge_design"];
meshes.forEach((mesh) => {
mesh.faces.forEach(([ai, bi, ci]) => {
const a = mesh.vertices[ai];
const b = mesh.vertices[bi];
const c = mesh.vertices[ci];
const n = normalFor(a, b, c);
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
lines.push(" outer loop");
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
lines.push(" endloop");
lines.push(" endfacet");
});
});
lines.push("endsolid sketchforge_design");
return lines.join("\n");
}
function toObj(meshes: MeshData[]) {
const lines = ["# SketchForge OBJ export"];
let offset = 1;
meshes.forEach((mesh) => {
lines.push(`o ${mesh.name}`);
mesh.vertices.forEach(([x, y, z]) => lines.push(`v ${x} ${y} ${z}`));
mesh.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
offset += mesh.vertices.length;
});
return lines.join("\n");
}
async function toSvg(shapes: WorkplaneShape[], title: string) {
const runtime = await getManifoldRuntime();
const layers: SvgProjectionLayer[] = [];
@@ -3118,6 +3148,12 @@ function separateMeshParts(shape: WorkplaneShape) {
.filter((part): part is WorkplaneShape => Boolean(part));
}
function cadModifierSourceParts(shape: WorkplaneShape) {
if (shape.kind !== "text" || shape.importedMesh || shape.cadBrep) return [shape];
const glyphParts = separateMeshParts(shape);
return glyphParts.length > 1 ? glyphParts : [shape];
}
function separablePartCount(shape: WorkplaneShape) {
if (shape.locked || shape.hole) return 0;
if (shape.groupedShapes?.length && !shape.importedMesh) return shape.groupedShapes.length;
@@ -5279,6 +5315,8 @@ export function SketchForgeEditor({
projectModifiedAt = Date.now(),
projectRevision = 0,
sharedProjectsEnabled = false,
challengeTutorial = null,
onChallengeTutorialFinish,
themePreference = "system",
resolvedTheme = "light",
onThemePreferenceChange,
@@ -5323,6 +5361,8 @@ export function SketchForgeEditor({
projectModifiedAt?: number;
projectRevision?: number;
sharedProjectsEnabled?: boolean;
challengeTutorial?: ChallengeTutorialId | null;
onChallengeTutorialFinish?: () => void;
themePreference?: AppThemePreference;
resolvedTheme?: ResolvedAppTheme;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
@@ -6566,8 +6606,9 @@ export function SketchForgeEditor({
if (sketchOperation === "revolve") {
resolved = await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing);
} else {
const extrusion = await shapeFromSketchProfile(sketchProfile, height, existing);
resolved = extrusion ? placeSketchExtrusion(extrusion, activeSketchWorkplane, existing) : null;
setNotice("Building exact sketch geometry…");
const extrusion = await cadShapeFromSketchProfile(sketchProfile, height, existing);
resolved = placeSketchExtrusion(extrusion, activeSketchWorkplane, existing);
}
} catch (error) {
setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`);
@@ -6579,7 +6620,7 @@ export function SketchForgeEditor({
}
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved];
const action = sketchOperation === "revolve" ? "Revolve sketch" : "Sketch";
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Sketch created at 10 mm height");
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Exact sketch created at 10 mm height");
setSketchActive(false);
setSketchRevolvePreview(null);
setEditingSketchShapeId(null);
@@ -7072,7 +7113,9 @@ export function SketchForgeEditor({
invalidateCadModifierSession();
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape];
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment
? restoreGroupedChildren(selectedShape)
: [selectedShape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => {
const frame = shape.cadBrepFrame;
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && (
@@ -7145,7 +7188,9 @@ export function SketchForgeEditor({
}
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape);
const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length);
const sourceParts = shape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(shape) : [shape];
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment
? restoreGroupedChildren(shape)
: [shape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => {
const frame = partShape.cadBrepFrame;
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(partShape) && Boolean(frame) && (
@@ -7711,8 +7756,7 @@ export function SketchForgeEditor({
let shape: WorkplaneShape;
if (kind === "sketch") {
const profile = defaultMcpSketchProfile(width, depth);
const extruded = await shapeFromSketchProfile(profile, height);
if (!extruded) throw new Error("Could not create the sketch profile");
const extruded = await cadShapeFromSketchProfile(profile, height);
shape = canonicalizeShape({
...extruded,
name,
@@ -7724,7 +7768,7 @@ export function SketchForgeEditor({
rotationX: mcpNumber(params.rotationX, 0),
rotationZ: mcpNumber(params.rotationZ, 0),
});
} else if (kind === "box" || kind === "cylinder") {
} else if (kind === "box" || kind === "cylinder" || kind === "text") {
shape = sceneShape({
name,
kind,
@@ -7740,9 +7784,13 @@ export function SketchForgeEditor({
rotationX: mcpNumber(params.rotationX, 0),
rotationZ: mcpNumber(params.rotationZ, 0),
sides: kind === "cylinder" ? Math.max(3, Math.floor(mcpNumber(params.sides, 96))) : undefined,
text: kind === "text" ? mcpString(params.text, "TEXT") : undefined,
font: kind === "text" ? mcpString(params.font, "Multilanguage") : undefined,
bevel: kind === "text" ? Math.max(0, mcpNumber(params.bevel, 0)) : undefined,
segments: kind === "text" ? Math.max(1, Math.floor(mcpNumber(params.segments, 2))) : undefined,
});
} else {
throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch");
throw new Error("MCP create_shape currently supports box, cube, cylinder, text, and sketch");
}
const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape));
commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`);
@@ -7822,6 +7870,9 @@ export function SketchForgeEditor({
if (typeof params.color === "string") patch.color = params.color;
if (typeof params.name === "string") patch.name = params.name;
if (typeof params.hole === "boolean") patch.hole = params.hole;
if (typeof params.text === "string") patch.text = params.text;
if (typeof params.font === "string") patch.font = params.font;
if (typeof params.bevel === "number" && Number.isFinite(params.bevel)) patch.bevel = Math.max(0, params.bevel);
const nextShapes = currentShapes().map((shape) => {
if (shape.id !== target.id) return shape;
const patched = { ...shape, ...cleanShapePatch(patch) };
@@ -8272,12 +8323,12 @@ export function SketchForgeEditor({
}
const meshes = exportable.map(meshForShape);
if (format === "stl") {
void downloadTextFile(projectExportFileName(exportName, "stl"), toStl(meshes), "model/stl")
void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl")
.then((result) => finishNotice("STL", result))
.catch((error: unknown) => failNotice("STL", error));
return;
}
void downloadTextFile(projectExportFileName(exportName, "obj"), toObj(meshes), "text/plain")
void downloadTextFile(projectExportFileName(exportName, "obj"), exportMeshesToObj(meshes), "text/plain")
.then((result) => finishNotice("OBJ", result))
.catch((error: unknown) => failNotice("OBJ", error));
}, [hasSelection, projectName, selectedShapes, shapes]);
@@ -8897,6 +8948,8 @@ export function SketchForgeEditor({
modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []}
selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []}
onModifierEdgeToggle={toggleModifierEdge}
challengeTutorial={challengeTutorial}
onChallengeTutorialFinish={onChallengeTutorialFinish}
themePreference={themePreference}
resolvedTheme={resolvedTheme}
onThemePreferenceChange={onThemePreferenceChange}
@@ -9274,7 +9327,15 @@ function SecondaryToolbar({
const { icon: Icon, action, enabled, label } = tool;
const active = "active" in tool && Boolean(tool.active);
return (
<button className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`} key={label} aria-label={label} title={label} onClick={action} disabled={!enabled}>
<button
className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`}
key={label}
data-sketchforge-tool={label === "Fillet" ? "fillet" : undefined}
aria-label={label}
title={label}
onClick={action}
disabled={!enabled}
>
<Icon />
</button>
);