Release SketchForge 0.5 edge tools

This commit is contained in:
Formsmith
2026-07-05 12:28:23 +03:00
parent f18bacf3ad
commit 5b0ea94e7b
38 changed files with 3973 additions and 519 deletions
+14 -3
View File
@@ -18,11 +18,11 @@
<a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-16a34a"></a>
<a href="https://github.com/Formsmith746/SketchForge-3D/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/Formsmith746/SketchForge-3D?style=social"></a>
<img alt="Local first" src="https://img.shields.io/badge/local--first-no%20account-0ea5e9">
<img alt="Version 0.2.0" src="https://img.shields.io/badge/version-0.2.0-2563eb">
<img alt="Version 0.5.0" src="https://img.shields.io/badge/version-0.5.0-2563eb">
</p>
</div>
![SketchForge v0.2 editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.2.png)
![SketchForge editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.5.png)
## Why SketchForge
@@ -39,8 +39,10 @@ No login. No server project storage. No heavyweight CAD install just to make a u
- **Primitive shape library** - boxes, cylinders, spheres, cones, pyramids, wedges, text, roofs, half spheres, torus shapes, tubes, and more.
- **Solid and hole workflow** - turn shapes into cutters and group them into final geometry.
- **Boolean Intersection** - keep only the geometry where selected solid and hole shapes overlap.
- **Reversible edge tools** - chamfer and fillet selected CAD edges, with history controls for removing applied edge features.
- **Rotated solid edge treatment** - chamfer and fillet preserve analytic box topology after one-, two-, or three-axis rotations.
- **STL import** - bring outside models into the same workspace as primitives.
- **STL and OBJ export** - export selected objects or the whole scene.
- **STL, OBJ, and STEP workflows** - export selected objects or the whole scene, and round-trip exact STEP/B-Rep geometry.
- **Fast browser stack** - Next.js, React, TypeScript, Three.js, and Manifold/CSG geometry tooling.
## Demo
@@ -238,6 +240,12 @@ Run tests:
npm run test
```
Start the local SketchForge MCP bridge for editor automation:
```bash
npm run mcp:sketchforge
```
Create a production build:
```bash
@@ -309,6 +317,7 @@ apps/web/src/types/ Shared shape and editor types
apps/web/src/generated/ Generated Manifold runtime source
apps/web/src/lib/ Shared utilities
apps/web/public/assets/ Static app images, icons, logos, shape assets
scripts/ Build and local automation helpers
docs/media/ README screenshots and demo videos
deploy/docker/ Docker, Compose, and Nginx deployment files
.github/ Issue templates and community files
@@ -322,7 +331,9 @@ SketchForge is alpha, but the core editor loop is usable today:
- add, move, resize, rotate, mirror, align, duplicate, hide, and delete shapes
- switch shapes between solid and hole modes
- group and ungroup geometry
- apply and remove chamfer/fillet edge treatments
- import STL files
- import and export STEP files
- export STL or OBJ
- generate project thumbnails
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

@@ -0,0 +1,110 @@
import { NextResponse } from "next/server";
import type { SketchForgeMcpApiPayload } from "@/lib/sketchforgeMcpProtocol";
import {
completeSketchForgeMcpCommand,
dispatchSketchForgeMcpCommand,
listSketchForgeMcpEditors,
pollSketchForgeMcpCommand,
registerSketchForgeMcpEditor,
} from "@/lib/sketchforgeMcpStore";
export const dynamic = "force-dynamic";
export const revalidate = false;
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
function isLocalRequest(request: Request) {
const requestUrl = new URL(request.url);
if (!LOCAL_HOSTS.has(requestUrl.hostname)) {
return false;
}
const origin = request.headers.get("origin");
if (origin) {
try {
const originUrl = new URL(origin);
if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) {
return false;
}
} catch {
return false;
}
}
const fetchSite = request.headers.get("sec-fetch-site");
return !fetchSite || fetchSite === "same-origin" || fetchSite === "none";
}
function localOnly(request: Request) {
if (process.env.NODE_ENV === "production") {
return NextResponse.json({ error: "SketchForge MCP is only available in local development." }, { status: 404 });
}
if (!isLocalRequest(request)) {
return NextResponse.json({ error: "SketchForge MCP only accepts localhost requests." }, { status: 403 });
}
return null;
}
function isObject(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
export async function GET(request: Request) {
const blocked = localOnly(request);
if (blocked) return blocked;
return NextResponse.json({ editors: listSketchForgeMcpEditors() });
}
export async function POST(request: Request) {
const blocked = localOnly(request);
if (blocked) return blocked;
let body: SketchForgeMcpApiPayload;
try {
body = (await request.json()) as SketchForgeMcpApiPayload;
} catch {
return NextResponse.json({ error: "Invalid SketchForge MCP request." }, { status: 400 });
}
if (!isObject(body) || typeof body.type !== "string") {
return NextResponse.json({ error: "Invalid SketchForge MCP request." }, { status: 400 });
}
if (body.type === "heartbeat") {
if (!isObject(body.editor)) {
return NextResponse.json({ error: "Invalid editor heartbeat." }, { status: 400 });
}
registerSketchForgeMcpEditor(body.editor);
return NextResponse.json({ ok: true, editors: listSketchForgeMcpEditors() });
}
if (body.type === "poll") {
if (typeof body.editorId !== "string") {
return NextResponse.json({ error: "Invalid editor poll." }, { status: 400 });
}
return NextResponse.json({ command: pollSketchForgeMcpCommand(body.editorId) });
}
if (body.type === "result") {
if (typeof body.editorId !== "string" || !isObject(body.result) || typeof body.result.commandId !== "string" || typeof body.result.ok !== "boolean") {
return NextResponse.json({ error: "Invalid command result." }, { status: 400 });
}
return NextResponse.json({ ok: completeSketchForgeMcpCommand(body.editorId, body.result) });
}
if (body.type === "command") {
if (typeof body.action !== "string") {
return NextResponse.json({ error: "Invalid command action." }, { status: 400 });
}
const result = await dispatchSketchForgeMcpCommand({
editorId: typeof body.editorId === "string" ? body.editorId : undefined,
editorNumber: typeof body.editorNumber === "number" ? body.editorNumber : undefined,
action: body.action,
params: isObject(body.params) ? body.params : {},
timeoutMs: typeof body.timeoutMs === "number" ? body.timeoutMs : undefined,
});
return NextResponse.json(result, { status: result.ok ? 200 : 504 });
}
return NextResponse.json({ error: "Unknown SketchForge MCP request." }, { status: 400 });
}
+324 -62
View File
@@ -182,10 +182,11 @@ button {
.dashboard-nav-item {
display: flex;
width: 100%;
min-width: 0;
height: 42px;
align-items: center;
gap: 10px;
padding: 0 12px;
gap: 8px;
padding: 0 8px;
color: #40586f;
background: transparent;
border-radius: 6px;
@@ -208,6 +209,14 @@ button {
background: #e8f6fc;
}
.dashboard-nav-item:focus {
outline: 0;
}
.dashboard-nav-item:focus-visible {
box-shadow: inset 0 0 0 2px #52bfe9;
}
.dashboard-settings-button {
color: #536a80;
}
@@ -231,6 +240,20 @@ button {
font-weight: 800;
}
.dashboard-coming-soon {
display: grid;
min-height: calc(100vh - 64px - 44px);
place-items: center;
color: #173a56;
}
.dashboard-coming-soon strong {
font-size: clamp(42px, 7vw, 96px);
font-weight: 900;
line-height: 1;
text-align: center;
}
.dashboard-action-tile {
display: flex;
min-width: 0;
@@ -989,7 +1012,6 @@ button {
}
.edge-modifier-header,
.edge-modifier-value-row,
.edge-modifier-quick-actions,
.edge-modifier-footer,
.edge-modifier-check {
@@ -1110,6 +1132,18 @@ button {
cursor: pointer;
}
.edge-modifier-history-toggle,
.edge-modifier-history-item {
display: flex;
align-items: center;
gap: 7px;
text-align: left;
}
.edge-modifier-history-toggle {
justify-content: center;
}
.edge-modifier-history-actions button:disabled {
color: #9aa8b3;
background: #f4f6f8;
@@ -1123,6 +1157,43 @@ button {
line-height: 1.35;
}
.edge-modifier-history-list {
display: grid;
gap: 5px;
max-height: 170px;
overflow: auto;
}
.edge-modifier-history-item {
justify-content: flex-start;
min-height: 42px;
padding: 6px 8px;
}
.edge-modifier-history-item > span {
display: grid;
min-width: 0;
gap: 2px;
}
.edge-modifier-history-item strong,
.edge-modifier-history-item small {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-modifier-history-item strong {
color: #6d4310;
font-size: 11px;
}
.edge-modifier-history-item small {
color: #7a6851;
font-size: 10px;
font-weight: 700;
}
.edge-modifier-field {
display: block;
margin-top: 11px;
@@ -1131,18 +1202,6 @@ button {
font-weight: 700;
}
.edge-modifier-value-row {
gap: 7px;
margin-top: 5px;
}
.edge-modifier-value-row input[type="range"] {
min-width: 0;
flex: 1;
accent-color: #139ed0;
}
.edge-modifier-value-row input[type="number"],
.edge-modifier-field select {
height: 31px;
color: #263f53;
@@ -1151,11 +1210,6 @@ button {
border-radius: 6px;
}
.edge-modifier-value-row input[type="number"] {
width: 72px;
padding: 0 6px;
}
.edge-modifier-field select {
width: 100%;
margin-top: 5px;
@@ -1273,6 +1327,57 @@ button {
stroke-width: 1.8;
}
.sketch-tool-icon .sketch-reference-icon {
width: 32px;
height: 32px;
}
.sketch-reference-icon {
--sketch-icon-offset-y: 0;
--sketch-icon-scale: 1;
display: block;
object-fit: contain;
pointer-events: none;
user-select: none;
opacity: 0.96;
transform:
translateY(var(--sketch-icon-offset-y))
scale(var(--sketch-icon-scale));
transition: filter 120ms ease, opacity 120ms ease;
}
.sketch-reference-icon[data-sketch-icon="line"],
.sketch-reference-icon[data-sketch-icon="erase"],
.sketch-reference-icon[data-sketch-icon="measure"],
.sketch-reference-icon[data-sketch-icon="select"] {
--sketch-icon-scale: 0.94;
}
.sketch-reference-icon[data-sketch-icon="bezier"] {
--sketch-icon-scale: 1.12;
}
.sketch-reference-icon[data-sketch-icon="smooth"] {
--sketch-icon-scale: 1.16;
}
.sketch-reference-icon[data-sketch-icon="image"] {
--sketch-icon-scale: 1.06;
}
.sketch-reference-icon[data-sketch-icon="refine"] {
--sketch-icon-scale: 1.12;
}
.sketch-reference-icon[data-sketch-icon="sketchTo3d"],
.sketch-reference-icon[data-sketch-icon="editSketchTo3d"] {
--sketch-icon-scale: 1.08;
}
.sketch-reference-icon[data-sketch-icon="sketchTo3d"] {
--sketch-icon-scale: 1.08;
}
.sketch-command-button {
display: inline-flex;
height: 43px;
@@ -1297,6 +1402,11 @@ button {
stroke-width: 1.8;
}
.sketch-command-button .sketch-reference-icon {
width: 27px;
height: 27px;
}
.sketch-command-button:hover:not(:disabled) {
color: #17405d;
background: #e7f5fb;
@@ -1317,6 +1427,25 @@ button {
cursor: default;
}
.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 {
filter: grayscale(1) brightness(1.25);
opacity: 0.34;
}
.toolbar-icon:not(.disabled):hover .sketch-reference-icon,
.sketch-command-button:hover:not(:disabled) .sketch-reference-icon {
filter: contrast(1.08) brightness(0.95);
opacity: 1;
}
.toolbar-icon.active .sketch-reference-icon {
filter: contrast(1.12) brightness(0.9) drop-shadow(0 0 5px rgba(0, 156, 222, 0.28));
opacity: 1;
}
.toolbar-workspace-tabs {
position: absolute;
top: 0;
@@ -1509,6 +1638,12 @@ button {
height: 43px;
}
.toolbar-icon .toolbar-art-toolbar-chamfer,
.toolbar-icon .toolbar-art-toolbar-fillet {
width: 34px;
height: 34px;
}
.toolbar-icon.disabled .toolbar-command-icon {
filter: grayscale(1) brightness(1.25);
opacity: 0.22;
@@ -2052,6 +2187,18 @@ button {
vector-effect: non-scaling-stroke;
}
.sketch-reference-shapes .sketch-reference-mesh-face {
fill: rgba(207, 142, 42, 0.22);
stroke: none;
}
.sketch-reference-shapes .sketch-reference-mesh-outline {
fill: none;
stroke: rgba(188, 113, 18, 0.7);
stroke-width: 1.25;
vector-effect: non-scaling-stroke;
}
.sketch-reference-images image {
cursor: move;
image-rendering: auto;
@@ -2217,6 +2364,26 @@ button {
pointer-events: none;
}
.sketch-measurement.pending > line {
stroke: #169fce;
}
.sketch-measurement-point {
fill: #ffffff;
stroke: #d56100;
stroke-width: 2;
vector-effect: non-scaling-stroke;
}
.sketch-measurement-point.pending {
stroke: #169fce;
}
.sketch-measurement-point.hover {
fill: #169fce;
stroke: #ffffff;
}
.sketch-measurement-pill {
cursor: pointer;
}
@@ -2590,6 +2757,11 @@ button {
cursor: crosshair;
}
.workplane-wrap.modifier-edge-pick .three-workplane-host,
.workplane-wrap.modifier-edge-pick .three-workplane-host:active {
cursor: crosshair;
}
.three-workplane-host canvas {
display: block;
width: 100%;
@@ -3312,8 +3484,12 @@ button {
opacity: 0.55;
}
.shape-inspector .edit-sketch-button {
display: block;
.shape-inspector .edit-sketch-button,
.shape-inspector .inspector-action-button {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: calc(100% - 20px);
height: 38px;
margin: 0 10px 12px;
@@ -3326,13 +3502,15 @@ button {
font-weight: 900;
}
.shape-inspector .edit-sketch-button:hover:not(:disabled) {
.shape-inspector .edit-sketch-button:hover:not(:disabled),
.shape-inspector .inspector-action-button:hover:not(:disabled) {
color: #0d7198;
background: #eaf7fb;
border-color: #8ecbdf;
}
.shape-inspector .edit-sketch-button:disabled {
.shape-inspector .edit-sketch-button:disabled,
.shape-inspector .inspector-action-button:disabled {
opacity: 0.45;
cursor: default;
}
@@ -3378,12 +3556,109 @@ button {
.range-property {
display: grid;
gap: 9px;
gap: 7px;
color: #637286;
font-size: 15px;
font-weight: 650;
}
.range-property-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-width: 0;
}
.range-property-name {
min-width: 0;
overflow: hidden;
color: #586a7d;
text-overflow: ellipsis;
white-space: nowrap;
}
.range-value-control {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 5px;
min-width: 88px;
min-height: 31px;
padding: 0 7px;
color: #51657a;
background: #fff;
border: 1px solid #c7d4df;
border-radius: 6px;
box-shadow: inset 0 1px 1px rgba(25, 45, 65, 0.04);
}
.range-value-control:focus-within {
border-color: #55add8;
box-shadow: 0 0 0 3px rgba(0, 156, 222, 0.14);
}
.range-value-control input {
width: 58px;
min-width: 0;
height: 29px;
padding: 0;
appearance: textfield;
color: #2f4457;
background: transparent;
border: 0;
outline: 0;
font: 750 14px/1 var(--font-ui);
letter-spacing: 0;
text-align: right;
}
.range-value-control input:disabled {
cursor: default;
}
.range-value-control input::-webkit-outer-spin-button,
.range-value-control input::-webkit-inner-spin-button {
appearance: none;
margin: 0;
}
.range-value-unit {
color: #7b8da0;
font-size: 11px;
font-weight: 850;
line-height: 1;
}
.edge-modifier-slider.range-property {
margin-top: 12px;
color: #415a6e;
font-size: 12px;
font-weight: 700;
}
.edge-modifier-slider .range-property-header {
gap: 10px;
}
.edge-modifier-slider .range-property-name {
color: #415a6e;
}
.edge-modifier-slider .range-value-control {
min-width: 84px;
border-color: #bdcdda;
}
.edge-modifier-slider .range-value-control input {
width: 50px;
font-size: 13px;
}
.edge-modifier-slider .range-value-unit {
font-size: 10px;
}
.text-property {
display: grid;
gap: 8px;
@@ -3435,42 +3710,15 @@ button {
.range-control {
position: relative;
height: 22px;
padding: 0 21px;
}
.range-control output,
.range-value-input {
position: absolute;
z-index: 2;
top: -3px;
left: clamp(22px, calc(var(--slider-pos) + 7px), calc(100% - 22px));
min-width: 31px;
height: 31px;
padding: 0 8px;
color: #617287;
font-size: 15px;
line-height: 29px;
text-align: center;
background: white;
border: 1px solid #cbd6e1;
border-radius: 999px;
transform: translateX(-50%);
}
.range-control output {
cursor: text;
}
.range-value-input {
width: 70px;
outline: 0;
font: 700 15px/29px var(--font-ui);
display: flex;
align-items: center;
height: 24px;
padding: 0 3px;
}
.range-control input[type="range"] {
width: 100%;
height: 22px;
height: 24px;
margin: 0;
appearance: none;
background: transparent;
@@ -3478,30 +3726,44 @@ button {
}
.range-control input[type="range"]::-webkit-slider-runnable-track {
height: 4px;
height: 5px;
background:
linear-gradient(to right, #00a6db 0 var(--slider-pos), #dbe1e7 var(--slider-pos) 100%);
border-radius: 999px;
}
.range-control input[type="range"]::-webkit-slider-thumb {
width: 1px;
height: 1px;
width: 17px;
height: 17px;
margin-top: -6px;
appearance: none;
background: #ffffff;
border: 2px solid #00a6db;
border-radius: 999px;
box-shadow: 0 1px 4px rgba(24, 48, 68, 0.2);
}
.range-control input[type="range"]::-moz-range-track {
height: 4px;
height: 5px;
background: #dbe1e7;
border-radius: 999px;
}
.range-control input[type="range"]::-moz-range-progress {
height: 4px;
height: 5px;
background: #00a6db;
border-radius: 999px;
}
.range-control input[type="range"]::-moz-range-thumb {
width: 15px;
height: 15px;
background: #ffffff;
border: 2px solid #00a6db;
border-radius: 999px;
box-shadow: 0 1px 4px rgba(24, 48, 68, 0.2);
}
.inspector-header-icon:hover,
.shape-state-card button:not(:disabled):hover {
background: #eef8fc;
+29 -2
View File
@@ -10,6 +10,7 @@ import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/typ
type AppView = "dashboard" | "editor";
type ViewMode = "grid" | "list";
type DashboardSection = "home" | "challenges";
type DownloadMode = "browser" | "folder";
type DashboardProject = {
@@ -244,6 +245,7 @@ export default function Home() {
const [editorStarted, setEditorStarted] = useState(false);
const [activeProjectId, setActiveProjectId] = useState<string | null>(null);
const [projects, setProjects] = useState<DashboardProject[]>([]);
const [dashboardSection, setDashboardSection] = useState<DashboardSection>("home");
const [query, setQuery] = useState("");
const [viewMode, setViewMode] = useState<ViewMode>("grid");
const [sortMode, setSortMode] = useState("recent");
@@ -550,6 +552,7 @@ export default function Home() {
if (activeProjectId) {
setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project)));
}
setDashboardSection("home");
setView("dashboard");
if (typeof window !== "undefined") {
window.history.replaceState(null, "", "/");
@@ -619,6 +622,7 @@ export default function Home() {
/>
{view === "dashboard" ? (
<Dashboard
dashboardSection={dashboardSection}
dashboardNotice={dashboardNotice}
downloadFolder={downloadFolder}
downloadMode={downloadMode}
@@ -634,6 +638,11 @@ export default function Home() {
onDownloadFolderChange={setDownloadFolder}
onDownloadModeChange={setDownloadMode}
onImportStl={() => dashboardStlInputRef.current?.click()}
onChallenges={() => {
setDashboardSection("challenges");
setDashboardNotice("");
}}
onDashboardHome={() => setDashboardSection("home")}
onOpenProject={openEditor}
onOpenSettings={() => setSettingsOpen(true)}
onQueryChange={setQuery}
@@ -664,6 +673,7 @@ export default function Home() {
}
function Dashboard({
dashboardSection,
dashboardNotice,
downloadFolder,
downloadMode,
@@ -679,6 +689,8 @@ function Dashboard({
onDownloadFolderChange,
onDownloadModeChange,
onImportStl,
onChallenges,
onDashboardHome,
onOpenProject,
onOpenSettings,
onQueryChange,
@@ -687,6 +699,7 @@ function Dashboard({
onViewModeChange,
onWorkspace,
}: {
dashboardSection: DashboardSection;
dashboardNotice: string;
downloadFolder: string;
downloadMode: DownloadMode;
@@ -702,6 +715,8 @@ function Dashboard({
onDownloadFolderChange: (value: string) => void;
onDownloadModeChange: (value: DownloadMode) => void;
onImportStl: () => void;
onChallenges: () => void;
onDashboardHome: () => void;
onOpenProject: (projectId: string) => void;
onOpenSettings: () => void;
onQueryChange: (value: string) => void;
@@ -766,10 +781,14 @@ function Dashboard({
<div className="dashboard-layout">
<aside className="dashboard-sidebar">
<div className="dashboard-nav-stack">
<button className="dashboard-nav-item active" type="button" aria-label="Home" title="Home">
<button className={`dashboard-nav-item ${dashboardSection === "home" ? "active" : ""}`} type="button" aria-label="Home" title="Home" onClick={onDashboardHome}>
<HomeIcon size={20} />
<span>Home</span>
</button>
<button className={`dashboard-nav-item ${dashboardSection === "challenges" ? "active" : ""}`} type="button" aria-label="Challenges" title="Challenges" onClick={onChallenges}>
<SlidersHorizontal size={20} />
<span>Challenges</span>
</button>
</div>
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Download settings" title="Download settings" onClick={onOpenSettings}>
<Settings size={20} />
@@ -777,7 +796,13 @@ function Dashboard({
</button>
</aside>
<section className="dashboard-main" aria-label="Dashboard">
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : "Dashboard"}>
{dashboardSection === "challenges" ? (
<div className="dashboard-coming-soon" role="status">
<strong>Coming soon</strong>
</div>
) : (
<>
<div className="dashboard-actions-band">
<button className="dashboard-action-tile create" type="button" onClick={onCreate}>
<span className="dashboard-action-icon">
@@ -878,6 +903,8 @@ function Dashboard({
<span>Create a 3D design and it will appear here.</span>
</div>
)}
</>
)}
</section>
</div>
File diff suppressed because it is too large Load Diff
+259 -32
View File
@@ -3,6 +3,7 @@
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -22,6 +23,7 @@ type SketchWorkspaceProps = {
activePointId: string | null;
selected: SketchSelection;
measurement: SketchMeasurement;
pendingMeasurementStart: SketchPoint | null;
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void;
@@ -42,6 +44,7 @@ type SketchWorkspaceProps = {
type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean };
type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null };
type PointerAction =
| { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
| { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } }
@@ -123,6 +126,14 @@ function formatDimension(value: number, accuracy: 1 | 2 | 3) {
return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy);
}
function dimensionPillSize(label: string, screenUnit: number, extra = 24) {
return {
width: Math.max(48, label.length * 7.5 + extra) * screenUnit,
height: 26 * screenUnit,
radius: 5 * screenUnit,
};
}
function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) {
const inverse = 1 - amount;
return {
@@ -239,6 +250,152 @@ function isRoundReference(shape: WorkplaneShape) {
return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind);
}
function sketchReferencePoint(shape: WorkplaneShape, x: number, z: number) {
return {
x: shape.x + x * mirrorSign(shape.mirrorX),
z: shape.z + z * mirrorSign(shape.mirrorZ),
};
}
function pointKey(point: { x: number; z: number }, tolerance: number) {
return `${Math.round(point.x / tolerance)},${Math.round(point.z / tolerance)}`;
}
function triangleArea2d(a: { x: number; z: number }, b: { x: number; z: number }, c: { x: number; z: number }) {
return Math.abs((b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z)) / 2;
}
function trianglePath(points: Array<{ x: number; z: number }>) {
return `M ${points[0].x} ${points[0].z} L ${points[1].x} ${points[1].z} L ${points[2].x} ${points[2].z} Z`;
}
function convexHull(points: Array<{ x: number; z: number }>) {
const unique = new Map<string, { x: number; z: number }>();
points.forEach((point) => unique.set(pointKey(point, 0.001), point));
const sorted = [...unique.values()].sort((a, b) => a.x === b.x ? a.z - b.z : a.x - b.x);
if (sorted.length <= 2) return sorted;
const cross = (origin: { x: number; z: number }, a: { x: number; z: number }, b: { x: number; z: number }) =>
(a.x - origin.x) * (b.z - origin.z) - (a.z - origin.z) * (b.x - origin.x);
const lower: Array<{ x: number; z: number }> = [];
sorted.forEach((point) => {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0) lower.pop();
lower.push(point);
});
const upper: Array<{ x: number; z: number }> = [];
[...sorted].reverse().forEach((point) => {
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0) upper.pop();
upper.push(point);
});
lower.pop();
upper.pop();
return [...lower, ...upper];
}
function boundaryPath(points: Array<{ x: number; z: number }>, triangles: number[][], tolerance: number) {
const pointByKey = new Map<string, { x: number; z: number }>();
const edgeCounts = new Map<string, { count: number; a: string; b: string }>();
const addEdge = (aIndex: number, bIndex: number) => {
const a = points[aIndex];
const b = points[bIndex];
const aKey = pointKey(a, tolerance);
const bKey = pointKey(b, tolerance);
pointByKey.set(aKey, a);
pointByKey.set(bKey, b);
const key = aKey < bKey ? `${aKey}|${bKey}` : `${bKey}|${aKey}`;
const current = edgeCounts.get(key);
edgeCounts.set(key, current ? { ...current, count: current.count + 1 } : { count: 1, a: aKey, b: bKey });
};
triangles.forEach(([a, b, c]) => {
addEdge(a, b);
addEdge(b, c);
addEdge(c, a);
});
const boundaryEdges = [...edgeCounts.values()].filter((edge) => edge.count === 1);
if (boundaryEdges.length === 0) return null;
const adjacency = new Map<string, string[]>();
boundaryEdges.forEach(({ a, b }) => {
adjacency.set(a, [...(adjacency.get(a) ?? []), b]);
adjacency.set(b, [...(adjacency.get(b) ?? []), a]);
});
const unused = new Set(boundaryEdges.map(({ a, b }) => (a < b ? `${a}|${b}` : `${b}|${a}`)));
const takeEdge = (a: string, b: string) => unused.delete(a < b ? `${a}|${b}` : `${b}|${a}`);
const hasEdge = (a: string, b: string) => unused.has(a < b ? `${a}|${b}` : `${b}|${a}`);
const commands: string[] = [];
while (unused.size > 0) {
const firstKey = unused.values().next().value as string;
const [start, firstNext] = firstKey.split("|");
const chain = [start, firstNext];
takeEdge(start, firstNext);
while (chain.length <= boundaryEdges.length + 1) {
const current = chain[chain.length - 1];
const previous = chain[chain.length - 2];
const next = (adjacency.get(current) ?? []).find((candidate) => candidate !== previous && hasEdge(current, candidate))
?? (adjacency.get(current) ?? []).find((candidate) => hasEdge(current, candidate));
if (!next) break;
takeEdge(current, next);
chain.push(next);
if (next === start) break;
}
const startPoint = pointByKey.get(chain[0]);
if (!startPoint) continue;
const pointsD = chain
.slice(1)
.map((key) => pointByKey.get(key))
.filter((point): point is { x: number; z: number } => Boolean(point))
.map((point) => `L ${point.x} ${point.z}`);
commands.push(`M ${startPoint.x} ${startPoint.z} ${pointsD.join(" ")}${chain[chain.length - 1] === chain[0] ? " Z" : ""}`);
}
return commands.join(" ");
}
function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint | null {
if (!shape.importedMesh) return null;
const positions = resizedImportedMeshPositions(shape);
if (positions.length < 9) return null;
let minY = Number.POSITIVE_INFINITY;
for (let index = 1; index < positions.length; index += 3) {
minY = Math.min(minY, positions[index]);
}
if (!Number.isFinite(minY)) return null;
const tolerance = Math.max(0.001, Math.max(shape.width, shape.depth, shape.height) / 100000);
const bottomTolerance = Math.max(0.025, shape.height * 0.003);
const points: Array<{ x: number; z: number }> = [];
const triangles: number[][] = [];
const allProjected: Array<{ x: number; z: number }> = [];
for (let index = 0; index + 8 < positions.length; index += 9) {
const ys = [positions[index + 1], positions[index + 4], positions[index + 7]];
const projected = [
sketchReferencePoint(shape, positions[index], positions[index + 2]),
sketchReferencePoint(shape, positions[index + 3], positions[index + 5]),
sketchReferencePoint(shape, positions[index + 6], positions[index + 8]),
];
allProjected.push(...projected);
if (!ys.every((value) => value <= minY + bottomTolerance) || triangleArea2d(projected[0], projected[1], projected[2]) <= tolerance) {
continue;
}
const offset = points.length;
points.push(...projected);
triangles.push([offset, offset + 1, offset + 2]);
}
if (triangles.length > 0) {
return {
fillD: triangles.length <= 5000 ? triangles.map((triangle) => trianglePath(triangle.map((index) => points[index]))).join(" ") : null,
outlineD: boundaryPath(points, triangles, tolerance),
};
}
const hull = convexHull(allProjected);
if (hull.length < 3) return null;
const d = `M ${hull[0].x} ${hull[0].z} ${hull.slice(1).map((point) => `L ${point.x} ${point.z}`).join(" ")} Z`;
return { fillD: d, outlineD: d };
}
export function SketchWorkspace({
profile,
referenceShapes,
@@ -246,6 +403,7 @@ export function SketchWorkspace({
activePointId,
selected,
measurement,
pendingMeasurementStart,
initialSnap,
initialWorkspace,
onPlanePoint,
@@ -270,9 +428,17 @@ export function SketchWorkspace({
const [pan, setPan] = useState({ x: 0, z: 0 });
const [hover, setHover] = useState<{ x: number; z: number } | null>(null);
const [pointerAction, setPointerAction] = useState<PointerAction | null>(null);
const [svgSize, setSvgSize] = useState({ width: 0, height: 0 });
const svgRef = useRef<SVGSVGElement | null>(null);
const width = workspace.width / zoom;
const depth = workspace.depth / zoom;
const screenUnit = useMemo(() => {
const fittedScale = Math.min(
svgSize.width > 0 ? svgSize.width / width : 0,
svgSize.height > 0 ? svgSize.height / depth : 0,
);
return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720;
}, [depth, svgSize.height, svgSize.width, width]);
const displayProfile = useMemo(() => {
if (pointerAction?.kind === "move-point") {
const source = profile.points.find((point) => point.id === pointerAction.pointId);
@@ -356,6 +522,19 @@ export function SketchWorkspace({
};
};
useEffect(() => {
const svg = svgRef.current;
if (!svg) return;
const updateSize = () => {
const bounds = svg.getBoundingClientRect();
setSvgSize({ width: bounds.width, height: bounds.height });
};
updateSize();
const observer = new ResizeObserver(updateSize);
observer.observe(svg);
return () => observer.disconnect();
}, []);
const beginPan = (event: ReactPointerEvent<SVGElement>) => {
event.preventDefault();
event.stopPropagation();
@@ -472,7 +651,12 @@ export function SketchWorkspace({
const measurementLabel = formatDimension(measurementLength, workspace.accuracy);
const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0;
const previewLabel = formatDimension(previewLength, workspace.accuracy);
const pillScale = 1 / zoom;
const labelOffset = 22 * screenUnit;
const pointRadius = 5 * screenUnit;
const controlPointRadius = 6 * screenUnit;
const hoverPointRadius = 5 * screenUnit;
const handleSize = 12 * screenUnit;
const handleRadius = 2 * screenUnit;
const selectedImageBounds = selectedImage ? {
minX: selectedImage.x - selectedImage.width / 2,
maxX: selectedImage.x + selectedImage.width / 2,
@@ -489,6 +673,10 @@ export function SketchWorkspace({
{ id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ },
{ id: "w", x: selectedImageBounds.minX, z: selectedImage.z },
] : [];
const referenceFootprints = useMemo(
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
[referenceShapes],
);
return (
<main className="sketch-workspace-stage">
@@ -556,15 +744,23 @@ export function SketchWorkspace({
))}
</g>
<g className="sketch-reference-shapes" pointerEvents="none">
{referenceShapes.filter((shape) => !shape.hidden).map((shape) => (
{referenceShapes.filter((shape) => !shape.hidden).map((shape) => {
const footprint = referenceFootprints.get(shape.id);
return (
<g key={shape.id} transform={`rotate(${shape.rotation ?? 0} ${shape.x} ${shape.z})`}>
{isRoundReference(shape) ? (
{footprint?.fillD || footprint?.outlineD ? (
<>
{footprint.fillD ? <path className="sketch-reference-mesh-face" d={footprint.fillD} /> : null}
{footprint.outlineD ? <path className="sketch-reference-mesh-outline" d={footprint.outlineD} /> : null}
</>
) : isRoundReference(shape) ? (
<ellipse cx={shape.x} cy={shape.z} rx={shape.width / 2} ry={shape.depth / 2} />
) : (
<rect x={shape.x - shape.width / 2} y={shape.z - shape.depth / 2} width={shape.width} height={shape.depth} />
)}
</g>
))}
);
})}
</g>
<rect className="sketch-plate-border" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} pointerEvents="none" />
{pointerAction?.kind === "marquee" ? (
@@ -604,53 +800,68 @@ export function SketchWorkspace({
const dimension = segmentDimension(segment, pointById);
if (!dimension) return null;
const label = formatDimension(dimension.length, workspace.accuracy);
const pillWidth = Math.max(7.2, label.length * 1.2 + 2.4) * pillScale;
const pillHeight = 4.2 * pillScale;
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<g key={`dimension-${segment.id}`} transform={`translate(${dimension.midpoint.x} ${dimension.midpoint.z - 4 * pillScale})`}>
<rect x={-pillWidth / 2} y={-pillHeight / 2} width={pillWidth} height={pillHeight} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{label}</text>
<g key={`dimension-${segment.id}`} transform={`translate(${dimension.midpoint.x} ${dimension.midpoint.z - labelOffset})`}>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</g>
);
})}
</g>
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? <line className="sketch-preview-line" x1={activePoint.x} y1={activePoint.z} x2={hover.x} y2={hover.z} pointerEvents="none" /> : null}
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? (
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - 4 * pillScale})`}>
<rect x={-(Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{previewLabel}</text>
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - labelOffset})`}>
{(() => {
const pill = dimensionPillSize(previewLabel, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{previewLabel}</text>
</>
);
})()}
</g>
) : null}
{pointerAction?.kind === "bezier" ? (
<g className="sketch-drag-handles" pointerEvents="none">
<line x1={pointerAction.origin.x * 2 - pointerAction.current.x} y1={pointerAction.origin.z * 2 - pointerAction.current.z} x2={pointerAction.current.x} y2={pointerAction.current.z} />
<circle cx={pointerAction.origin.x} cy={pointerAction.origin.z} r={1.2 / Math.sqrt(zoom)} />
<circle cx={pointerAction.origin.x} cy={pointerAction.origin.z} r={controlPointRadius} />
</g>
) : null}
{measurement ? (
<g className="sketch-measurement">
<line x1={measurement.start.x} y1={measurement.start.z} x2={measurement.end.x} y2={measurement.end.z} />
<circle className="sketch-measurement-point" cx={measurement.start.x} cy={measurement.start.z} r={pointRadius} pointerEvents="none" />
<circle className="sketch-measurement-point" cx={measurement.end.x} cy={measurement.end.z} r={pointRadius} pointerEvents="none" />
<g
className="sketch-measurement-pill"
role="button"
aria-label="Remove measurement"
transform={`translate(${(measurement.start.x + measurement.end.x) / 2} ${(measurement.start.z + measurement.end.z) / 2 - 4 * pillScale})`}
transform={`translate(${(measurement.start.x + measurement.end.x) / 2} ${(measurement.start.z + measurement.end.z) / 2 - labelOffset})`}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
onClearMeasurement();
}}
>
<rect x={-(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text x={-0.9 * pillScale} y={0.78 * pillScale} fontSize={2.25 * pillScale}>{measurementLabel}</text>
<text className="remove" x={(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2 - 1.45 * pillScale} y={0.82 * pillScale} fontSize={2.45 * pillScale}>×</text>
<rect x={-dimensionPillSize(measurementLabel, screenUnit, 30).width / 2} y={-dimensionPillSize(measurementLabel, screenUnit, 30).height / 2} width={dimensionPillSize(measurementLabel, screenUnit, 30).width} height={dimensionPillSize(measurementLabel, screenUnit, 30).height} rx={dimensionPillSize(measurementLabel, screenUnit, 30).radius} />
<text x={-5 * screenUnit} y={5 * screenUnit} fontSize={13 * screenUnit}>{measurementLabel}</text>
<text className="remove" x={dimensionPillSize(measurementLabel, screenUnit, 30).width / 2 - 8 * screenUnit} y={5 * screenUnit} fontSize={14 * screenUnit}>x</text>
</g>
</g>
) : null}
{pendingMeasurementStart ? (
<g className="sketch-measurement pending" pointerEvents="none">
{hover ? <line x1={pendingMeasurementStart.x} y1={pendingMeasurementStart.z} x2={hover.x} y2={hover.z} /> : null}
<circle className="sketch-measurement-point pending" cx={pendingMeasurementStart.x} cy={pendingMeasurementStart.z} r={pointRadius} />
{hover ? <circle className="sketch-measurement-point hover" cx={hover.x} cy={hover.z} r={pointRadius} /> : null}
</g>
) : null}
{selectedPoint && tool === "select" ? (
<g className="sketch-curve-handles">
{selectedPoint.handleIn ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleIn.x} y2={selectedPoint.handleIn.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleIn.x} cy={selectedPoint.handleIn.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /></> : null}
{selectedPoint.handleOut ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleOut.x} y2={selectedPoint.handleOut.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleOut.x} cy={selectedPoint.handleOut.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /></> : null}
{selectedPoint.handleIn ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleIn.x} y2={selectedPoint.handleIn.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleIn.x} cy={selectedPoint.handleIn.z} r={controlPointRadius} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /></> : null}
{selectedPoint.handleOut ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleOut.x} y2={selectedPoint.handleOut.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleOut.x} cy={selectedPoint.handleOut.z} r={controlPointRadius} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /></> : null}
</g>
) : null}
<g className="sketch-points">
@@ -661,7 +872,7 @@ export function SketchWorkspace({
key={point.id}
cx={point.x}
cy={point.z}
r={0.82 / Math.sqrt(zoom)}
r={pointRadius}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -689,24 +900,40 @@ export function SketchWorkspace({
height={selectedImage.depth}
pointerEvents="none"
/>
<g className="sketch-image-dimension width" pointerEvents="none" transform={`translate(${selectedImage.x} ${selectedImageBounds.minZ - 4 * pillScale})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.width, workspace.accuracy)}</text>
<g className="sketch-image-dimension width" pointerEvents="none" transform={`translate(${selectedImage.x} ${selectedImageBounds.minZ - labelOffset})`}>
{(() => {
const label = formatDimension(selectedImage.width, workspace.accuracy);
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</>
);
})()}
</g>
<g className="sketch-image-dimension depth" pointerEvents="none" transform={`translate(${selectedImageBounds.maxX + 7 * pillScale} ${selectedImage.z})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.depth, workspace.accuracy)}</text>
<g className="sketch-image-dimension depth" pointerEvents="none" transform={`translate(${selectedImageBounds.maxX + 34 * screenUnit} ${selectedImage.z})`}>
{(() => {
const label = formatDimension(selectedImage.depth, workspace.accuracy);
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</>
);
})()}
</g>
{imageResizeHandles.map((handle) => (
<rect
key={handle.id}
data-sketch-entity="image-handle"
className={`sketch-image-resize-handle handle-${handle.id}`}
x={handle.x - 1.05 * pillScale}
y={handle.z - 1.05 * pillScale}
width={2.1 * pillScale}
height={2.1 * pillScale}
rx={0.2 * pillScale}
x={handle.x - handleSize / 2}
y={handle.z - handleSize / 2}
width={handleSize}
height={handleSize}
rx={handleRadius}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
@@ -728,7 +955,7 @@ export function SketchWorkspace({
))}
</g>
) : null}
{hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? <circle className="sketch-cursor-point" cx={hover.x} cy={hover.z} r={0.7 / Math.sqrt(zoom)} pointerEvents="none" /> : null}
{hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? <circle className="sketch-cursor-point" cx={hover.x} cy={hover.z} r={hoverPointRadius} pointerEvents="none" /> : null}
</svg>
</section>
{selectedImage && tool === "select" ? (
+158 -36
View File
@@ -19,6 +19,7 @@ import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } fro
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
TransformOverlay,
getElevationMeasureKey,
@@ -89,6 +90,7 @@ const preservedImportedGeometryCache = new WeakMap<WorkplaneShape, THREE.BufferG
const imageTextureLoader = new THREE.TextureLoader();
const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000;
const NORMAL_IMPORTED_SELECTION_EDGE_ANGLE = 60;
const MODIFIER_EDGE_PICK_RADIUS_PX = 14;
function parseDroppedShapeAsset(raw: string): ShapeAsset | null {
try {
@@ -146,6 +148,8 @@ type WorkplaneViewportProps = {
onSetPlacementElevation: (elevation: number, source: "shape" | "base") => void;
onInteractionActiveChange?: (active: boolean) => void;
onEditSketch?: () => void;
canSeparateParts?: boolean;
onSeparateParts?: () => void;
onUpdateShape: (id: string, patch: ShapeUpdatePatch) => void;
onWorkspaceSettingsChange?: (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
onWorkplaneModeChange: (active: boolean) => void;
@@ -219,6 +223,7 @@ declare global {
get: () => ViewportPerfStats;
};
sketchforgeCaptureCanvas?: () => string;
sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise<string> | string;
}
}
@@ -523,6 +528,51 @@ function projectToScreen(point: THREE.Vector3, state: ThreeState) {
};
}
function distanceToScreenSegment(x: number, y: number, ax: number, ay: number, bx: number, by: number) {
const dx = bx - ax;
const dy = by - ay;
const lengthSq = dx * dx + dy * dy;
const amount = lengthSq > 0.0001 ? clamp(((x - ax) * dx + (y - ay) * dy) / lengthSq, 0, 1) : 0;
return Math.hypot(x - (ax + dx * amount), y - (ay + dy * amount));
}
function projectCadPointToCanvas(point: THREE.Vector3, state: ThreeState, rect: DOMRect) {
const projected = point.clone().project(state.camera);
if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y) || projected.z < -1 || projected.z > 1) {
return null;
}
return {
x: ((projected.x + 1) / 2) * rect.width,
y: ((1 - projected.y) / 2) * rect.height,
};
}
function pickModifierEdgeFromScreen(state: ThreeState, edges: CadModifierEdge[], clientX: number, clientY: number) {
const rect = state.renderer.domElement.getBoundingClientRect();
const pointerX = clientX - rect.left;
const pointerY = clientY - rect.top;
const pointA = new THREE.Vector3();
const pointB = new THREE.Vector3();
let nearestId: number | null = null;
let nearestDistance = MODIFIER_EDGE_PICK_RADIUS_PX;
state.camera.updateMatrixWorld();
edges.forEach((edge) => {
for (let index = 0; index + 5 < edge.points.length; index += 3) {
pointA.set(edge.points[index], edge.points[index + 1], edge.points[index + 2]);
pointB.set(edge.points[index + 3], edge.points[index + 4], edge.points[index + 5]);
const a = projectCadPointToCanvas(pointA, state, rect);
const b = projectCadPointToCanvas(pointB, state, rect);
if (!a || !b) continue;
const distance = distanceToScreenSegment(pointerX, pointerY, a.x, a.y, b.x, b.y);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestId = edge.id;
}
}
});
return nearestId;
}
function syncRulerOverlay(
state: ThreeState,
model: RulerModel,
@@ -1112,6 +1162,8 @@ export function WorkplaneViewport({
onSetPlacementElevation,
onInteractionActiveChange,
onEditSketch,
canSeparateParts = false,
onSeparateParts,
onUpdateShape,
onWorkspaceSettingsChange,
onWorkplaneModeChange,
@@ -1170,6 +1222,8 @@ export function WorkplaneViewport({
const mirrorModeRef = useRef(mirrorMode);
const modifierActiveRef = useRef(modifierActive);
const modifierPreviewActiveRef = useRef(modifierPreviewActive);
const modifierEdgesRef = useRef(modifierEdges);
const [hoverModifierEdgeId, setHoverModifierEdgeId] = useState<number | null>(null);
const selectedIdsKeyRef = useRef(selectedIds.join("|"));
const perfRef = useRef({
fps: 0,
@@ -1186,8 +1240,9 @@ export function WorkplaneViewport({
);
useEffect(() => {
rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive);
}, [modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]);
modifierEdgesRef.current = modifierEdges;
rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive, hoverModifierEdgeId);
}, [hoverModifierEdgeId, modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]);
const placementElevationRef = useRef(placementElevation);
const workplaneModeRef = useRef(workplaneMode);
@@ -1259,10 +1314,11 @@ export function WorkplaneViewport({
useEffect(() => {
shapesRef.current = shapes;
rebuildShapes(threeRef.current, shapes, renderSelectionIds(), !transformRef.current && !dragRef.current);
refreshDragPreviewObjects(threeRef.current, dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
shapes,
previewShapesForDrag(shapes, dragRef.current),
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
@@ -1306,10 +1362,11 @@ export function WorkplaneViewport({
}
selectedIdsRef.current = selectedIds;
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), !transformRef.current && !dragRef.current);
refreshDragPreviewObjects(threeRef.current, dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
shapesRef.current,
previewShapesForDrag(shapesRef.current, dragRef.current),
selectedIds,
transformOverlayRef,
setTransformOverlay,
@@ -1324,6 +1381,7 @@ export function WorkplaneViewport({
useEffect(() => {
modifierActiveRef.current = modifierActive;
if (!modifierActive) setHoverModifierEdgeId(null);
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current);
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierActive, renderSelectionIds]);
@@ -1334,6 +1392,12 @@ export function WorkplaneViewport({
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierPreviewActive, renderSelectionIds]);
useEffect(() => {
if (hoverModifierEdgeId !== null && !modifierEdges.some((edge) => edge.id === hoverModifierEdgeId)) {
setHoverModifierEdgeId(null);
}
}, [hoverModifierEdgeId, modifierEdges]);
useEffect(() => {
alignModeRef.current = alignMode;
alignAnchorIdRef.current = alignAnchorId;
@@ -1411,6 +1475,17 @@ export function WorkplaneViewport({
state.renderer.render(state.scene, state.camera);
return state.renderer.domElement.toDataURL("image/png");
};
window.sketchforgeCaptureView = (face = "current") => {
if (face === "home") {
resetCamera(state);
} else if (face !== "current") {
setCameraToViewFace(state, face);
}
syncViewCube(state, viewCubeRef.current);
state.camera.updateMatrixWorld();
state.renderer.render(state.scene, state.camera);
return state.renderer.domElement.toDataURL("image/png");
};
perfRef.current.lastSample = performance.now();
resetCamera(state);
rebuildShapes(state, shapesRef.current, renderSelectionIds());
@@ -1483,6 +1558,9 @@ export function WorkplaneViewport({
if (window.sketchforgeCaptureCanvas) {
delete window.sketchforgeCaptureCanvas;
}
if (window.sketchforgeCaptureView) {
delete window.sketchforgeCaptureView;
}
threeRef.current = null;
};
}, []);
@@ -2199,14 +2277,16 @@ export function WorkplaneViewport({
const pickModifierEdge = useCallback((clientX: number, clientY: number) => {
const state = threeRef.current;
if (!state) return null;
const rect = state.renderer.domElement.getBoundingClientRect();
state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
state.raycaster.setFromCamera(state.pointer, state.camera);
const hit = state.raycaster
.intersectObjects(state.modifierLayer.children, true)
.find((entry) => typeof entry.object.userData.modifierEdgeId === "number");
return hit ? hit.object.userData.modifierEdgeId as number : null;
return pickModifierEdgeFromScreen(state, modifierEdgesRef.current, clientX, clientY);
}, []);
const updateModifierEdgeHover = useCallback((clientX: number, clientY: number) => {
const edgeId = pickModifierEdge(clientX, clientY);
setHoverModifierEdgeId((current) => (current === edgeId ? current : edgeId));
}, [pickModifierEdge]);
const clearModifierEdgeHover = useCallback(() => {
setHoverModifierEdgeId((current) => (current === null ? current : null));
}, []);
const pickTransformHandle = useCallback((clientX: number, clientY: number) => {
@@ -2497,6 +2577,10 @@ export function WorkplaneViewport({
const handlePointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (modifierActiveRef.current) {
updateModifierEdgeHover(event.clientX, event.clientY);
return;
}
if (rulerModeRef.current) {
updateRulerHover(event.clientX, event.clientY);
return;
@@ -2542,21 +2626,7 @@ export function WorkplaneViewport({
drag.items.forEach((item) => {
item.nextX = clamp(item.startX + deltaX, -workspaceRef.current.width / 2 + 6, workspaceRef.current.width / 2 - 6);
item.nextZ = clamp(item.startZ + deltaZ, -workspaceRef.current.depth / 2 + 6, workspaceRef.current.depth / 2 - 6);
if (item.visual) {
if (!item.hadPreviewSimplified) {
setComplexEdgeVisibility(item.visual, false);
item.hadPreviewSimplified = true;
}
item.visual.position.x = item.nextX;
item.visual.position.z = item.nextZ;
}
if (item.helper && item.helperBox) {
item.helper.box.copy(item.helperBox);
item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ));
item.helper.updateMatrixWorld(true);
}
if (threeRef.current) applyDragItemPreview(threeRef.current, item);
});
if (threeRef.current) {
const previewShapes = previewShapesForDrag(shapesRef.current, drag);
@@ -2574,9 +2644,13 @@ export function WorkplaneViewport({
threeRef.current.needsRender = true;
}
},
[setMarqueeFromState, toPlanePoint, updateRulerHover, updateTransform],
[setMarqueeFromState, toPlanePoint, updateModifierEdgeHover, updateRulerHover, updateTransform],
);
const handlePointerLeave = useCallback(() => {
if (modifierActiveRef.current) clearModifierEdgeHover();
}, [clearModifierEdgeHover]);
const finishDrag = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const state = threeRef.current;
@@ -2846,7 +2920,7 @@ export function WorkplaneViewport({
</button>
</div>
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""}`} aria-label="Workplane">
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""} ${modifierActive ? "modifier-edge-pick" : ""}`} aria-label="Workplane">
<div className="workplane-plane">
<div
className="three-workplane-host"
@@ -2860,6 +2934,7 @@ export function WorkplaneViewport({
onPointerMove={handlePointerMove}
onPointerUp={finishDrag}
onPointerCancel={finishDrag}
onPointerLeave={handlePointerLeave}
/>
{marqueeRect ? <div className="selection-marquee" style={marqueeRect} /> : null}
{transformOverlay && !alignMode && !mirrorMode && !rulerMode && !modifierActive ? (
@@ -2909,12 +2984,14 @@ export function WorkplaneViewport({
shape={selectedShape}
snap={snap}
snapOpen={snapOpen}
accuracy={workspace.accuracy}
workspace={workspace}
onUpdate={(patch, options) => onUpdateShape(selectedShape.id, patchWithResizeAnchor(selectedShape, patch, options?.resizeAxis, lastResizeAnchorRef.current))}
onClose={() => onSelectShape(null)}
onSnapChange={setSnap}
onSnapOpenChange={setSnapOpen}
onEditSketch={selectedShape.sketchProfile ? onEditSketch : undefined}
canSeparateParts={canSeparateParts}
onSeparateParts={onSeparateParts}
/>
) : null}
@@ -3442,7 +3519,16 @@ function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selec
rebuildSelectionHelpers(state, shapes, selectedIds);
}
function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false) {
function modifierEdgeMaterialStyle(active: boolean, hovered: boolean, previewActive: boolean) {
const subduedSelectedPreviewEdge = previewActive && active && !hovered;
return {
color: active ? (hovered ? "#ffbf45" : "#ff8a1d") : hovered ? "#84edff" : "#17b7e5",
opacity: subduedSelectedPreviewEdge ? 0.18 : active || hovered ? 1 : 0.72,
linewidth: active || hovered ? 3 : 1,
};
}
function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false, hoverId: number | null = null) {
if (!state) return;
disposeChildren(state.modifierLayer);
const selected = new Set(selectedIds);
@@ -3451,17 +3537,19 @@ function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[]
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(edge.points, 3));
const active = selected.has(edge.id);
const subduedSelectedPreviewEdge = previewActive && active;
const hovered = hoverId === edge.id;
const style = modifierEdgeMaterialStyle(active, hovered, previewActive);
const material = new THREE.LineBasicMaterial({
color: active ? "#ff8a1d" : "#17b7e5",
color: style.color,
depthTest: false,
depthWrite: false,
transparent: true,
opacity: subduedSelectedPreviewEdge ? 0.18 : active ? 1 : 0.82,
opacity: style.opacity,
linewidth: style.linewidth,
});
const line = new THREE.Line(geometry, material);
line.userData.modifierEdgeId = edge.id;
line.renderOrder = active ? 1002 : 1001;
line.renderOrder = hovered ? 1003 : active ? 1002 : 1001;
state.modifierLayer.add(line);
});
state.needsRender = true;
@@ -4089,6 +4177,39 @@ function findSelectedGroundFootprint(state: ThreeState, id: string) {
return state.helperLayer.children.find((child) => child.name === "SelectedGroundFootprint" && child.userData.shapeId === id) ?? null;
}
function applyDragItemPreview(state: ThreeState, item: DragItem) {
if (!item.visual || !item.visual.parent) {
item.visual = findShapeObject(state, item.id);
}
if (!item.helper || !item.helper.parent) {
item.helper = findSelectionHelper(state, item.id);
item.helperBox = item.helper ? item.helper.box.clone() : null;
}
if (item.visual) {
if (!item.hadPreviewSimplified) {
setComplexEdgeVisibility(item.visual, false);
item.hadPreviewSimplified = true;
}
item.visual.position.x = item.nextX;
item.visual.position.z = item.nextZ;
item.visual.updateMatrixWorld(true);
}
if (item.helper && item.helperBox) {
item.helper.box.copy(item.helperBox);
item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ));
item.helper.updateMatrixWorld(true);
}
}
function refreshDragPreviewObjects(state: ThreeState | null, drag: DragState | null) {
if (!state || !drag) return;
drag.items.forEach((item) => applyDragItemPreview(state, item));
updateSelectedGroundFootprintPreviews(state, drag);
state.needsRender = true;
}
function updateSelectedGroundFootprintPreviews(state: ThreeState, drag: DragState) {
drag.items.forEach((item) => {
const footprint = findSelectedGroundFootprint(state, item.id);
@@ -4822,8 +4943,9 @@ function createHalfSphereGeometry(width: number, height: number, depth: number,
function disposeChildren(group: THREE.Group) {
while (group.children.length > 0) {
const child = group.children.pop();
const child = group.children[group.children.length - 1];
if (child) {
group.remove(child);
disposeObject(child);
}
}
+4 -16
View File
@@ -148,24 +148,12 @@ export function ToolbarMirrorIcon() {
return <ToolbarCommandImage file="toolbar-mirror.png" className="toolbar-user-art-icon" />;
}
export function ToolbarChamferIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17 18 11h18v18l-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
export function ToolbarChamferIcon() {
return <ToolbarCommandImage file="toolbar-chamfer.png" className="toolbar-user-art-icon" />;
}
export function ToolbarFilletIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17c0-3.3 2.7-6 6-6h18v18c0 3.9-3.1 7-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="M12 17c0-3.3 2.7-6 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
export function ToolbarFilletIcon() {
return <ToolbarCommandImage file="toolbar-fillet.png" className="toolbar-user-art-icon" />;
}
export function ToolbarPreserveEdgeIcon(props: IconProps) {
@@ -1,7 +1,128 @@
"use client";
import { Check, LoaderCircle, X } from "lucide-react";
import { useEffect, useState, type CSSProperties } from "react";
import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
const EDGE_MODIFIER_AMOUNT_STEP = 0.001;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatSliderValue(value: number, accuracy: WorkplaneWorkspaceSettings["accuracy"], step: number) {
if (step >= 1) return String(Math.round(value));
return formatMeasurementNumber(value, accuracy, step);
}
type EdgeHistoryOption = {
id: string;
label: string;
targetName: string;
removesNewerCount: number;
};
function EdgeModifierSlider({
label,
value,
min,
max,
step,
unit,
workspace,
length = false,
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
step: number;
unit?: string;
workspace: WorkplaneWorkspaceSettings;
length?: boolean;
onChange: (value: number) => void;
}) {
const safeMin = Number.isFinite(min) ? min : 0;
const safeMax = Math.max(safeMin, Number.isFinite(max) ? max : safeMin);
const actualValue = Number.isFinite(value) ? value : safeMin;
const controlValue = length ? millimetersToDisplay(actualValue, workspace) : actualValue;
const controlMin = length ? millimetersToDisplay(safeMin, workspace) : safeMin;
const controlMax = length ? millimetersToDisplay(safeMax, workspace) : safeMax;
const controlStep = length ? displayStepFromMillimeters(step, workspace) : step;
const sliderValue = clamp(controlValue, controlMin, controlMax);
const position = ((sliderValue - controlMin) / Math.max(Number.EPSILON, controlMax - controlMin)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatSliderValue(controlValue, workspace.accuracy, controlStep));
const unitLabel = length ? lengthDisplayUnit(workspace).label : unit;
useEffect(() => {
if (!editing) {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
}
}, [controlStep, controlValue, editing, workspace.accuracy]);
const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
onChange(clamp(toModelValue(finiteNext), safeMin, safeMax));
setEditing(false);
};
const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
onChange(clamp(toModelValue(next), safeMin, safeMax));
setDraft(formatSliderValue(next, workspace.accuracy, controlStep));
};
return (
<label className="edge-modifier-field edge-modifier-slider range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span className="range-property-header">
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={controlMax}
step={controlStep}
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal"
onFocus={() => {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(true);
}}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(false);
}
}}
/>
{unitLabel ? <span className="range-value-unit">{unitLabel}</span> : null}
</span>
</span>
<div className="range-control">
<input
type="range"
min={controlMin}
max={controlMax}
step={controlStep}
value={sliderValue}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</div>
</label>
);
}
export function EdgeModifierPanel({
kind,
@@ -10,12 +131,14 @@ export function EdgeModifierPanel({
chamferAngle,
quality,
sharpAngle,
workspace,
tangentChain,
preserveEdgeSize,
targetName,
groupedCount,
appliedFeatureCount,
reversibleFeatureCount,
historyOptions,
selectedCount,
availableCount,
busy,
@@ -28,7 +151,7 @@ export function EdgeModifierPanel({
onPreserveEdgeSizeChange,
onSelectAll,
onClear,
onRemoveLastFeature,
onRemoveFeature,
onApply,
onCancel,
}: {
@@ -38,12 +161,14 @@ export function EdgeModifierPanel({
chamferAngle: number;
quality: CadModifierQuality;
sharpAngle: number;
workspace: WorkplaneWorkspaceSettings;
tangentChain: boolean;
preserveEdgeSize: boolean;
targetName: string;
groupedCount: number;
appliedFeatureCount: number;
reversibleFeatureCount: number;
historyOptions: EdgeHistoryOption[];
selectedCount: number;
availableCount: number;
busy: boolean;
@@ -56,11 +181,14 @@ export function EdgeModifierPanel({
onPreserveEdgeSizeChange: (value: boolean) => void;
onSelectAll: () => void;
onClear: () => void;
onRemoveLastFeature: () => void;
onRemoveFeature: (id: string) => void;
onApply: () => void;
onCancel: () => void;
}) {
const [historyOpen, setHistoryOpen] = useState(false);
const title = kind === "fillet" ? "Fillet edges" : "Chamfer edges";
const amountMin = Math.min(MIN_EDGE_MODIFIER_AMOUNT, Math.max(Number.EPSILON, maxAmount));
const amountMax = Math.max(amountMin, maxAmount);
return (
<aside className="edge-modifier-panel" aria-label={title}>
<div className="edge-modifier-header">
@@ -87,55 +215,50 @@ export function EdgeModifierPanel({
{appliedFeatureCount > 0 ? (
<div className="edge-modifier-history-actions">
<button type="button" disabled={reversibleFeatureCount === 0} onClick={onRemoveLastFeature}>
Remove last edge feature
<button
className="edge-modifier-history-toggle"
type="button"
aria-expanded={historyOpen}
disabled={reversibleFeatureCount === 0}
onClick={() => setHistoryOpen((open) => !open)}
>
{historyOpen ? <Minus size={15} /> : <Plus size={15} />}
<span>Edge feature history</span>
</button>
{reversibleFeatureCount === 0 ? <span>Older edge features do not have stored undo history.</span> : null}
{historyOpen && historyOptions.length > 0 ? (
<div className="edge-modifier-history-list">
{historyOptions.map((option) => (
<button className="edge-modifier-history-item" type="button" key={option.id} onClick={() => onRemoveFeature(option.id)}>
<RotateCcw size={14} />
<span>
<strong>{option.label}</strong>
<small>
{option.targetName}
{option.removesNewerCount > 0 ? ` · also removes ${option.removesNewerCount} newer` : ""}
</small>
</span>
</button>
))}
</div>
) : null}
</div>
) : null}
<label className="edge-modifier-field">
<span>{kind === "fillet" ? "Radius" : "Distance"}</span>
<div className="edge-modifier-value-row">
<input
type="range"
min="0.05"
max={Math.max(0.05, maxAmount)}
step="0.05"
value={Math.min(amount, maxAmount)}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
/>
<input
type="number"
min="0.05"
max={maxAmount}
step="0.05"
<EdgeModifierSlider
label={kind === "fillet" ? "Radius" : "Distance"}
value={amount}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
min={amountMin}
max={amountMax}
step={EDGE_MODIFIER_AMOUNT_STEP}
workspace={workspace}
length
onChange={onAmountChange}
/>
<span>mm</span>
</div>
</label>
{kind === "chamfer" ? (
<label className="edge-modifier-field">
<span>Angle</span>
<div className="edge-modifier-value-row">
<input type="range" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
) : null}
{kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} onChange={onChamferAngleChange} /> : null}
<label className="edge-modifier-field">
<span>Sharp-edge threshold</span>
<div className="edge-modifier-value-row">
<input type="range" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
<EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={120} step={1} unit="deg" workspace={workspace} onChange={onSharpAngleChange} />
<label className="edge-modifier-check">
<input type="checkbox" checked={tangentChain} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
@@ -1,10 +1,11 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen } from "lucide-react";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen, Split } from "lucide-react";
import { useEffect, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, MeasurementAccuracy, WorkplaneShape } from "@/types/sketchforge";
import type { GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_SHAPE_SIZE = 0.01;
@@ -73,9 +74,13 @@ function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatPanelNumber(value: number, accuracy: MeasurementAccuracy) {
const zeroThreshold = 0.5 * 10 ** -accuracy;
return (Math.abs(value) < zeroThreshold ? 0 : value).toFixed(accuracy);
function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step: number) {
if (step >= 1) return String(Math.round(value));
return formatMeasurementNumber(value, accuracy, step);
}
function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
@@ -92,8 +97,6 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
if (shape.kind === "box") {
return [
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ 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 },
@@ -197,22 +200,26 @@ export function ShapeInspector({
shape,
snap,
snapOpen,
accuracy,
workspace,
onUpdate,
onClose,
onSnapChange,
onSnapOpenChange,
onEditSketch,
canSeparateParts = false,
onSeparateParts,
}: {
shape: WorkplaneShape;
snap: GridSize;
snapOpen: boolean;
accuracy: MeasurementAccuracy;
workspace: WorkplaneWorkspaceSettings;
onUpdate: ShapeInspectorUpdate;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
onEditSketch?: () => void;
canSeparateParts?: boolean;
onSeparateParts?: () => void;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
@@ -310,6 +317,13 @@ export function ShapeInspector({
</button>
) : null}
{canSeparateParts && onSeparateParts ? (
<button className="inspector-action-button" type="button" disabled={locked} onClick={onSeparateParts}>
<Split size={17} strokeWidth={2.5} />
<span>Separate Parts</span>
</button>
) : null}
<div className="property-card">
<button
className="property-card-header"
@@ -330,7 +344,7 @@ export function ShapeInspector({
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} accuracy={accuracy} disabled={locked} />;
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} />;
})}
</div>
) : null}
@@ -386,76 +400,81 @@ function RangeProperty({
min,
max,
step = 0.01,
accuracy,
workspace,
disabled,
onChange,
}: RangePropertyConfig & { accuracy: MeasurementAccuracy; disabled?: boolean }) {
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean }) {
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
const isLength = propertyUsesLengthUnit(label);
const accuracy = workspace.accuracy;
const actualValue = Math.max(min, Number.isFinite(value) ? value : min);
const sliderValue = clamp(actualValue, min, max);
const position = ((sliderValue - min) / Math.max(1, max - min)) * 100;
const controlValue = isLength ? millimetersToDisplay(actualValue, workspace) : actualValue;
const controlMin = isLength ? millimetersToDisplay(min, workspace) : min;
const controlMax = isLength ? millimetersToDisplay(max, workspace) : max;
const controlStep = isLength ? displayStepFromMillimeters(step, workspace) : step;
const sliderValue = clamp(controlValue, controlMin, controlMax);
const position = ((sliderValue - controlMin) / Math.max(Number.EPSILON, controlMax - controlMin)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPanelNumber(actualValue, accuracy));
const [draft, setDraft] = useState(formatPropertyNumber(controlValue, accuracy, controlStep));
const unit = isLength ? lengthDisplayUnit(workspace).label : null;
useEffect(() => {
if (!editing) {
setDraft(formatPanelNumber(actualValue, accuracy));
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
}
}, [accuracy, actualValue, editing]);
}, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const finiteNext = Number.isFinite(next) ? next : actualValue;
onChange(allowsAboveSliderMax ? Math.max(min, finiteNext) : clamp(finiteNext, min, max));
const finiteNext = Number.isFinite(next) ? next : controlValue;
const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
setEditing(false);
};
const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
onChange(clamp(toModelValue(next), min, max));
setDraft(formatPropertyNumber(next, accuracy, controlStep));
};
return (
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span>{label}</span>
<div className="range-control">
{editing ? (
<span className="range-property-header">
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
className="range-value-input"
type="number"
min={min}
max={allowsAboveSliderMax ? undefined : max}
step={step}
value={draft}
autoFocus
min={controlMin}
max={allowsAboveSliderMax ? undefined : controlMax}
step={controlStep}
value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)}
disabled={disabled}
inputMode="decimal"
onFocus={() => {
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(true);
}}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatPanelNumber(actualValue, accuracy));
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(false);
}
}}
/>
) : (
<output
onDoubleClick={(event) => {
if (disabled) {
return;
}
event.preventDefault();
setDraft(formatPanelNumber(actualValue, accuracy));
setEditing(true);
}}
>
{formatPanelNumber(actualValue, accuracy)}
</output>
)}
{unit ? <span className="range-value-unit">{unit}</span> : null}
</span>
</span>
<div className="range-control">
<input
type="range"
min={min}
max={max}
step={step}
min={controlMin}
max={controlMax}
step={controlStep}
value={sliderValue}
disabled={disabled}
onChange={(event) => {
const next = Number(event.currentTarget.value);
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
}}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</div>
</label>
@@ -2,6 +2,7 @@
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useState, type CSSProperties } from "react";
import { normalizeScaleForUnits, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -51,9 +52,12 @@ export function WorkspaceSettingsModal({
}) {
const [defaultSaved, setDefaultSaved] = useState(false);
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
onWorkspaceChange({ ...workspace, ...patch });
const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
};
const setDimension = (key: "width" | "depth", value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
@@ -151,13 +155,13 @@ export function WorkspaceSettingsModal({
<WorkspaceSelect
label="Units"
value={workspace.units}
options={["Metric (Default)", "Imperial", "Bricks"]}
options={WORKSPACE_UNIT_OPTIONS}
onChange={(units) => patchWorkspace({ units })}
/>
<WorkspaceSelect
label="Scale"
value={workspace.scale}
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
value={scaleValue}
options={scaleOptions}
onChange={(scale) => patchWorkspace({ scale })}
/>
<WorkspaceSelect
+249
View File
@@ -0,0 +1,249 @@
import * as THREE from "three";
import type { WorkplaneShape } from "@/types/sketchforge";
import type { CadModifierPrimitivePart } from "@/lib/cadModifierTypes";
import { mirrorSign, resizedImportedCoordinates, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
export type BakedCadMetadataFrame = {
centerX: number;
minY: number;
centerZ: number;
width: number;
depth: number;
height: number;
yawDegrees: number;
};
export function cadTransformToMatrix(transform: number[] | undefined) {
if (!transform || transform.length !== 12 || !transform.every(Number.isFinite)) {
return new THREE.Matrix4();
}
return new THREE.Matrix4().set(
transform[0], transform[1], transform[2], transform[3],
transform[4], transform[5], transform[6], transform[7],
transform[8], transform[9], transform[10], transform[11],
0, 0, 0, 1,
);
}
export function cadTransformFromMatrix(matrix: THREE.Matrix4) {
const elements = matrix.elements;
return [
elements[0], elements[4], elements[8], elements[12],
elements[1], elements[5], elements[9], elements[13],
elements[2], elements[6], elements[10], elements[14],
];
}
function isIdentityCadTransform(transform: number[]) {
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
return transform.every((value, index) => Math.abs(value - identity[index]) < 1e-9);
}
function allFinitePositive(values: number[]) {
return values.every((value) => Number.isFinite(value) && value > 0);
}
export function cadModifierPrimitiveForAnalyticBox(shape: WorkplaneShape): CadModifierPrimitivePart | null {
if (shape.kind !== "box" || shape.importedMesh || shape.groupedShapes?.length) {
return null;
}
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const height = shape.height;
if (!allFinitePositive([width, depth, height])) {
return null;
}
const centerY = height / 2;
const matrix = new THREE.Matrix4()
.makeTranslation(shape.x, (shape.elevation ?? 0) + centerY, shape.z)
.multiply(new THREE.Matrix4().makeRotationFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation ?? 0),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
),
))
.multiply(new THREE.Matrix4().makeScale(mirrorSign(shape.mirrorX), mirrorSign(shape.mirrorY), mirrorSign(shape.mirrorZ)))
.multiply(new THREE.Matrix4().makeTranslation(0, -centerY, 0));
const transform = cadTransformFromMatrix(matrix);
return {
kind: "box",
width,
depth,
height,
transform: isIdentityCadTransform(transform) ? undefined : transform,
};
}
export function cadModifierPrimitiveForBakedShape(shape: WorkplaneShape): CadModifierPrimitivePart | null {
const primitive = shape.cadPrimitiveFrame;
const frame = primitive?.frame;
if (!primitive || primitive.kind !== "box" || !frame) {
return null;
}
if (!allFinitePositive([
primitive.width,
primitive.depth,
primitive.height,
frame.width,
frame.depth,
frame.height,
shapeWidth(shape),
shapeDepth(shape),
shape.height,
])) {
return null;
}
const centerY = shape.height / 2;
const scaleX = shapeWidth(shape) / frame.width;
const scaleY = shape.height / frame.height;
const scaleZ = shapeDepth(shape) / frame.depth;
const mirrorX = mirrorSign(shape.mirrorX);
const mirrorY = mirrorSign(shape.mirrorY);
const mirrorZ = mirrorSign(shape.mirrorZ);
const matrix = new THREE.Matrix4()
.makeTranslation(shape.x, (shape.elevation ?? 0) + centerY, shape.z)
.multiply(new THREE.Matrix4().makeRotationFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation ?? 0),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
),
))
.multiply(new THREE.Matrix4().makeTranslation(0, -mirrorY * centerY, 0))
.multiply(new THREE.Matrix4().makeScale(mirrorX * scaleX, mirrorY * scaleY, mirrorZ * scaleZ))
.multiply(new THREE.Matrix4().makeTranslation(-frame.x, -frame.elevation, -frame.z))
.multiply(cadTransformToMatrix(frame.sourceTransform));
const transform = cadTransformFromMatrix(matrix);
return {
kind: primitive.kind,
width: primitive.width,
depth: primitive.depth,
height: primitive.height,
transform: isIdentityCadTransform(transform) ? undefined : transform,
};
}
export function cadBrepTransformForShape(shape: WorkplaneShape) {
const frame = shape.cadBrepFrame;
if (!frame) return undefined;
const oldCenter = new THREE.Vector3(frame.x, frame.elevation + frame.height / 2, frame.z);
const currentCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z);
const rotation = new THREE.Quaternion().setFromEuler(new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation ?? 0),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
));
const scale = new THREE.Vector3(
shapeWidth(shape) / Math.max(0.001, frame.width) * mirrorSign(shape.mirrorX),
shape.height / Math.max(0.001, frame.height) * mirrorSign(shape.mirrorY),
shapeDepth(shape) / Math.max(0.001, frame.depth) * mirrorSign(shape.mirrorZ),
);
const matrix = new THREE.Matrix4()
.compose(currentCenter, rotation, scale)
.multiply(new THREE.Matrix4().makeTranslation(-oldCenter.x, -oldCenter.y, -oldCenter.z))
.multiply(cadTransformToMatrix(frame.sourceTransform));
const result = cadTransformFromMatrix(matrix);
return isIdentityCadTransform(result) ? undefined : result;
}
function bakeCadDisplayEdgesForShape(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
if (!shape.cadDisplayEdges?.length) {
return undefined;
}
const centerY = shape.height / 2;
const matrix = new THREE.Matrix4().makeRotationFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(frame.yawDegrees),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
),
);
const xMirror = mirrorSign(shape.mirrorX);
const yMirror = mirrorSign(shape.mirrorY);
const zMirror = mirrorSign(shape.mirrorZ);
const bakedEdges = shape.cadDisplayEdges.flatMap((edge) => {
if (edge.points.length < 6) {
return [];
}
const resizedPoints = resizedImportedCoordinates(shape, edge.points);
const points: number[] = [];
for (let index = 0; index + 2 < resizedPoints.length; index += 3) {
const vertex = new THREE.Vector3(
resizedPoints[index] * xMirror,
(resizedPoints[index + 1] - centerY) * yMirror,
resizedPoints[index + 2] * zMirror,
).applyMatrix4(matrix);
const x = vertex.x + shape.x - frame.centerX;
const y = vertex.y + (shape.elevation ?? 0) + centerY - frame.minY;
const z = vertex.z + shape.z - frame.centerZ;
if ([x, y, z].every(Number.isFinite)) {
points.push(x, y, z);
}
}
return points.length >= 6 ? [{ points }] : [];
});
return bakedEdges.length > 0 ? bakedEdges : undefined;
}
function bakeCadPrimitiveFrameForShapeTransform(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
const primitive = cadModifierPrimitiveForBakedShape(shape) ?? cadModifierPrimitiveForAnalyticBox(shape);
if (!primitive) {
return undefined;
}
return {
kind: primitive.kind,
width: primitive.width,
depth: primitive.depth,
height: primitive.height,
frame: {
x: frame.centerX,
z: frame.centerZ,
elevation: frame.minY,
width: frame.width,
depth: frame.depth,
height: frame.height,
...(primitive.transform ? { sourceTransform: primitive.transform } : {}),
},
};
}
export function bakeCadMetadataForShapeTransform(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
const cadDisplayEdges = bakeCadDisplayEdgesForShape(shape, frame);
const sourceTransform = cadBrepTransformForShape(shape);
const cadPrimitiveFrame = bakeCadPrimitiveFrameForShapeTransform(shape, frame);
const cadBrepFrame = shape.cadBrep && shape.cadBrepFrame
? {
x: frame.centerX,
z: frame.centerZ,
elevation: frame.minY,
width: frame.width,
depth: frame.depth,
height: frame.height,
...(sourceTransform ? { sourceTransform } : {}),
}
: undefined;
return {
cadDisplayEdges,
cadDisplayEdgesVersion: cadDisplayEdges ? (2 as const) : undefined,
cadBrep: cadBrepFrame ? shape.cadBrep : undefined,
cadBrepFrame,
cadPrimitiveFrame,
};
}
+25 -2
View File
@@ -2,7 +2,10 @@ export type CadModifierKind = "chamfer" | "fillet";
export type CadModifierEdge = {
id: number;
owner?: number;
points: number[];
display: boolean;
selectable: boolean;
angle: number;
boundary: boolean;
manifold: boolean;
@@ -14,16 +17,35 @@ export type CadModifierDisplayEdge = {
points: number[];
};
export type CadModifierPrimitivePart = {
kind: "box";
width: number;
depth: number;
height: number;
transform?: number[];
};
export type CadModifierMeshPart = {
positions?: Float32Array;
indices?: Uint32Array;
brep?: string;
brepTransform?: number[];
primitive?: CadModifierPrimitivePart;
hole: boolean;
};
export type CadModifierComponentMesh = {
owner: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
triangleCount: number;
brep: string;
displayEdges: CadModifierDisplayEdge[];
};
export type CadModifierWorkerRequest =
| { type: "prepare"; requestId: number; parts: CadModifierMeshPart[]; sharpAngle: number }
| { type: "prepare"; requestId: number; parts: CadModifierMeshPart[]; sharpAngle: number; suppressTreatmentDetailEdges?: boolean }
| {
type: "preview";
requestId: number;
@@ -46,6 +68,7 @@ export type CadModifierWorkerResponse =
triangleCount: number;
brep: string;
displayEdges: CadModifierDisplayEdge[];
components?: CadModifierComponentMesh[];
}
| { type: "disposed"; requestId: number }
| { type: "error"; requestId: number; message: string };
| { type: "error"; requestId: number; message: string; resetSession?: boolean };
+85
View File
@@ -0,0 +1,85 @@
import type { MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MILLIMETERS_PER_INCH = 25.4;
const MILLIMETERS_PER_FOOT = 304.8;
const MILLIMETERS_PER_STUD = 8;
type WorkspaceScaleOption = {
label: string;
displayLabel: string;
millimetersPerDisplayUnit: number;
};
const METRIC_SCALE_OPTIONS: WorkspaceScaleOption[] = [
{ label: "1:1 (millimeters)", displayLabel: "mm", millimetersPerDisplayUnit: 1 },
{ label: "1:10 (centimeters)", displayLabel: "cm", millimetersPerDisplayUnit: 10 },
{ label: "1:1000 (meters)", displayLabel: "m", millimetersPerDisplayUnit: 1000 },
];
const IMPERIAL_SCALE_OPTIONS: WorkspaceScaleOption[] = [
{ label: "1:1 (inches)", displayLabel: "in", millimetersPerDisplayUnit: MILLIMETERS_PER_INCH },
{ label: "1:1 (feet)", displayLabel: "ft", millimetersPerDisplayUnit: MILLIMETERS_PER_FOOT },
];
const BRICK_SCALE_OPTIONS: WorkspaceScaleOption[] = [
{ label: "1:1 (studs)", displayLabel: "stud", millimetersPerDisplayUnit: MILLIMETERS_PER_STUD },
];
export const WORKSPACE_UNIT_OPTIONS = ["Metric (Default)", "Imperial", "Bricks"] as const;
export type LengthDisplayUnit = {
label: string;
millimetersPerUnit: number;
};
function scaleEntriesForUnits(units: string) {
if (units === "Imperial") return IMPERIAL_SCALE_OPTIONS;
if (units === "Bricks") return BRICK_SCALE_OPTIONS;
return METRIC_SCALE_OPTIONS;
}
export function scaleOptionsForUnits(units: string) {
return scaleEntriesForUnits(units).map((option) => option.label);
}
export function defaultScaleForUnits(units: string) {
return scaleEntriesForUnits(units)[0].label;
}
export function normalizeScaleForUnits(units: string, scale: string) {
const options = scaleEntriesForUnits(units);
const normalizedScale = units !== "Imperial" && units !== "Bricks" && scale === "1:100 (meters)" ? "1:1000 (meters)" : scale;
return options.some((option) => option.label === normalizedScale) ? normalizedScale : options[0].label;
}
function scaleEntryForWorkspace(workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
const options = scaleEntriesForUnits(workspace.units);
const normalizedScale = normalizeScaleForUnits(workspace.units, workspace.scale);
return options.find((option) => option.label === normalizedScale) ?? options[0];
}
export function lengthDisplayUnit(workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">): LengthDisplayUnit {
const scale = scaleEntryForWorkspace(workspace);
return { label: scale.displayLabel, millimetersPerUnit: scale.millimetersPerDisplayUnit };
}
export function millimetersToDisplay(value: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
return value / lengthDisplayUnit(workspace).millimetersPerUnit;
}
export function displayToMillimeters(value: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
return value * lengthDisplayUnit(workspace).millimetersPerUnit;
}
export function displayStepFromMillimeters(step: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
return step / lengthDisplayUnit(workspace).millimetersPerUnit;
}
export function formatMeasurementNumber(value: number, accuracy: MeasurementAccuracy, _step?: number) {
let decimals = accuracy;
while (decimals < 6 && value !== 0 && Math.abs(value) < 0.5 * 10 ** -decimals) {
decimals += 1;
}
const zeroThreshold = 0.5 * 10 ** -decimals;
return (Math.abs(value) < zeroThreshold ? 0 : value).toFixed(decimals);
}
+134
View File
@@ -0,0 +1,134 @@
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
export const SKETCHFORGE_MCP_STALE_MS = 6500;
export const SKETCHFORGE_MCP_POLL_MS = 220;
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
export type SketchForgeMcpShapeSummary = {
id: string;
name: string;
kind: ShapeKind;
color: string;
hole: boolean;
locked: boolean;
hidden: boolean;
position: {
x: number;
z: number;
elevation: number;
};
dimensions: {
width: number;
depth: number;
height: number;
size: number;
};
rotation: {
x: number;
y: number;
z: number;
};
mirror: {
x: boolean;
y: boolean;
z: boolean;
};
edgeTreatments: unknown[];
groupedCount: number;
importedTriangles: number;
cadDisplayEdgeCount: number | null;
sketchPointCount: number;
sketchSegmentCount: number;
children?: SketchForgeMcpShapeSummary[];
};
export type SketchForgeMcpSceneSummary = {
projectId: string | null;
projectName: string;
notice: string;
selectedIds: string[];
shapeCount: number;
workspace: WorkplaneWorkspaceSettings;
snap: GridSize | null;
shapes: SketchForgeMcpShapeSummary[];
};
export type SketchForgeMcpEditorSummary = {
editorId: string;
editorNumber: number;
projectId: string | null;
projectName: string;
url: string;
focused: boolean;
shapeCount: number;
selectedCount: number;
notice: string;
lastError: string | null;
lastSeen: number;
};
export type SketchForgeMcpCommandName =
| "get_scene"
| "list_objects"
| "select_objects"
| "delete_objects"
| "create_shape"
| "import_mesh"
| "update_object"
| "align_objects"
| "group_objects"
| "ungroup_objects"
| "boolean_cut"
| "separate_parts"
| "list_edges"
| "apply_edge_treatment"
| "inspect_errors"
| "capture_image";
export type SketchForgeMcpCommand = {
id: string;
action: SketchForgeMcpCommandName;
params: Record<string, unknown>;
createdAt: number;
};
export type SketchForgeMcpCommandResult = {
commandId: string;
ok: boolean;
data?: unknown;
error?: string;
completedAt?: number;
};
export type SketchForgeMcpHeartbeatPayload = {
type: "heartbeat";
editor: Omit<SketchForgeMcpEditorSummary, "lastSeen">;
};
export type SketchForgeMcpPollPayload = {
type: "poll";
editorId: string;
};
export type SketchForgeMcpResultPayload = {
type: "result";
editorId: string;
result: SketchForgeMcpCommandResult;
};
export type SketchForgeMcpDispatchPayload = {
type: "command";
editorId?: string;
editorNumber?: number;
action: SketchForgeMcpCommandName;
params?: Record<string, unknown>;
timeoutMs?: number;
};
export type SketchForgeMcpApiPayload =
| SketchForgeMcpHeartbeatPayload
| SketchForgeMcpPollPayload
| SketchForgeMcpResultPayload
| SketchForgeMcpDispatchPayload;
+143
View File
@@ -0,0 +1,143 @@
import type {
SketchForgeMcpCommand,
SketchForgeMcpCommandName,
SketchForgeMcpCommandResult,
SketchForgeMcpEditorSummary,
} from "@/lib/sketchforgeMcpProtocol";
import { SKETCHFORGE_MCP_STALE_MS } from "@/lib/sketchforgeMcpProtocol";
type PendingCommand = {
editorId: string;
resolve: (value: SketchForgeMcpCommandResult) => void;
timer: ReturnType<typeof setTimeout>;
};
type SketchForgeMcpStore = {
editors: Map<string, SketchForgeMcpEditorSummary>;
queues: Map<string, SketchForgeMcpCommand[]>;
pending: Map<string, PendingCommand>;
};
declare global {
// eslint-disable-next-line no-var
var __sketchforgeMcpStore: SketchForgeMcpStore | undefined;
}
function store() {
globalThis.__sketchforgeMcpStore ??= {
editors: new Map<string, SketchForgeMcpEditorSummary>(),
queues: new Map<string, SketchForgeMcpCommand[]>(),
pending: new Map<string, PendingCommand>(),
};
return globalThis.__sketchforgeMcpStore;
}
function createCommandId() {
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
function prune(current = Date.now()) {
const state = store();
for (const [editorId, editor] of state.editors) {
if (current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
continue;
}
state.editors.delete(editorId);
state.queues.delete(editorId);
for (const [commandId, pending] of state.pending) {
if (pending.editorId !== editorId) {
continue;
}
clearTimeout(pending.timer);
state.pending.delete(commandId);
pending.resolve({
commandId,
ok: false,
error: `SketchForge editor ${editor.editorNumber} is no longer open`,
completedAt: current,
});
}
}
}
export function registerSketchForgeMcpEditor(editor: Omit<SketchForgeMcpEditorSummary, "lastSeen">) {
const current = Date.now();
prune(current);
const state = store();
state.editors.set(editor.editorId, { ...editor, lastSeen: current });
state.queues.set(editor.editorId, state.queues.get(editor.editorId) ?? []);
}
export function listSketchForgeMcpEditors() {
prune();
return [...store().editors.values()].sort((a, b) => a.editorNumber - b.editorNumber);
}
export function pollSketchForgeMcpCommand(editorId: string) {
prune();
const queue = store().queues.get(editorId);
return queue?.shift() ?? null;
}
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
const state = store();
const pending = state.pending.get(result.commandId);
if (!pending || pending.editorId !== editorId) {
return false;
}
clearTimeout(pending.timer);
state.pending.delete(result.commandId);
pending.resolve({ ...result, completedAt: result.completedAt ?? Date.now() });
return true;
}
export function dispatchSketchForgeMcpCommand({
editorId,
editorNumber,
action,
params = {},
timeoutMs = 15000,
}: {
editorId?: string;
editorNumber?: number;
action: SketchForgeMcpCommandName;
params?: Record<string, unknown>;
timeoutMs?: number;
}) {
prune();
const state = store();
const editor =
(editorId ? state.editors.get(editorId) : null) ??
(typeof editorNumber === "number" ? [...state.editors.values()].find((candidate) => candidate.editorNumber === editorNumber) : null);
if (!editor) {
return Promise.resolve({
commandId: "",
ok: false,
error: typeof editorNumber === "number" ? `No open SketchForge editor ${editorNumber}` : "No matching open SketchForge editor",
completedAt: Date.now(),
} satisfies SketchForgeMcpCommandResult);
}
const command: SketchForgeMcpCommand = {
id: createCommandId(),
action,
params,
createdAt: Date.now(),
};
const queue = state.queues.get(editor.editorId) ?? [];
queue.push(command);
state.queues.set(editor.editorId, queue);
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
const timer = setTimeout(() => {
state.pending.delete(command.id);
resolve({
commandId: command.id,
ok: false,
error: `Timed out waiting for SketchForge editor ${editor.editorNumber}`,
completedAt: Date.now(),
});
}, Math.max(1000, Math.min(timeoutMs, 60000)));
state.pending.set(command.id, { editorId: editor.editorId, resolve, timer });
});
}
+4 -2
View File
@@ -1,4 +1,5 @@
import type { GridSize, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
@@ -42,6 +43,7 @@ export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_S
export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWorkspaceSettings = DEFAULT_WORKPLANE_WORKSPACE): WorkplaneWorkspaceSettings {
const candidate = value && typeof value === "object" ? (value as Partial<WorkplaneWorkspaceSettings>) : {};
const units = stringOrDefault(candidate.units, fallback.units);
return {
width: numberOrDefault(candidate.width, fallback.width),
depth: numberOrDefault(candidate.depth, fallback.depth),
@@ -53,8 +55,8 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
showGrid: booleanOrDefault(candidate.showGrid, fallback.showGrid),
cruiseShapes: booleanOrDefault(candidate.cruiseShapes, fallback.cruiseShapes),
zoomSpeed: numberOrDefault(candidate.zoomSpeed, fallback.zoomSpeed),
units: stringOrDefault(candidate.units, fallback.units),
scale: stringOrDefault(candidate.scale, fallback.scale),
units,
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
};
}
+1
View File
@@ -167,6 +167,7 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.edgeResizeMode === b.edgeResizeMode &&
a.cadBrep === b.cadBrep &&
a.cadBrepFrame === b.cadBrepFrame &&
a.cadPrimitiveFrame === b.cadPrimitiveFrame &&
a.groupedShapes === b.groupedShapes &&
a.groupedBaseWidth === b.groupedBaseWidth &&
a.groupedBaseDepth === b.groupedBaseDepth &&
+10
View File
@@ -118,6 +118,15 @@ export type CadBrepFrame = {
width: number;
depth: number;
height: number;
sourceTransform?: number[];
};
export type CadPrimitiveFrame = {
kind: "box";
width: number;
depth: number;
height: number;
frame: CadBrepFrame;
};
export type WorkplaneShape = {
@@ -175,6 +184,7 @@ export type WorkplaneShape = {
edgeResizeMode?: "scale" | "preserve";
cadBrep?: string;
cadBrepFrame?: CadBrepFrame;
cadPrimitiveFrame?: CadPrimitiveFrame;
groupedShapes?: WorkplaneShape[];
groupedBaseWidth?: number;
groupedBaseDepth?: number;
+192 -43
View File
@@ -1,7 +1,7 @@
/// <reference lib="webworker" />
import { OcctKernel, type ShapeHandle } from "occt-wasm";
import type { CadModifierDisplayEdge, CadModifierEdge, CadModifierMeshPart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
const HASH_UPPER_BOUND = 2_147_483_647;
const CAD_EDGE_WIREFRAME_DEFLECTION = 0.035;
@@ -13,10 +13,12 @@ let baseSolids: ShapeHandle[] = [];
let edgeHandles: ShapeHandle[] = [];
let edgeOwners: number[] = [];
type CollectedCadEdge = CadModifierEdge & {
type CollectedCadEdgeGeometry = Omit<CadModifierEdge, "display" | "selectable"> & {
curveType: string;
surfaceTypes: string[];
faceAreas: number[];
};
type CollectedCadEdge = CollectedCadEdgeGeometry & Pick<CadModifierEdge, "display" | "selectable">;
function post(message: CadModifierWorkerResponse, transfer: Transferable[] = []) {
self.postMessage(message, { transfer });
@@ -45,6 +47,16 @@ function releaseSession(cad: OcctKernel) {
edgeOwners = [];
}
function cadShapeIsValid(cad: OcctKernel, shape: ShapeHandle) {
const validator = (cad as { isValid?: unknown }).isValid;
if (typeof validator !== "function") return true;
try {
return Boolean(validator.call(cad, shape));
} catch {
return false;
}
}
function orientedFaceNormal(cad: OcctKernel, face: ShapeHandle, point: { x: number; y: number; z: number }) {
const uv = cad.uvFromPoint(face, point);
const normal = cad.surfaceNormal(face, uv.u, uv.v);
@@ -128,19 +140,61 @@ function meshPartToAsciiStl(part: CadModifierMeshPart) {
return lines.join("\n");
}
function isCadTransform(transform: number[] | undefined): transform is number[] {
return Boolean(transform?.length === 12 && transform.every(Number.isFinite));
}
function isIdentityCadTransform(transform: number[]) {
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
return transform.every((value, index) => Math.abs(value - identity[index]) < 1e-9);
}
function applyCadTransform(cad: OcctKernel, shape: ShapeHandle, transform: number[] | undefined) {
if (!isCadTransform(transform) || isIdentityCadTransform(transform)) return shape;
try {
return cad.transform(shape, transform);
} catch {
return cad.generalTransform(shape, transform);
}
}
function reconstructPrimitiveSolid(cad: OcctKernel, primitive: CadModifierPrimitivePart) {
if (primitive.kind !== "box") {
throw new Error(`Unsupported CAD primitive: ${primitive.kind}`);
}
const width = primitive.width;
const depth = primitive.depth;
const height = primitive.height;
if (![width, depth, height].every((value) => Number.isFinite(value) && value > 0)) {
throw new Error("The selected primitive has invalid dimensions");
}
const solid = cad.makeBoxFromCorners(
{ x: -width / 2, y: 0, z: -depth / 2 },
{ x: width / 2, y: height, z: depth / 2 },
);
const transformed = applyCadTransform(cad, solid, primitive.transform);
if (!cad.isSolid(transformed) || !cadShapeIsValid(cad, transformed)) {
throw new Error("The selected primitive could not be prepared as a valid CAD solid");
}
return transformed;
}
function reconstructSolid(cad: OcctKernel, part: CadModifierMeshPart) {
if (part.primitive) {
return reconstructPrimitiveSolid(cad, part.primitive);
}
if (part.brep) {
let exact = cad.fromBREP(part.brep);
if (part.brepTransform?.length === 12) exact = cad.generalTransform(exact, part.brepTransform);
const restoredSolids = cad.getSubShapes(exact, "solid");
if (cad.isValid(exact) && (cad.isSolid(exact) || restoredSolids.length > 0)) {
if (cadShapeIsValid(cad, exact) && (cad.isSolid(exact) || restoredSolids.length > 0)) {
return restoredSolids.length === 1 ? restoredSolids[0] : exact;
}
exact = cad.fixShape(exact);
exact = cad.fixFaceOrientations(exact);
if (cad.isSolid(exact)) exact = cad.healSolid(exact, 1e-5);
const healedSolids = cad.getSubShapes(exact, "solid");
if (cad.isValid(exact) && (cad.isSolid(exact) || healedSolids.length > 0)) {
if (cadShapeIsValid(cad, exact) && (cad.isSolid(exact) || healedSolids.length > 0)) {
return healedSolids.length === 1 ? healedSolids[0] : exact;
}
throw new Error("The stored CAD feature could not be restored as a valid solid");
@@ -156,7 +210,7 @@ function reconstructSolid(cad: OcctKernel, part: CadModifierMeshPart) {
} catch {
// Fall through to face sewing when the imported solid cannot be healed directly.
}
if (cad.isSolid(shape) && cad.isValid(shape)) return shape;
if (cad.isSolid(shape) && cadShapeIsValid(cad, shape)) return shape;
}
const faces = cad.getSubShapes(imported, "face");
@@ -169,7 +223,7 @@ function reconstructSolid(cad: OcctKernel, part: CadModifierMeshPart) {
candidate = cad.fixFaceOrientations(candidate);
candidate = cad.removeDegenerateEdges(candidate);
candidate = cad.unifySameDomain(candidate);
if (cad.isSolid(candidate) && cad.isValid(candidate)) return candidate;
if (cad.isSolid(candidate) && cadShapeIsValid(cad, candidate)) return candidate;
} catch {
// Try the next tolerance. Curved tessellations can need looser vertex sewing.
}
@@ -195,14 +249,52 @@ function reconstructParts(cad: OcctKernel, parts: CadModifierMeshPart[]) {
result = cad.fixShape(result);
result = cad.simplify(result);
result = cad.unifySameDomain(result);
if (!cad.isValid(result)) throw new Error("The grouped solid could not be repaired into valid topology");
if (!cadShapeIsValid(cad, result)) throw new Error("The grouped solid could not be repaired into valid topology");
return result;
}
function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number) {
function isDisplayCadEdge(edge: CollectedCadEdgeGeometry) {
if (!edge.manifold || edge.boundary || edge.points.length < 6) return false;
const effectiveAngle = Math.min(edge.angle, 180 - edge.angle);
const touchesCurvedSurface = edge.surfaceTypes.some((surfaceType) => CURVED_SURFACE_TYPES.has(surfaceType));
const isCurvedEdge = edge.curveType !== "line";
return effectiveAngle + 1e-3 >= CAD_DISPLAY_EDGE_MIN_ANGLE || touchesCurvedSurface || isCurvedEdge;
}
function treatmentDetailFaceAreaLimit(faceAreas: number[]) {
const finiteAreas = faceAreas.filter((area) => Number.isFinite(area) && area > 1e-8);
if (finiteAreas.length === 0) return 0;
return Math.max(1e-8, Math.max(...finiteAreas) * 0.3);
}
function touchesTreatmentDetailFace(edge: CollectedCadEdgeGeometry, areaLimit: number) {
return areaLimit > 0 && edge.faceAreas.some((area) => area > 0 && area <= areaLimit);
}
function isModifierDisplayCadEdge(edge: CollectedCadEdgeGeometry, treatmentAreaLimit: number) {
return isDisplayCadEdge(edge) && !touchesTreatmentDetailFace(edge, treatmentAreaLimit);
}
function isSelectableModifierEdge(edge: CollectedCadEdgeGeometry) {
return edge.manifold && !edge.boundary && edge.points.length >= 6;
}
function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number, suppressTreatmentDetailEdges = false) {
const handles = cad.getSubShapes(shape, "edge");
const faces = cad.getSubShapes(shape, "face");
const faceByHash = new Map(faces.map((face) => [cad.hashCode(face, HASH_UPPER_BOUND), face]));
const faceAreaByHash = new Map<number, number>();
faces.forEach((face) => {
const hash = cad.hashCode(face, HASH_UPPER_BOUND);
let area = 0;
try {
area = Math.abs(cad.getSurfaceArea(face));
} catch {
area = 0;
}
faceAreaByHash.set(hash, area);
});
const treatmentAreaLimit = suppressTreatmentDetailEdges ? treatmentDetailFaceAreaLimit([...faceAreaByHash.values()]) : 0;
const adjacentFaces = parseEdgeFaceMap(cad.edgeToFaceMap(shape, HASH_UPPER_BOUND));
const wire = cad.wireframe(shape, CAD_EDGE_WIREFRAME_DEFLECTION);
const pointsByHash = new Map<number, number[]>();
@@ -213,11 +305,12 @@ function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number) {
if (!pointsByHash.has(hash)) pointsByHash.set(hash, Array.from(wire.points.slice(start, start + count)));
}
const edges: CollectedCadEdge[] = handles.map((handle, id) => {
const collectedEdges = handles.map((handle, id) => {
const hash = cad.hashCode(handle, HASH_UPPER_BOUND);
const faceHashes = adjacentFaces.get(hash) ?? [];
const points = pointsByHash.get(hash) ?? [];
const classification = edgeAngle(cad, points, faceHashes, faceByHash);
const faceAreas = faceHashes.map((faceHash) => faceAreaByHash.get(faceHash) ?? 0);
const surfaceTypes = faceHashes
.map((faceHash) => faceByHash.get(faceHash))
.filter((face): face is ShapeHandle => face !== undefined)
@@ -234,22 +327,21 @@ function collectEdges(cad: OcctKernel, shape: ShapeHandle, sharpAngle: number) {
} catch {
curveType = "unknown";
}
return { id, points, ...classification, curveType, surfaceTypes };
return { id, points, ...classification, curveType, surfaceTypes, faceAreas };
}).filter((edge) => edge.points.length >= 6);
const selectableEdgeIds = edges.filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const edges: CollectedCadEdge[] = collectedEdges.map((edge) => ({
...edge,
display: treatmentAreaLimit > 0 ? isModifierDisplayCadEdge(edge, treatmentAreaLimit) : isDisplayCadEdge(edge),
selectable: isSelectableModifierEdge(edge),
}));
const selectableEdgeIds = edges.filter((edge) => edge.selectable && edge.angle + 1e-3 >= sharpAngle).map((edge) => edge.id);
const displayEdges = cadDisplayEdgesFromCollected(edges);
return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, ...edge }) => edge), selectableEdgeIds, displayEdges };
return { handles, edges: edges.map(({ curveType: _curveType, surfaceTypes: _surfaceTypes, faceAreas: _faceAreas, ...edge }) => edge), selectableEdgeIds, displayEdges };
}
function cadDisplayEdgesFromCollected(edges: CollectedCadEdge[]): CadModifierDisplayEdge[] {
return edges
.filter((edge) => {
if (!edge.manifold || edge.boundary || edge.points.length < 6) return false;
const effectiveAngle = Math.min(edge.angle, 180 - edge.angle);
const touchesCurvedSurface = edge.surfaceTypes.some((surfaceType) => CURVED_SURFACE_TYPES.has(surfaceType));
const isCurvedEdge = edge.curveType !== "line";
return effectiveAngle + 1e-3 >= CAD_DISPLAY_EDGE_MIN_ANGLE || touchesCurvedSurface || isCurvedEdge;
})
.filter(isDisplayCadEdge)
.map((edge) => ({ points: edge.points }));
}
@@ -259,33 +351,56 @@ function tessellationOptions(quality: CadModifierQuality, amount: number) {
return { linearDeflection: Math.max(0.055, amount / 7), angularDeflection: 0.2 };
}
function copyCadMesh(mesh: { positions: Float32Array; normals: Float32Array; indices: Uint32Array; triangleCount: number }) {
return {
positions: new Float32Array(mesh.positions),
normals: new Float32Array(mesh.normals),
indices: new Uint32Array(mesh.indices),
triangleCount: mesh.triangleCount,
};
}
function isWasmMemoryFault(message: string) {
return /memory access out of bounds|WebAssembly\.RuntimeError|wasm|abort/i.test(message);
}
function isImportStlWasmFault(message: string) {
return /importStl:.*WebAssembly\.Exception/i.test(message);
}
function isMissingValidatorFault(message: string) {
return /isValid/i.test(message) && /null|not a function|undefined/i.test(message);
}
self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
const request = event.data;
let cad: OcctKernel | null = null;
try {
const cad = await kernel();
cad = await kernel();
const activeCad = cad;
if (request.type === "dispose") {
releaseSession(cad);
releaseSession(activeCad);
post({ type: "disposed", requestId: request.requestId });
return;
}
if (request.type === "prepare") {
releaseSession(cad);
baseShape = reconstructParts(cad, request.parts);
const collected = collectEdges(cad, baseShape, request.sharpAngle);
releaseSession(activeCad);
baseShape = reconstructParts(activeCad, request.parts);
const collected = collectEdges(activeCad, baseShape, request.sharpAngle, Boolean(request.suppressTreatmentDetailEdges));
edgeHandles = collected.handles;
baseSolids = cad.isSolid(baseShape) ? [baseShape] : cad.getSubShapes(baseShape, "solid");
baseSolids = activeCad.isSolid(baseShape) ? [baseShape] : activeCad.getSubShapes(baseShape, "solid");
if (baseSolids.length === 0) throw new Error("The selected group contains no closed solid components");
const ownerHashes = baseSolids.map((solid) => new Set(cad.getSubShapes(solid, "edge").map((edge) => cad.hashCode(edge, HASH_UPPER_BOUND))));
const ownerHashes = baseSolids.map((solid) => new Set(activeCad.getSubShapes(solid, "edge").map((edge) => activeCad.hashCode(edge, HASH_UPPER_BOUND))));
edgeOwners = edgeHandles.map((edge) => {
const hash = cad.hashCode(edge, HASH_UPPER_BOUND);
const hash = activeCad.hashCode(edge, HASH_UPPER_BOUND);
return Math.max(0, ownerHashes.findIndex((hashes) => hashes.has(hash)));
});
post({
type: "ready",
requestId: request.requestId,
edges: collected.edges,
edges: collected.edges.map((edge) => ({ ...edge, owner: edgeOwners[edge.id] ?? 0 })),
selectableEdgeIds: collected.selectableEdgeIds,
sourceType: cad.getShapeType(baseShape),
sourceType: activeCad.getShapeType(baseShape),
});
return;
}
@@ -294,26 +409,60 @@ self.onmessage = async (event: MessageEvent<CadModifierWorkerRequest>) => {
if (selected.length === 0) throw new Error("Select at least one highlighted edge");
const componentResults = baseSolids.map((solid, owner) => {
const componentEdges = selected.filter((entry) => entry.owner === owner).map((entry) => entry.edge);
if (componentEdges.length === 0) return cad.copy(solid);
if (componentEdges.length === 0) return activeCad.copy(solid);
return request.kind === "fillet"
? cad.fillet(solid, componentEdges, request.amount)
? activeCad.fillet(solid, componentEdges, request.amount)
: Math.abs(request.chamferAngle - 45) < 0.001
? cad.chamfer(solid, componentEdges, request.amount)
: cad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
? activeCad.chamfer(solid, componentEdges, request.amount)
: activeCad.chamferDistAngle(solid, componentEdges, request.amount, request.chamferAngle);
});
const result = componentResults.length === 1 ? componentResults[0] : cad.makeCompound(componentResults);
if (!cad.isValid(result)) throw new Error("The chosen size creates invalid or overlapping edge geometry");
const mesh = cad.tessellate(result, tessellationOptions(request.quality, request.amount));
const displayEdges = collectEdges(cad, result, request.chamferAngle).displayEdges;
const brep = cad.toBREP(result);
componentResults.forEach((component) => cad.release(component));
if (componentResults.length > 1) cad.release(result);
const result = componentResults.length === 1 ? componentResults[0] : activeCad.makeCompound(componentResults);
if (!cadShapeIsValid(activeCad, result)) throw new Error("The chosen size creates invalid or overlapping edge geometry");
const options = tessellationOptions(request.quality, request.amount);
const mesh = copyCadMesh(activeCad.tessellate(result, options));
const displayEdges = collectEdges(activeCad, result, request.chamferAngle).displayEdges;
const brep = activeCad.toBREP(result);
const components: CadModifierComponentMesh[] = componentResults.map((component, owner) => {
const componentMesh = copyCadMesh(activeCad.tessellate(component, options));
return {
owner,
positions: componentMesh.positions,
normals: componentMesh.normals,
indices: componentMesh.indices,
triangleCount: componentMesh.triangleCount,
brep: activeCad.toBREP(component),
displayEdges: collectEdges(activeCad, component, request.chamferAngle).displayEdges,
};
});
componentResults.forEach((component) => activeCad.release(component));
if (componentResults.length > 1) activeCad.release(result);
post(
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges },
[mesh.positions.buffer, mesh.normals.buffer, mesh.indices.buffer],
{ type: "preview", requestId: request.requestId, positions: mesh.positions, normals: mesh.normals, indices: mesh.indices, triangleCount: mesh.triangleCount, brep, displayEdges, components },
[
mesh.positions.buffer,
mesh.normals.buffer,
mesh.indices.buffer,
...components.flatMap((component) => [component.positions.buffer, component.normals.buffer, component.indices.buffer]),
],
);
} catch (error) {
const rawMessage = error instanceof Error ? error.message : "";
const rawMessage = error instanceof Error ? error.message : String(error ?? "");
if (isWasmMemoryFault(rawMessage) || isImportStlWasmFault(rawMessage) || isMissingValidatorFault(rawMessage)) {
if (cad) releaseSession(cad);
kernelPromise = null;
const message = isImportStlWasmFault(rawMessage)
? "The selected mesh could not be converted into a closed CAD solid. The CAD kernel reset; try Separate Parts, ungrouping, or simplifying the object before adding edge features."
: isMissingValidatorFault(rawMessage)
? "The CAD kernel exposed an incomplete validation function and reset. Start the edge tool again; no page refresh is needed."
: "The CAD kernel hit a memory fault and reset. Start the edge tool again; no page refresh is needed.";
post({
type: "error",
requestId: request.requestId,
message,
resetSession: true,
});
return;
}
const message = request.type === "preview" && (rawMessage.includes("WebAssembly.Exception") || rawMessage.includes("fillet:") || rawMessage.includes("chamfer:"))
? `The selected edges cannot be ${request.kind === "fillet" ? "filleted" : "chamfered"} together at this size. Reduce the size or select fewer connected edges.`
: rawMessage || "The CAD kernel could not complete this edge treatment";
Binary file not shown.

After

Width:  |  Height:  |  Size: 850 KiB

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "sketchforge",
"version": "0.2.0",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sketchforge",
"version": "0.2.0",
"version": "0.5.0",
"dependencies": {
"@tailwindcss/postcss": "^4.1.8",
"@types/three": "^0.184.1",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "sketchforge",
"version": "0.2.0",
"version": "0.5.0",
"private": true,
"scripts": {
"copy:occt": "node scripts/copy-occt-wasm.mjs",
@@ -19,7 +19,8 @@
"docker:build": "docker build -f deploy/docker/Dockerfile -t sketchforge:local .",
"docker:run": "docker run --rm -p 3000:80 sketchforge:local",
"docker:up": "docker compose -f deploy/docker/compose.yaml up --build -d",
"docker:down": "docker compose -f deploy/docker/compose.yaml down"
"docker:down": "docker compose -f deploy/docker/compose.yaml down",
"mcp:sketchforge": "node scripts/sketchforge-mcp-server.mjs"
},
"dependencies": {
"@tailwindcss/postcss": "^4.1.8",
+436
View File
@@ -0,0 +1,436 @@
#!/usr/bin/env node
const DEFAULT_BASE_URL = "http://127.0.0.1:3000";
const MCP_ROUTE = "/api/sketchforge-mcp";
const baseUrl = process.env.SKETCHFORGE_URL || DEFAULT_BASE_URL;
const editorTargetSchema = {
type: "object",
properties: {
editorNumber: { type: "number", description: "The 5-digit SketchForge editor number from sketchforge_list_editors." },
editorId: { type: "string", description: "Optional internal editor id. Prefer editorNumber for human-directed use." },
timeoutMs: { type: "number", description: "Command timeout in milliseconds. Defaults to 15000." },
},
};
const tools = [
{
name: "sketchforge_list_editors",
description: "List SketchForge editor tabs that are currently open and heartbeating, including editorNumber and projectName.",
inputSchema: { type: "object", properties: {} },
},
{
name: "sketchforge_read_scene",
description: "Read the current scene, selection, workspace units, and exact object dimensions from an open SketchForge editor.",
inputSchema: {
...editorTargetSchema,
properties: {
...editorTargetSchema.properties,
includeRawShapes: { type: "boolean", description: "Include raw WorkplaneShape JSON. Can be large for imported meshes." },
},
},
},
{
name: "sketchforge_list_objects",
description: "List all current objects available in the editor with exact dimensions, position, rotation, and object ids.",
inputSchema: editorTargetSchema,
},
{
name: "sketchforge_select_objects",
description: "Select objects by id in the SketchForge editor.",
inputSchema: {
...editorTargetSchema,
required: ["ids"],
properties: {
...editorTargetSchema.properties,
ids: { type: "array", items: { type: "string" } },
},
},
},
{
name: "sketchforge_delete_objects",
description: "Delete objects by id, or delete the current selection when ids are omitted.",
inputSchema: {
...editorTargetSchema,
properties: {
...editorTargetSchema.properties,
ids: { type: "array", items: { type: "string" } },
id: { type: "string" },
},
},
},
{
name: "sketchforge_create_shape",
description: "Create a box/cube, cylinder, or simple extruded sketch in SketchForge.",
inputSchema: {
...editorTargetSchema,
required: ["kind"],
properties: {
...editorTargetSchema.properties,
kind: { type: "string", enum: ["box", "cube", "cylinder", "sketch"] },
name: { type: "string" },
color: { type: "string" },
x: { type: "number" },
z: { type: "number" },
elevation: { type: "number" },
width: { type: "number" },
depth: { type: "number" },
height: { type: "number" },
size: { type: "number" },
rotation: { type: "number" },
rotationX: { type: "number" },
rotationZ: { type: "number" },
sides: { type: "number" },
},
},
},
{
name: "sketchforge_import_mesh",
description: "Import a triangle mesh into SketchForge from raw position and optional normal arrays.",
inputSchema: {
...editorTargetSchema,
required: ["positions"],
properties: {
...editorTargetSchema.properties,
name: { type: "string" },
color: { type: "string" },
x: { type: "number" },
z: { type: "number" },
elevation: { type: "number" },
width: { type: "number" },
depth: { type: "number" },
height: { type: "number" },
positions: { type: "array", items: { type: "number" } },
normals: { type: "array", items: { type: "number" } },
},
},
},
{
name: "sketchforge_update_object",
description: "Update one object's exact dimensions, position, color, name, hole state, or rotations.",
inputSchema: {
...editorTargetSchema,
required: ["id"],
properties: {
...editorTargetSchema.properties,
id: { type: "string" },
name: { type: "string" },
color: { type: "string" },
hole: { type: "boolean" },
x: { type: "number" },
z: { type: "number" },
elevation: { type: "number" },
width: { type: "number" },
depth: { type: "number" },
height: { type: "number" },
size: { type: "number" },
rotation: { type: "number" },
rotationX: { type: "number" },
rotationZ: { type: "number" },
},
},
},
{
name: "sketchforge_align_objects",
description: "Align two or more SketchForge objects using the same alignment logic as the editor Alignment button.",
inputSchema: {
...editorTargetSchema,
required: ["axis", "target"],
properties: {
...editorTargetSchema.properties,
ids: { type: "array", items: { type: "string" }, description: "Object ids to align. If omitted, uses the current selection." },
anchorId: { type: "string", description: "Optional object id to keep fixed as the alignment reference." },
axis: { type: "string", enum: ["x", "y", "z"], description: "x=left/right, z=front/back, y=bottom/top." },
target: { type: "string", enum: ["min", "center", "max"], description: "Which side/center to align." },
},
},
},
{
name: "sketchforge_group_objects",
description: "Group objects by id using SketchForge's normal grouping/boolean pipeline.",
inputSchema: {
...editorTargetSchema,
required: ["ids"],
properties: {
...editorTargetSchema.properties,
ids: { type: "array", items: { type: "string" } },
},
},
},
{
name: "sketchforge_ungroup_objects",
description: "Ungroup one or more grouped objects by id and preserve their edited geometry.",
inputSchema: {
...editorTargetSchema,
properties: {
...editorTargetSchema.properties,
ids: { type: "array", items: { type: "string" } },
id: { type: "string" },
},
},
},
{
name: "sketchforge_boolean_cut",
description: "Cut solids with hole objects. Provide solidIds and holeIds; the result replaces the operands.",
inputSchema: {
...editorTargetSchema,
required: ["solidIds", "holeIds"],
properties: {
...editorTargetSchema.properties,
solidIds: { type: "array", items: { type: "string" } },
holeIds: { type: "array", items: { type: "string" } },
},
},
},
{
name: "sketchforge_separate_parts",
description: "Separate one disconnected multi-part object into independent objects.",
inputSchema: {
...editorTargetSchema,
properties: {
...editorTargetSchema.properties,
id: { type: "string" },
},
},
},
{
name: "sketchforge_list_edges",
description: "List real CAD edge ids for one object so a later chamfer/fillet can target specific edges.",
inputSchema: {
...editorTargetSchema,
required: ["id"],
properties: {
...editorTargetSchema.properties,
id: { type: "string" },
sharpAngle: { type: "number" },
},
},
},
{
name: "sketchforge_apply_edge_treatment",
description: "Apply chamfer or fillet to specific edge ids returned by sketchforge_list_edges.",
inputSchema: {
...editorTargetSchema,
required: ["id", "kind", "edgeIds", "amount"],
properties: {
...editorTargetSchema.properties,
id: { type: "string" },
kind: { type: "string", enum: ["chamfer", "fillet"] },
edgeIds: {
anyOf: [
{ type: "array", items: { type: "number" } },
{ type: "string", enum: ["all"] },
],
},
allEdges: { type: "boolean" },
amount: { type: "number" },
chamferAngle: { type: "number" },
sharpAngle: { type: "number" },
quality: { type: "string", enum: ["draft", "standard", "fine"] },
preserveEdgeSize: { type: "boolean" },
},
},
},
{
name: "sketchforge_inspect_errors",
description: "Inspect the editor notice, last MCP error, and active edge modifier error.",
inputSchema: editorTargetSchema,
},
{
name: "sketchforge_capture_image",
description: "Capture a PNG image of the editor viewport from current/home/top/bottom/front/back/right/left view.",
inputSchema: {
...editorTargetSchema,
properties: {
...editorTargetSchema.properties,
face: { type: "string", enum: ["current", "home", "top", "bottom", "front", "back", "right", "left"] },
},
},
},
];
function bridgeUrl() {
return new URL(MCP_ROUTE, baseUrl);
}
async function bridgeGet() {
const response = await fetch(bridgeUrl());
const payload = await response.json().catch(() => null);
if (!response.ok) {
throw new Error(payload?.error || `SketchForge bridge returned HTTP ${response.status}`);
}
return payload;
}
async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000) {
const { editorNumber, editorId, timeoutMs, ...params } = args || {};
let targetNumber = typeof editorNumber === "number" ? editorNumber : undefined;
let targetId = typeof editorId === "string" ? editorId : undefined;
if (!targetNumber && !targetId) {
const { editors = [] } = await bridgeGet();
if (editors.length === 1) {
targetNumber = editors[0].editorNumber;
} else {
throw new Error(editors.length === 0 ? "No open SketchForge editors found" : "Provide editorNumber because multiple SketchForge editors are open");
}
}
const response = await fetch(bridgeUrl(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "command",
editorNumber: targetNumber,
editorId: targetId,
action,
params,
timeoutMs: typeof timeoutMs === "number" ? timeoutMs : defaultTimeoutMs,
}),
});
const payload = await response.json().catch(() => null);
if (!payload?.ok) {
throw new Error(payload?.error || `SketchForge command failed with HTTP ${response.status}`);
}
return payload.data;
}
async function callTool(name, args) {
switch (name) {
case "sketchforge_list_editors":
return bridgeGet();
case "sketchforge_read_scene":
return bridgeCommand("get_scene", args);
case "sketchforge_list_objects":
return bridgeCommand("list_objects", args);
case "sketchforge_select_objects":
return bridgeCommand("select_objects", args);
case "sketchforge_delete_objects":
return bridgeCommand("delete_objects", args);
case "sketchforge_create_shape":
return bridgeCommand("create_shape", args);
case "sketchforge_import_mesh":
return bridgeCommand("import_mesh", args, 60000);
case "sketchforge_update_object":
return bridgeCommand("update_object", args);
case "sketchforge_align_objects":
return bridgeCommand("align_objects", args);
case "sketchforge_group_objects":
return bridgeCommand("group_objects", args, 30000);
case "sketchforge_ungroup_objects":
return bridgeCommand("ungroup_objects", args);
case "sketchforge_boolean_cut":
return bridgeCommand("boolean_cut", args, 45000);
case "sketchforge_separate_parts":
return bridgeCommand("separate_parts", args);
case "sketchforge_list_edges":
return bridgeCommand("list_edges", args, 30000);
case "sketchforge_apply_edge_treatment":
return bridgeCommand("apply_edge_treatment", args, 60000);
case "sketchforge_inspect_errors":
return bridgeCommand("inspect_errors", args);
case "sketchforge_capture_image":
return bridgeCommand("capture_image", args, 30000);
default:
throw new Error(`Unknown tool: ${name}`);
}
}
function textContent(value) {
return {
type: "text",
text: typeof value === "string" ? value : JSON.stringify(value, null, 2),
};
}
function toolResult(value) {
if (value?.dataUrl?.startsWith?.("data:image/png;base64,")) {
return {
content: [
textContent({ face: value.face, bytesApprox: value.bytesApprox }),
{
type: "image",
data: value.dataUrl.slice("data:image/png;base64,".length),
mimeType: "image/png",
},
],
};
}
return { content: [textContent(value)] };
}
function send(message) {
process.stdout.write(`${JSON.stringify(message)}\n`);
}
function sendResult(id, result) {
send({ jsonrpc: "2.0", id, result });
}
function sendError(id, code, message) {
send({ jsonrpc: "2.0", id, error: { code, message } });
}
async function handleMessage(message) {
if (!message || typeof message !== "object") return;
const { id, method, params } = message;
try {
if (method === "initialize") {
sendResult(id, {
protocolVersion: params?.protocolVersion || "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "sketchforge-mcp", version: "0.1.0" },
});
return;
}
if (method === "notifications/initialized") {
return;
}
if (method === "ping") {
sendResult(id, {});
return;
}
if (method === "tools/list") {
sendResult(id, { tools });
return;
}
if (method === "tools/call") {
const name = params?.name;
if (typeof name !== "string") {
sendError(id, -32602, "Expected tool name");
return;
}
const result = await callTool(name, params?.arguments || {});
sendResult(id, toolResult(result));
return;
}
if (method === "resources/list") {
sendResult(id, { resources: [] });
return;
}
sendError(id, -32601, `Unknown method: ${method}`);
} catch (error) {
if (method === "tools/call") {
sendResult(id, { isError: true, content: [textContent(error instanceof Error ? error.message : String(error))] });
return;
}
sendError(id, -32000, error instanceof Error ? error.message : String(error));
}
}
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
const lines = buffer.split(/\r?\n/);
buffer = lines.pop() || "";
lines.forEach((line) => {
const trimmed = line.trim();
if (!trimmed) return;
try {
void handleMessage(JSON.parse(trimmed));
} catch (error) {
sendError(null, -32700, error instanceof Error ? error.message : String(error));
}
});
});
+188
View File
@@ -0,0 +1,188 @@
import { describe, expect, it } from "vitest";
import {
bakeCadMetadataForShapeTransform,
cadBrepTransformForShape,
cadModifierPrimitiveForAnalyticBox,
cadModifierPrimitiveForBakedShape,
} from "@/lib/cadBakeMetadata";
import type { WorkplaneShape } from "@/types/sketchforge";
function expectTransformClose(actual: number[] | undefined, expected: number[]) {
expect(actual).toHaveLength(expected.length);
expected.forEach((value, index) => {
expect(actual?.[index]).toBeCloseTo(value, 6);
});
}
function treatedMeshShape(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id: "treated-mesh",
name: "Treated Mesh",
kind: "mesh",
color: "#d41721",
x: 10,
z: 0,
elevation: 5,
size: 2,
width: 2,
depth: 2,
height: 2,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions: [-1, 0, 0, 1, 0, 0, 0, 2, 0],
baseWidth: 2,
baseDepth: 2,
baseHeight: 2,
triangleCount: 1,
sourceFormat: "json",
},
edgeTreatments: [{ kind: "fillet", amount: 0.5, edgeCount: 1 }],
cadDisplayEdges: [{ points: [-1, 0, 0, 1, 0, 0] }],
cadDisplayEdgesVersion: 2,
cadBrep: "stored-brep-before-rotation",
cadBrepFrame: {
x: 10,
z: 0,
elevation: 5,
width: 2,
depth: 2,
height: 2,
},
locked: false,
hidden: false,
...overrides,
};
}
function boxShape(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id: "box",
name: "Box",
kind: "box",
color: "#d41721",
x: 4,
z: -6,
elevation: 2,
size: 20,
width: 20,
depth: 18,
height: 16,
rotation: 32,
rotationX: 18,
rotationZ: 24,
locked: false,
hidden: false,
...overrides,
};
}
describe("SketchForge transform baking", () => {
it("preserves exact BREP and rebases CAD display edges after wheel rotation", () => {
const shape = treatedMeshShape({ rotationZ: 90 });
const baked = bakeCadMetadataForShapeTransform(shape, {
centerX: 10,
minY: 5,
centerZ: 0,
width: 2,
depth: 2,
height: 2,
yawDegrees: 0,
});
const expectedTransform = [0, -1, 0, 16, 1, 0, 0, -4, 0, 0, 1, 0];
expect(baked.cadBrep).toBe("stored-brep-before-rotation");
expect(baked.cadBrepFrame).toMatchObject({
x: 10,
z: 0,
elevation: 5,
width: 2,
depth: 2,
height: 2,
});
expectTransformClose(baked.cadBrepFrame?.sourceTransform, expectedTransform);
expect(baked.cadDisplayEdgesVersion).toBe(2);
expect(baked.cadDisplayEdges?.[0].points).toEqual([1, 0, 0, 1, 2, 0]);
const bakedShape: WorkplaneShape = {
...shape,
...baked,
x: 10,
z: 0,
elevation: 5,
width: 2,
depth: 2,
height: 2,
size: 2,
rotation: 0,
rotationX: 0,
rotationZ: 0,
};
expectTransformClose(cadBrepTransformForShape(bakedShape), expectedTransform);
});
it("preserves an analytic box primitive when wheel rotation bakes it to a mesh", () => {
const shape = boxShape();
const directPrimitive = cadModifierPrimitiveForAnalyticBox(shape);
expect(directPrimitive?.transform).toBeDefined();
const baked = bakeCadMetadataForShapeTransform(shape, {
centerX: 4.5,
minY: -2,
centerZ: -5.5,
width: 27,
depth: 26,
height: 25,
yawDegrees: 32,
});
expect(baked.cadPrimitiveFrame).toMatchObject({
kind: "box",
width: 20,
depth: 18,
height: 16,
frame: {
x: 4.5,
z: -5.5,
elevation: -2,
width: 27,
depth: 26,
height: 25,
},
});
expectTransformClose(baked.cadPrimitiveFrame?.frame.sourceTransform, directPrimitive?.transform ?? []);
const bakedShape: WorkplaneShape = {
...shape,
...baked,
kind: "mesh",
x: 4.5,
z: -5.5,
elevation: -2,
width: 27,
depth: 26,
height: 25,
size: 27,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions: [-1, 0, 0, 1, 0, 0, 0, 1, 0],
baseWidth: 27,
baseDepth: 26,
baseHeight: 25,
triangleCount: 1,
sourceFormat: "json",
},
};
const restoredPrimitive = cadModifierPrimitiveForBakedShape(bakedShape);
expect(restoredPrimitive).toMatchObject({
kind: "box",
width: 20,
depth: 18,
height: 16,
});
expectTransformClose(restoredPrimitive?.transform, directPrimitive?.transform ?? []);
});
});
+25 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, scaleOptionsForUnits } from "@/lib/measurementUnits";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
describe("workplane settings helpers", () => {
@@ -47,13 +48,36 @@ describe("workplane settings helpers", () => {
showGrid: false,
cruiseShapes: false,
units: "Bricks",
scale: "1:10 (centimeters)",
scale: "1:1 (studs)",
accuracy: 3,
});
expect(normalizeWorkspaceSettings({ accuracy: 9 }, fallback).accuracy).toBe(fallback.accuracy);
});
it("keeps scale options in the selected unit family", () => {
expect(scaleOptionsForUnits("Metric (Default)")).toEqual(["1:1 (millimeters)", "1:10 (centimeters)", "1:1000 (meters)"]);
expect(normalizeScaleForUnits("Metric (Default)", "1:100 (meters)")).toBe("1:1000 (meters)");
expect(scaleOptionsForUnits("Imperial")).toEqual(["1:1 (inches)", "1:1 (feet)"]);
expect(normalizeScaleForUnits("Imperial", "1:100 (meters)")).toBe("1:1 (inches)");
expect(normalizeWorkspaceSettings({ units: "Imperial", scale: "1:100 (meters)" }).scale).toBe("1:1 (inches)");
});
it("changes display units without scaling model values", () => {
expect(lengthDisplayUnit({ units: "Metric (Default)", scale: "1:1000 (meters)" }).label).toBe("m");
expect(millimetersToDisplay(20, { units: "Metric (Default)", scale: "1:1 (millimeters)" })).toBe(20);
expect(millimetersToDisplay(20, { units: "Metric (Default)", scale: "1:1000 (meters)" })).toBe(0.02);
expect(millimetersToDisplay(20, { units: "Metric (Default)", scale: "1:100 (meters)" })).toBe(0.02);
expect(Number(millimetersToDisplay(25.4, { units: "Imperial", scale: "1:1 (inches)" }).toFixed(4))).toBe(1);
expect(Number(millimetersToDisplay(304.8, { units: "Imperial", scale: "1:1 (feet)" }).toFixed(4))).toBe(1);
});
it("uses accuracy as display precision", () => {
expect(formatMeasurementNumber(20, 1, 0.01)).toBe("20.0");
expect(formatMeasurementNumber(20, 3, 0.01)).toBe("20.000");
expect(formatMeasurementNumber(0.0004, 1, 0.001)).toBe("0.0004");
});
it("fingerprints workspace and snap settings together", () => {
const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
const changedSnap = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "5.0 mm");