diff --git a/apps/web/src/app/api/app-update/route.ts b/apps/web/src/app/api/app-update/route.ts index 806e3a3..b160eb3 100644 --- a/apps/web/src/app/api/app-update/route.ts +++ b/apps/web/src/app/api/app-update/route.ts @@ -1,4 +1,8 @@ import { timingSafeEqual } from "node:crypto"; +import { execFile, spawn } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { promisify } from "node:util"; import { NextResponse } from "next/server"; import { appUpdateIsAvailable, OFFICIAL_UPDATE_GUIDE_URL, type AppUpdateStatus } from "@/lib/appUpdates"; import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; @@ -8,8 +12,11 @@ export const dynamic = "force-dynamic"; export const revalidate = false; const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json"; +const OFFICIAL_REPO_URL = "https://github.com/Formsmith746/SketchForge-3D.git"; const UPDATE_CACHE_MS = 5 * 60 * 1000; const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000; +const execFileAsync = promisify(execFile); +const VERSION_PATTERN = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; let cachedLatest: { version: string; expiresAt: number } | null = null; let nextTriggerAt = 0; @@ -29,12 +36,56 @@ function sameOriginRequest(request: Request) { } } +function loopbackRequest(request: Request) { + try { + const hostname = new URL(request.url).hostname.toLowerCase(); + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]"; + } catch { + return false; + } +} + function safeEqual(left: string, right: string) { const leftBytes = Buffer.from(left); const rightBytes = Buffer.from(right); return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes); } +function findParentRoot(requireGit: boolean) { + let current = path.resolve(process.cwd()); + for (let depth = 0; depth < 7; depth += 1) { + const hasPackage = existsSync(path.join(current, "package.json")); + const hasGit = existsSync(path.join(current, ".git")); + if (hasPackage && (!requireGit || hasGit)) return current; + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + return null; +} + +function packageVersion(root: string | null) { + if (!root) return null; + try { + const payload = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as { version?: unknown }; + const version = typeof payload.version === "string" ? payload.version.trim() : ""; + return VERSION_PATTERN.test(version) ? version : null; + } catch { + return null; + } +} + +function currentAppVersion() { + const configured = process.env.SKETCHFORGE_APP_VERSION?.trim(); + if (configured && VERSION_PATTERN.test(configured)) return configured; + return packageVersion(findParentRoot(false)) || SKF_CREATED_WITH_VERSION; +} + +function localRepoForRequest(request: Request) { + if (!loopbackRequest(request)) return null; + return findParentRoot(true); +} + function updateTriggerUrl() { const configured = process.env.SKETCHFORGE_UPDATE_TRIGGER_URL?.trim(); if (!configured) return null; @@ -59,7 +110,7 @@ async function latestOfficialVersion(force = false) { if (!response.ok) throw new Error(`Update server returned ${response.status}`); const payload = await response.json() as { version?: unknown }; const version = typeof payload.version === "string" ? payload.version.trim() : ""; - if (!/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) { + if (!VERSION_PATTERN.test(version)) { throw new Error("Update server returned an invalid version"); } cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS }; @@ -73,41 +124,113 @@ function updateGuideUrl() { return process.env.SKETCHFORGE_UPDATE_GUIDE_URL?.trim() || OFFICIAL_UPDATE_GUIDE_URL; } -async function statusResponse(force = false): Promise { +async function statusResponse(request: Request, force = false): Promise { const trigger = updateTriggerUrl(); const adminKeyConfigured = Boolean(process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim()); + const localRepo = localRepoForRequest(request); + const currentVersion = currentAppVersion(); try { const latestVersion = await latestOfficialVersion(force); return { - currentVersion: SKF_CREATED_WITH_VERSION, + currentVersion, latestVersion, - updateAvailable: appUpdateIsAvailable(SKF_CREATED_WITH_VERSION, latestVersion), + updateAvailable: appUpdateIsAvailable(currentVersion, latestVersion), checkedAt: new Date().toISOString(), updateUrl: updateGuideUrl(), - installationReady: Boolean(trigger && adminKeyConfigured), - requiresUpdateKey: Boolean(trigger && adminKeyConfigured), + installationReady: Boolean(localRepo || (trigger && adminKeyConfigured)), + requiresUpdateKey: localRepo ? false : Boolean(trigger && adminKeyConfigured), + updateMode: localRepo ? "local" : "server", }; } catch (error) { return { - currentVersion: SKF_CREATED_WITH_VERSION, + currentVersion, latestVersion: null, updateAvailable: false, checkedAt: new Date().toISOString(), updateUrl: updateGuideUrl(), - installationReady: Boolean(trigger && adminKeyConfigured), - requiresUpdateKey: Boolean(trigger && adminKeyConfigured), + installationReady: Boolean(localRepo || (trigger && adminKeyConfigured)), + requiresUpdateKey: localRepo ? false : Boolean(trigger && adminKeyConfigured), + updateMode: localRepo ? "local" : "server", checkError: error instanceof Error ? error.message : "Could not check for updates", }; } } +async function runLocalUpdate(repoRoot: string, expectedVersion: string) { + const gitOptions = { cwd: repoRoot, timeout: 120_000, maxBuffer: 2 * 1024 * 1024 }; + const { stdout: dirtyOutput } = await execFileAsync("git", ["status", "--porcelain", "--untracked-files=no"], gitOptions); + if (dirtyOutput.trim()) { + throw new Error("Local SketchForge has uncommitted code changes. Commit or stash them before updating so the updater does not overwrite your work."); + } + + await execFileAsync("git", ["fetch", "--no-tags", OFFICIAL_REPO_URL, "main"], gitOptions); + await execFileAsync("git", ["merge", "--ff-only", "FETCH_HEAD"], gitOptions); + + const installedVersion = packageVersion(repoRoot); + if (installedVersion && appUpdateIsAvailable(installedVersion, expectedVersion)) { + throw new Error(`The local checkout updated to ${installedVersion}, but ${expectedVersion} was expected.`); + } + + const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; + await execFileAsync(npmCommand, ["install", "--no-audit", "--no-fund"], { + cwd: repoRoot, + timeout: 5 * 60 * 1000, + maxBuffer: 4 * 1024 * 1024, + windowsHide: true, + }); + + const restartScript = path.join(repoRoot, "scripts", "restart-local-dev.mjs"); + if (existsSync(restartScript)) { + const child = spawn(process.execPath, [restartScript, String(process.pid), repoRoot], { + cwd: repoRoot, + detached: true, + stdio: "ignore", + windowsHide: true, + }); + child.unref(); + } + + return installedVersion || expectedVersion; +} + export async function GET(request: Request) { const force = new URL(request.url).searchParams.get("force") === "1"; - return NextResponse.json(await statusResponse(force), { headers: { "Cache-Control": "no-store" } }); + return NextResponse.json(await statusResponse(request, force), { headers: { "Cache-Control": "no-store" } }); } export async function POST(request: Request) { if (!sameOriginRequest(request)) return NextResponse.json({ error: "Updates only accept same-origin requests" }, { status: 403 }); + + const localRepo = localRepoForRequest(request); + if (localRepo) { + if (Date.now() < nextTriggerAt) { + return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 }); + } + const status = await statusResponse(request, true); + if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 }); + if (!status.updateAvailable || !status.latestVersion) { + return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 }); + } + + nextTriggerAt = Date.now() + UPDATE_TRIGGER_COOLDOWN_MS; + try { + const installedVersion = await runLocalUpdate(localRepo, status.latestVersion); + return NextResponse.json( + { + accepted: true, + currentVersion: installedVersion, + latestVersion: status.latestVersion, + updateMode: "local", + restartRequired: true, + }, + { status: 202, headers: { "Cache-Control": "no-store" } }, + ); + } catch (error) { + nextTriggerAt = 0; + return NextResponse.json({ error: error instanceof Error ? error.message : "Could not update local SketchForge" }, { status: 409 }); + } + } + const trigger = updateTriggerUrl(); const adminKey = process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim() || ""; if (!trigger || !adminKey) { @@ -125,7 +248,7 @@ export async function POST(request: Request) { return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 }); } - const status = await statusResponse(true); + const status = await statusResponse(request, true); if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 }); if (!status.updateAvailable || !status.latestVersion) { return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 }); @@ -154,7 +277,7 @@ export async function POST(request: Request) { }); if (!response.ok) throw new Error(`Update service returned ${response.status}`); return NextResponse.json( - { accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion }, + { accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion, updateMode: "server" }, { status: 202, headers: { "Cache-Control": "no-store" } }, ); } catch (error) { diff --git a/apps/web/src/app/api/project-thumbnail/route.ts b/apps/web/src/app/api/project-thumbnail/route.ts index fc88ef2..57ca8a5 100644 --- a/apps/web/src/app/api/project-thumbnail/route.ts +++ b/apps/web/src/app/api/project-thumbnail/route.ts @@ -5,7 +5,6 @@ import { NextResponse } from "next/server"; export const revalidate = false; const THUMBNAIL_DIR = path.join(process.cwd(), ".codex", "project-thumbnails"); -const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]); const PNG_DATA_URL_PREFIX = "data:image/png;base64,"; const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024; const MAX_THUMBNAIL_REQUEST_BYTES = Math.ceil((MAX_THUMBNAIL_BYTES * 4) / 3) + PNG_DATA_URL_PREFIX.length + 2048; @@ -23,26 +22,24 @@ function thumbnailPath(projectId: string) { return path.join(THUMBNAIL_DIR, `${safeId}.png`); } -function isLocalSameOriginRequest(request: Request) { - const requestUrl = new URL(request.url); - if (!LOCAL_HOSTS.has(requestUrl.hostname)) { - return false; - } - +function isSameOriginRequest(request: Request) { const origin = request.headers.get("origin"); if (origin) { try { - const originUrl = new URL(origin); - if (!LOCAL_HOSTS.has(originUrl.hostname) || originUrl.port !== requestUrl.port || originUrl.protocol !== requestUrl.protocol) { - return false; - } + const requestUrl = new URL(request.url); + const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim(); + const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(); + const host = forwardedHost || request.headers.get("host") || requestUrl.host; + const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, "")).toLowerCase(); + if (protocol !== "http" && protocol !== "https") return false; + if (new URL(origin).origin !== new URL(`${protocol}://${host}`).origin) return false; } catch { return false; } } const fetchSite = request.headers.get("sec-fetch-site"); - return !fetchSite || fetchSite === "same-origin" || fetchSite === "same-site" || fetchSite === "none"; + return !fetchSite || fetchSite === "same-origin" || fetchSite === "none"; } function decodedBase64ByteLength(value: string) { @@ -54,8 +51,8 @@ function decodedBase64ByteLength(value: string) { } export async function GET(request: Request) { - if (!isLocalSameOriginRequest(request)) { - return new NextResponse("Project thumbnails are only available from this localhost app", { status: 403 }); + if (!isSameOriginRequest(request)) { + return new NextResponse("Project thumbnails require a same-origin request", { status: 403 }); } const projectId = new URL(request.url).searchParams.get("projectId") ?? ""; @@ -78,8 +75,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - if (!isLocalSameOriginRequest(request)) { - return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 }); + if (!isSameOriginRequest(request)) { + return NextResponse.json({ error: "Project thumbnails require a same-origin request" }, { status: 403 }); } const contentLength = Number(request.headers.get("content-length")); @@ -124,8 +121,8 @@ export async function POST(request: Request) { } export async function DELETE(request: Request) { - if (!isLocalSameOriginRequest(request)) { - return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 }); + if (!isSameOriginRequest(request)) { + return NextResponse.json({ error: "Project thumbnails require a same-origin request" }, { status: 403 }); } const projectId = new URL(request.url).searchParams.get("projectId") ?? ""; diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 940bacb..525c711 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -3459,6 +3459,87 @@ button { vector-effect: non-scaling-stroke; } +.sketch-primitive-preview { + fill: rgba(0, 159, 227, 0.12); + stroke: rgba(0, 117, 184, 0.92); + stroke-width: 1.5; + stroke-dasharray: 5 3; + vector-effect: non-scaling-stroke; +} + +.sketch-primitive-center { + fill: #ffffff; + stroke: rgba(0, 117, 184, 0.95); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-profile-hit-targets path { + fill: transparent; + stroke: transparent; + stroke-width: 10; + vector-effect: non-scaling-stroke; + cursor: move; +} + +.sketch-primitive-source { + cursor: grab; +} + +.sketch-primitive-source:active { + cursor: grabbing; +} + +.sketch-geometry-selection-box { + fill: rgba(0, 117, 184, 0.025); + stroke: rgba(0, 117, 184, 0.82); + stroke-width: 1; + stroke-dasharray: 4 3; + vector-effect: non-scaling-stroke; + cursor: move; +} + +.sketch-geometry-resize-handle { + fill: #ffffff; + stroke: rgba(0, 117, 184, 0.95); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-geometry-resize-handle.handle-nw, +.sketch-geometry-resize-handle.handle-se { + cursor: nwse-resize; +} + +.sketch-geometry-resize-handle.handle-ne, +.sketch-geometry-resize-handle.handle-sw { + cursor: nesw-resize; +} + +.sketch-geometry-resize-handle.handle-n, +.sketch-geometry-resize-handle.handle-s { + cursor: ns-resize; +} + +.sketch-geometry-resize-handle.handle-e, +.sketch-geometry-resize-handle.handle-w { + cursor: ew-resize; +} + +.sketch-geometry-dimension rect { + fill: rgba(255, 255, 255, 0.98); + stroke: rgba(0, 117, 184, 0.8); + stroke-width: 1; + vector-effect: non-scaling-stroke; + filter: drop-shadow(0 1px 2px rgba(25, 55, 76, 0.14)); +} + +.sketch-geometry-dimension text { + fill: #173b5a; + font-weight: 750; + text-anchor: middle; +} + .sketch-plate-background { fill: #ddf8ff; stroke: none; diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 5d422c0..8f5b807 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -802,8 +802,14 @@ export default function Home() { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ dataUrl: snapshot.image, projectId: snapshot.projectId }), }) - .then((response) => (response.ok ? response.json() : null)) - .then((payload: { version?: number } | null) => { + .then(async (response) => { + if (!response.ok) { + const payload = await response.json().catch(() => null) as { error?: string } | null; + throw new Error(payload?.error ?? "Could not save project thumbnail"); + } + return response.json() as Promise<{ version?: number }>; + }) + .then((payload) => { const nextVersion = payload?.version ?? Date.now(); const thumbnailUrl = `/api/project-thumbnail?projectId=${encodeURIComponent(snapshot.projectId)}&v=${nextVersion}`; setProjects((current) => @@ -1529,6 +1535,7 @@ function Dashboard({ updateUrl: "", installationReady: true, requiresUpdateKey: false, + updateMode: "desktop", }; setUpdateStatus(payload); if (result.updateAvailable && result.latestVersion) { @@ -1597,6 +1604,7 @@ function Dashboard({ updateUrl: "", installationReady: true, requiresUpdateKey: false, + updateMode: "desktop", }); setUpdateMessage("SketchForge is already up to date."); } else { @@ -1627,13 +1635,35 @@ function Dashboard({ method: "POST", headers: { "x-sketchforge-update-key": updateKey.trim() }, }); - const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string }; + const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string; updateMode?: "local" | "server"; restartRequired?: boolean }; if (!response.ok || !payload.accepted) throw new Error(payload.error || "Could not start the update"); if (updateStatus.latestVersion) { window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion); } - setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts."); setUpdateKey(""); + if (payload.updateMode === "local" || updateStatus.updateMode === "local") { + const expectedVersion = updateStatus.latestVersion; + setUpdateMessage("Update installed. Restarting local SketchForge…"); + await new Promise((resolve) => window.setTimeout(resolve, 1800)); + for (let attempt = 0; attempt < 60; attempt += 1) { + try { + const statusResponse = await fetch("/api/app-update?force=1", { cache: "no-store" }); + if (statusResponse.ok) { + const statusPayload = await statusResponse.json() as AppUpdateStatus; + if (!expectedVersion || statusPayload.currentVersion === expectedVersion || !statusPayload.updateAvailable) { + window.location.reload(); + return; + } + } + } catch { + // The local dev server is expected to be briefly unavailable while it restarts. + } + await new Promise((resolve) => window.setTimeout(resolve, 500)); + } + setUpdateMessage("Update installed. Reload this page once local SketchForge finishes restarting."); + } else { + setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts."); + } } catch (error) { setUpdateMessage(error instanceof Error ? error.message : "Could not start the update"); } finally { @@ -1964,7 +1994,11 @@ function Dashboard({

Do you want to update from version {updateStatus.currentVersion}?

- Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent /data/projects volume. + {updateStatus.updateMode === "local" ? ( + <>Your browser projects are kept. The updater only replaces the local SketchForge application files. + ) : ( + <>Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent /data/projects volume. + )}
{!updateStatus.installationReady ? (
One-click installation is not configured on this server. Continue to the safe update guide.
@@ -2024,7 +2058,7 @@ function Dashboard({
SketchForge version - {desktopAppVersion ?? SKF_CREATED_WITH_VERSION} + {desktopAppVersion ?? updateStatus?.currentVersion ?? SKF_CREATED_WITH_VERSION}
diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 3fc141a..d433cba 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -1,6 +1,6 @@ "use client"; -import { Check, CloudUpload, Download, Eye, FolderOpen, X } from "lucide-react"; +import { Check, Circle as CircleIcon, CloudUpload, Download, Eye, FolderOpen, Hexagon as HexagonIcon, Square as SquareIcon, Triangle as TriangleIcon, X } from "lucide-react"; import type manifoldModule from "manifold-3d"; import type { ManifoldToplevel } from "manifold-3d"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -48,7 +48,7 @@ import { ToolbarVectorExportIcon, } from "./icons"; import { WorkplaneViewport } from "./WorkplaneViewport"; -import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type SketchTool } from "./SketchWorkspace"; +import { SketchWorkspace, type SketchMeasurement, type SketchPrimitive, type SketchSelection, type SketchTool } from "./SketchWorkspace"; import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel"; import { canonicalizeShape, @@ -64,6 +64,8 @@ import { resizedImportedMeshPositions, serializeShapesForSync, shapeDepth, + shapeHasTaper, + shapeTaperScaleAt, shapeWidth, withHoleMode, workplaneShapesEqual, @@ -89,6 +91,7 @@ import { exportMeshesToObj } from "@/lib/objExport"; import { importedShapeFromObj } from "@/lib/objImport"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation"; +import { addLineIntersectionPoints, splitSketchSegment } from "@/lib/sketchPointRefinement"; import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve"; import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; @@ -1387,6 +1390,15 @@ function shapeFromCadMesh( mirrorY: undefined, mirrorZ: undefined, radius: undefined, + // The CAD result is already generated from the final tapered surface. Do + // not carry the parametric taper fields onto this baked mesh or the viewport + // and subsequent mesh exports will apply the deformation a second time. + taperTopWidth: undefined, + taperTopDepth: undefined, + taperBottomWidth: undefined, + taperBottomDepth: undefined, + taperTopScale: undefined, + taperBottomScale: undefined, importedMesh: { positions: flattenedPositions, normals: flattenedNormals.length === flattenedPositions.length ? flattenedNormals : undefined, @@ -1618,6 +1630,11 @@ function groupedShapeWithComponentEdgeTreatment( ) { if ( !base.groupedShapes?.length || + // A tapered group is sent to CAD as one baked final mesh because the parent + // deformation cannot be represented by its untapered child primitives. + // Keep the treated result flattened instead of rebuilding a nested group + // that would reintroduce the old pre-taper children. + shapeHasTaper(base) || !hasOneToOneCadComponentMapping(sourceParts.length, session.componentPreviews.map((component) => component.owner)) ) { return null; @@ -1758,6 +1775,18 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[] function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData { const centerY = shape.height / 2; + const tapered = shapeHasTaper(shape); + let minLocalY = 0; + let maxLocalY = 1; + if (tapered && mesh.vertices.length) { + minLocalY = Number.POSITIVE_INFINITY; + maxLocalY = Number.NEGATIVE_INFINITY; + mesh.vertices.forEach((vertex) => { + minLocalY = Math.min(minLocalY, vertex[1]); + maxLocalY = Math.max(maxLocalY, vertex[1]); + }); + } + const taperHeight = Math.max(1e-6, maxLocalY - minLocalY); const matrix = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler( THREE.MathUtils.degToRad(shape.rotationX ?? 0), @@ -1773,7 +1802,10 @@ function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData { return { ...mesh, vertices: mesh.vertices.map(([x, y, z]) => { - const vertex = new THREE.Vector3(x * mirrorX, (y - centerY) * mirrorY, z * mirrorZ).applyMatrix4(matrix); + const normalizedHeight = (y - minLocalY) / taperHeight; + const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1; + const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1; + const vertex = new THREE.Vector3(x * widthScale * mirrorX, (y - centerY) * mirrorY, z * depthScale * mirrorZ).applyMatrix4(matrix); return [vertex.x + shape.x, vertex.y + (shape.elevation ?? 0) + centerY, vertex.z + shape.z] as Vec3; }), faces: reversedWinding ? mesh.faces.map(([a, b, c]) => [a, c, b] as [number, number, number]) : mesh.faces, @@ -2334,6 +2366,10 @@ function shapeHasTransformToBake(shape: WorkplaneShape) { } function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimitivePart | null { + // Taper is a non-affine deformation, so an analytic primitive or stored BREP + // cannot represent the final visible surface. Send the baked mesh to the CAD + // worker instead so edge selection/treatment matches the viewport exactly. + if (shapeHasTaper(shape)) return null; return cadModifierPrimitiveForBakedShape(shape) ?? (shapeHasTransformToBake(shape) ? cadModifierPrimitiveForAnalyticBox(shape) : null); } @@ -2404,6 +2440,12 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { mirrorX: undefined, mirrorY: undefined, mirrorZ: undefined, + taperTopWidth: undefined, + taperTopDepth: undefined, + taperBottomWidth: undefined, + taperBottomDepth: undefined, + taperTopScale: undefined, + taperBottomScale: undefined, importedMesh: { positions, baseWidth: rawWidth, @@ -6204,7 +6246,7 @@ export function SketchForgeEditor({ const commitSketchProfile = useCallback( (next: SketchProfile, message?: string) => { - const snapshot = cloneSketchProfile(next); + const snapshot = cloneSketchProfile(addLineIntersectionPoints(next, createLocalId)); const current = sketchHistoryRef.current; const currentIndex = Math.min(sketchHistoryIndexRef.current, Math.max(0, current.length - 1)); const trimmed = current.slice(0, currentIndex + 1); @@ -6341,6 +6383,10 @@ export function SketchForgeEditor({ line: "Line: click points to draw straight segments", bezier: "Bézier: click and drag points to pull curve handles", smooth: "Smooth curve: click points to build a flowing path", + rectangle: "Rectangle: drag across the sketch to create a closed rectangle", + circle: "Circle: drag a bounding box to create a closed circle", + triangle: "Triangle: drag a bounding box to create a closed triangle", + hexagon: "Hexagon: drag a bounding box to create a closed hexagon", select: "Select: edit sketch geometry or place and scale reference images", refine: "Refine: click a segment to add a point, or a point to remove it", erase: "Erase: click a point or segment to remove it", @@ -6434,6 +6480,90 @@ export function SketchForgeEditor({ [commitSketchProfile, connectSketchPoint, measureSketchPoint, sketchActivePointId, sketchProfile, sketchTool], ); + const addSketchPrimitive = useCallback( + (primitive: SketchPrimitive, center: { x: number; z: number } = { x: 0, z: 0 }) => { + const cx = center.x; + const cz = center.z; + const width = 20; + const depth = 20; + const radius = width / 2; + const minX = cx - width / 2; + const maxX = cx + width / 2; + const minZ = cz - depth / 2; + const maxZ = cz + depth / 2; + let points: SketchPoint[] = []; + let segments: SketchSegment[] = []; + + if (primitive === "circle") { + const kappa = 0.5522847498307936; + const right: SketchPoint = { + id: createLocalId("sketch-point"), x: cx + radius, z: cz, mode: "smooth", + handleIn: { x: cx + radius, z: cz - kappa * radius }, + handleOut: { x: cx + radius, z: cz + kappa * radius }, + }; + const bottom: SketchPoint = { + id: createLocalId("sketch-point"), x: cx, z: cz + radius, mode: "smooth", + handleIn: { x: cx + kappa * radius, z: cz + radius }, + handleOut: { x: cx - kappa * radius, z: cz + radius }, + }; + const left: SketchPoint = { + id: createLocalId("sketch-point"), x: cx - radius, z: cz, mode: "smooth", + handleIn: { x: cx - radius, z: cz + kappa * radius }, + handleOut: { x: cx - radius, z: cz - kappa * radius }, + }; + const top: SketchPoint = { + id: createLocalId("sketch-point"), x: cx, z: cz - radius, mode: "smooth", + handleIn: { x: cx - kappa * radius, z: cz - radius }, + handleOut: { x: cx + kappa * radius, z: cz - radius }, + }; + points = [right, bottom, left, top]; + segments = points.map((point, index) => ({ + id: createLocalId("sketch-segment"), + startId: point.id, + endId: points[(index + 1) % points.length]!.id, + kind: "bezier", + })); + } else { + const vertices: Array<{ x: number; z: number }> = primitive === "rectangle" + ? [ + { x: minX, z: minZ }, + { x: maxX, z: minZ }, + { x: maxX, z: maxZ }, + { x: minX, z: maxZ }, + ] + : primitive === "triangle" + ? [ + { x: cx, z: minZ }, + { x: maxX, z: maxZ }, + { x: minX, z: maxZ }, + ] + : Array.from({ length: 6 }, (_, index) => { + const angle = -Math.PI / 2 + index * Math.PI / 3; + return { x: cx + Math.cos(angle) * width / 2, z: cz + Math.sin(angle) * depth / 2 }; + }); + points = vertices.map((vertex) => ({ id: createLocalId("sketch-point"), ...vertex, mode: "corner" })); + segments = points.map((point, index) => ({ + id: createLocalId("sketch-segment"), + startId: point.id, + endId: points[(index + 1) % points.length]!.id, + kind: "line", + })); + } + + const next: SketchProfile = { + ...sketchProfile, + points: [...sketchProfile.points, ...points], + segments: [...sketchProfile.segments, ...segments], + }; + const label = primitive[0]!.toUpperCase() + primitive.slice(1); + commitSketchProfile(next, `${label} added to sketch`); + setSketchActivePointId(null); + setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] }); + setSketchTool("select"); + }, + [commitSketchProfile, sketchProfile], + ); + const pressSketchPoint = useCallback( (id: string) => { const point = sketchProfile.points.find((entry) => entry.id === id); @@ -6584,6 +6714,15 @@ export function SketchForgeEditor({ commitSketchProfile(next, "Sketch point moved"); }, [commitSketchProfile, sketchProfile]); + const transformSketchPoints = useCallback((points: SketchPoint[], message = "Sketch geometry transformed") => { + if (!points.length) return; + const byId = new Map(points.map((point) => [point.id, point])); + commitSketchProfile({ + ...sketchProfile, + points: sketchProfile.points.map((point) => byId.get(point.id) ?? point), + }, message); + }, [commitSketchProfile, sketchProfile]); + const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => { const next = cloneSketchProfile(sketchProfile); const point = next.points.find((entry) => entry.id === id); @@ -6616,21 +6755,11 @@ export function SketchForgeEditor({ commitSketchProfile(next, mode === "corner" ? "Made corner" : mode === "smooth" ? "Made smooth" : "Curve handles split"); }, [commitSketchProfile, sketchProfile]); - const insertSketchPoint = useCallback((segmentId: string, position: { x: number; z: number }) => { - const segment = sketchProfile.segments.find((entry) => entry.id === segmentId); - if (!segment) return; - const point: SketchPoint = { id: createLocalId("sketch-point"), ...position, mode: segment.kind === "line" ? "corner" : "smooth" }; - let next: SketchProfile = { - ...sketchProfile, - points: [...sketchProfile.points, point], - segments: sketchProfile.segments.flatMap((entry) => entry.id === segmentId ? [ - { ...entry, id: createLocalId("sketch-segment"), endId: point.id }, - { ...entry, id: createLocalId("sketch-segment"), startId: point.id }, - ] : [entry]), - }; - if (segment.kind === "smooth") next = withSmoothSketchHandles(next); - commitSketchProfile(next, "Point added to path"); - setSketchSelection({ kind: "point", id: point.id }); + const insertSketchPoint = useCallback((segmentId: string, _position: { x: number; z: number }, amount: number) => { + const result = splitSketchSegment(sketchProfile, segmentId, amount, createLocalId); + if (!result.pointId) return; + if (result.inserted) commitSketchProfile(result.profile, "Point added to path"); + setSketchSelection({ kind: "point", id: result.pointId }); setSketchTool("select"); }, [commitSketchProfile, sketchProfile]); @@ -7149,7 +7278,7 @@ export function SketchForgeEditor({ invalidateCadModifierSession(); const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape); const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); - const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment + const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(selectedShape) ? restoreGroupedChildren(selectedShape) : [selectedShape]).flatMap(cadModifierSourceParts); const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => { @@ -7159,6 +7288,7 @@ export function SketchForgeEditor({ Math.abs(shapeDepth(shape) - (frame?.depth ?? shapeDepth(shape))) > 1e-6 || Math.abs(shape.height - (frame?.height ?? shape.height)) > 1e-6 ); + if (shapeHasTaper(shape)) return { shape, mesh: meshForShape(shape) }; const primitive = cadModifierPrimitiveForShape(shape); if (primitive) return { shape, primitive }; return shape.cadBrep && frame && !preserveNeedsRetessellation @@ -7224,7 +7354,7 @@ export function SketchForgeEditor({ } const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape); const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length); - const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment + const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(shape) ? restoreGroupedChildren(shape) : [shape]).flatMap(cadModifierSourceParts); const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => { @@ -7234,6 +7364,7 @@ export function SketchForgeEditor({ Math.abs(shapeDepth(partShape) - (frame?.depth ?? shapeDepth(partShape))) > 1e-6 || Math.abs(partShape.height - (frame?.height ?? partShape.height)) > 1e-6 ); + if (shapeHasTaper(partShape)) return { shape: partShape, mesh: meshForShape(partShape) }; const primitive = cadModifierPrimitiveForShape(partShape); if (primitive) return { shape: partShape, primitive }; return partShape.cadBrep && frame && !preserveNeedsRetessellation @@ -8359,7 +8490,8 @@ export function SketchForgeEditor({ } const meshes = exportable.map(meshForShape); if (format === "stl") { - void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl") + const blob = new Blob([exportMeshesToStl(meshes)], { type: "model/stl" }); + void downloadBlobFile(projectExportFileName(exportName, "stl"), blob) .then((result) => finishNotice("STL", result)) .catch((error: unknown) => failNotice("STL", error)); return; @@ -8821,7 +8953,7 @@ export function SketchForgeEditor({ return; } - if (!shortcut && !event.altKey && key === "r" && hasSelection) { + if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) { event.preventDefault(); rotateSelected45(); return; @@ -8931,6 +9063,7 @@ export function SketchForgeEditor({ onStartSketch={(operation) => beginSketch(operation)} onEditSketch={beginSketchEdit} onSketchTool={setActiveSketchTool} + onSketchPrimitive={(primitive) => addSketchPrimitive(primitive, { x: 0, z: 0 })} onSketchImage={() => { if (sketchTool !== "select") { setNotice("Choose Select before adding a sketch image"); @@ -8985,6 +9118,7 @@ export function SketchForgeEditor({ initialSnap={snapGrid} initialWorkspace={workspaceSettings} onPlanePoint={addSketchPlanePoint} + onAddPrimitive={addSketchPrimitive} onPointPress={pressSketchPoint} onSelectSegment={(id) => { setSketchSelection({ kind: "segment", id }); @@ -9006,6 +9140,7 @@ export function SketchForgeEditor({ onDeletePoint={deleteSketchPoint} onDeleteSegment={deleteSketchSegment} onMovePoint={moveSketchPoint} + onTransformPoints={transformSketchPoints} onMoveHandle={moveSketchHandle} onInsertPoint={insertSketchPoint} onSetPointMode={setSketchPointMode} @@ -9227,6 +9362,7 @@ function SecondaryToolbar({ onStartSketch, onEditSketch, onSketchTool, + onSketchPrimitive, onSketchImage, onSketchUndo, onSketchRedo, @@ -9278,6 +9414,7 @@ function SecondaryToolbar({ onStartSketch: (operation: SketchOperation) => void; onEditSketch: () => void; onSketchTool: (tool: SketchTool) => void; + onSketchPrimitive: (primitive: SketchPrimitive) => void; onSketchImage: () => void; onSketchUndo: () => void; onSketchRedo: () => void; @@ -9647,6 +9784,23 @@ function SecondaryToolbar({
+
+
Shapes
+
+ + + + +
+
Select
diff --git a/apps/web/src/components/SketchWorkspace.tsx b/apps/web/src/components/SketchWorkspace.tsx index f5386f3..3619acb 100644 --- a/apps/web/src/components/SketchWorkspace.tsx +++ b/apps/web/src/components/SketchWorkspace.tsx @@ -6,11 +6,13 @@ import { SnapGridControl } from "@/components/workplane/ShapeInspector"; import { SketchRevolvePreview } from "@/components/SketchRevolvePreview"; import { parseMeasurementInput } from "@/lib/measurementUnits"; import { WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid"; +import { closestPointOnSketchSegment, type SketchSegmentPlacement } from "@/lib/sketchPointRefinement"; import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import type { GridSize, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; -export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure"; +export type SketchPrimitive = "rectangle" | "circle" | "triangle" | "hexagon"; +export type SketchTool = "line" | "bezier" | "smooth" | SketchPrimitive | "select" | "refine" | "erase" | "measure"; export type SketchSelection = | { kind: "point"; id: string } | { kind: "segment"; id: string } @@ -32,6 +34,7 @@ type SketchWorkspaceProps = { initialSnap?: GridSize; initialWorkspace?: WorkplaneWorkspaceSettings; onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void; + onAddPrimitive: (primitive: SketchPrimitive, center: { x: number; z: number }) => void; onPointPress: (id: string) => void; onSelectSegment: (id: string) => void; onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void; @@ -41,8 +44,9 @@ type SketchWorkspaceProps = { onDeletePoint: (id: string) => void; onDeleteSegment: (id: string) => void; onMovePoint: (id: string, point: { x: number; z: number }) => void; + onTransformPoints: (points: SketchPoint[], message?: string) => void; onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void; - onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void; + onInsertPoint: (segmentId: string, point: { x: number; z: number }, amount: number) => void; onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void; onClearMeasurement: () => void; }; @@ -53,6 +57,8 @@ 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 } } + | { kind: "move-selection"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number }; startPoints: SketchPoint[] } + | { kind: "resize-selection"; pointerId: number; handle: ResizeHandle; current: { x: number; z: number }; startPoints: SketchPoint[]; bounds: SelectionBounds } | { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } } | { kind: "pan"; pointerId: number; clientX: number; clientY: number } | { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } @@ -60,6 +66,7 @@ type PointerAction = | { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage }; type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; +type SelectionBounds = { minX: number; maxX: number; minZ: number; maxZ: number; width: number; depth: number; cx: number; cz: number }; function snapStep(size: GridSize) { if (size === "Off") return 0; @@ -126,6 +133,62 @@ function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x: }; } +function boundsForSketchPoints(points: SketchPoint[]): SelectionBounds | null { + if (points.length < 2) return null; + const xs = points.map((point) => point.x); + const zs = points.map((point) => point.z); + const minX = Math.min(...xs); + const maxX = Math.max(...xs); + const minZ = Math.min(...zs); + const maxZ = Math.max(...zs); + return { + minX, + maxX, + minZ, + maxZ, + width: maxX - minX, + depth: maxZ - minZ, + cx: (minX + maxX) / 2, + cz: (minZ + maxZ) / 2, + }; +} + +function translateSketchPoints(points: SketchPoint[], dx: number, dz: number) { + return points.map((point) => ({ + ...point, + x: point.x + dx, + z: point.z + dz, + handleIn: point.handleIn ? { x: point.handleIn.x + dx, z: point.handleIn.z + dz } : undefined, + handleOut: point.handleOut ? { x: point.handleOut.x + dx, z: point.handleOut.z + dz } : undefined, + })); +} + +function resizeSketchPoints(points: SketchPoint[], bounds: SelectionBounds, handle: ResizeHandle, current: { x: number; z: number }) { + const minimum = 0.5; + let minX = bounds.minX; + let maxX = bounds.maxX; + let minZ = bounds.minZ; + let maxZ = bounds.maxZ; + if (handle.includes("w")) minX = Math.min(current.x, bounds.maxX - minimum); + if (handle.includes("e")) maxX = Math.max(current.x, bounds.minX + minimum); + if (handle.includes("n")) minZ = Math.min(current.z, bounds.maxZ - minimum); + if (handle.includes("s")) maxZ = Math.max(current.z, bounds.minZ + minimum); + const width = Math.max(minimum, bounds.width); + const depth = Math.max(minimum, bounds.depth); + const scaleX = (maxX - minX) / width; + const scaleZ = (maxZ - minZ) / depth; + const map = (value: { x: number; z: number }) => ({ + x: minX + (value.x - bounds.minX) * scaleX, + z: minZ + (value.z - bounds.minZ) * scaleZ, + }); + return points.map((point) => ({ + ...point, + ...map(point), + handleIn: point.handleIn ? map(point.handleIn) : undefined, + handleOut: point.handleOut ? map(point.handleOut) : undefined, + })); +} + function formatDimension(value: number, accuracy: 1 | 2 | 3) { const threshold = 0.5 * 10 ** -accuracy; return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy); @@ -414,6 +477,7 @@ export function SketchWorkspace({ initialSnap, initialWorkspace, onPlanePoint, + onAddPrimitive, onPointPress, onSelectSegment, onSelectMany, @@ -423,6 +487,7 @@ export function SketchWorkspace({ onDeletePoint, onDeleteSegment, onMovePoint, + onTransformPoints, onMoveHandle, onInsertPoint, onSetPointMode, @@ -434,6 +499,7 @@ export function SketchWorkspace({ const [zoom, setZoom] = useState(1); const [pan, setPan] = useState({ x: 0, z: 0 }); const [hover, setHover] = useState<{ x: number; z: number } | null>(null); + const [refinePreview, setRefinePreview] = useState<{ segmentId: string; placement: SketchSegmentPlacement } | null>(null); const [pointerAction, setPointerAction] = useState(null); const [svgSize, setSvgSize] = useState({ width: 0, height: 0 }); const svgRef = useRef(null); @@ -447,6 +513,20 @@ export function SketchWorkspace({ return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720; }, [depth, svgSize.height, svgSize.width, width]); const displayProfile = useMemo(() => { + if (pointerAction?.kind === "move-selection") { + const moved = translateSketchPoints( + pointerAction.startPoints, + pointerAction.current.x - pointerAction.origin.x, + pointerAction.current.z - pointerAction.origin.z, + ); + const movedById = new Map(moved.map((point) => [point.id, point])); + return { ...profile, points: profile.points.map((point) => movedById.get(point.id) ?? point) }; + } + if (pointerAction?.kind === "resize-selection") { + const resized = resizeSketchPoints(pointerAction.startPoints, pointerAction.bounds, pointerAction.handle, pointerAction.current); + const resizedById = new Map(resized.map((point) => [point.id, point])); + return { ...profile, points: profile.points.map((point) => resizedById.get(point.id) ?? point) }; + } if (pointerAction?.kind === "move-point") { const source = profile.points.find((point) => point.id === pointerAction.pointId); if (!source) return profile; @@ -498,6 +578,10 @@ export function SketchWorkspace({ const activePoint = activePointId ? pointById.get(activePointId) ?? null : null; const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null; const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null; + const selectedGeometryPoints = selected?.kind === "multiple" + ? selected.pointIds.map((id) => pointById.get(id)).filter((point): point is SketchPoint => Boolean(point)) + : []; + const selectedGeometryBounds = boundsForSketchPoints(selectedGeometryPoints); const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false; const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false; const gridStep = clamp(workspace.gridBlockSize, 1, 200); @@ -529,6 +613,10 @@ export function SketchWorkspace({ }; }; + useEffect(() => { + if (tool !== "refine") setRefinePreview(null); + }, [tool]); + useEffect(() => { const svg = svgRef.current; if (!svg) return; @@ -619,6 +707,13 @@ export function SketchWorkspace({ handleIn: { x: action.origin.x - dx, z: action.origin.z - dz }, handleOut: { x: action.origin.x + dx, z: action.origin.z + dz }, }); + } else if (action.kind === "move-selection") { + onTransformPoints( + translateSketchPoints(action.startPoints, action.current.x - action.origin.x, action.current.z - action.origin.z), + "Sketch shape moved", + ); + } else if (action.kind === "resize-selection") { + onTransformPoints(resizeSketchPoints(action.startPoints, action.bounds, action.handle, action.current), "Sketch shape resized"); } else if (action.kind === "move-point") { onMovePoint(action.pointId, action.current); } else if (action.kind === "move-handle") { @@ -673,6 +768,16 @@ export function SketchWorkspace({ { id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ }, { id: "w", x: selectedImageBounds.minX, z: selectedImage.z }, ] : []; + const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [ + { id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ }, + { id: "n", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.minZ }, + { id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ }, + { id: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz }, + { id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ }, + { id: "s", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.maxZ }, + { id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ }, + { id: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz }, + ] : []; const referenceFootprints = useMemo( () => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])), [referenceShapes], @@ -697,8 +802,23 @@ export function SketchWorkspace({ onPointerMove={handlePointerMove} onPointerUp={finishPointerAction} onPointerCancel={() => setPointerAction(null)} - onPointerLeave={() => !pointerAction && setHover(null)} + onPointerLeave={() => { + if (!pointerAction) setHover(null); + setRefinePreview(null); + }} onWheel={handleWheel} + onDragOver={(event) => { + if (!event.dataTransfer.types.includes("application/x-sketchforge-sketch-primitive")) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "copy"; + }} + onDrop={(event) => { + const primitive = event.dataTransfer.getData("application/x-sketchforge-sketch-primitive") as SketchPrimitive; + if (!["rectangle", "circle", "triangle", "hexagon"].includes(primitive)) return; + event.preventDefault(); + const point = pointFromEvent(event); + if (point) onAddPrimitive(primitive, point); + }} > {workspace.showGrid ? ( @@ -783,6 +903,29 @@ export function SketchWorkspace({ {paths.some((path) => path.closed) ? path.closed).map(pathData).join(" ")} /> : null} + + {paths.filter((path) => path.closed).map((path) => ( + { + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0 || tool !== "select") return; + const point = pointFromEvent(event); + if (!point) return; + const pointIds = path.points.map((entry) => entry.id); + const segmentIds = path.steps.map((step) => step.segment.id); + const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined })); + onSelectMany(pointIds, segmentIds, []); + beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints }); + }} + /> + ))} + {displayProfile.segments.map((segment) => ( { + if (tool !== "refine") return; + const target = pointFromEvent(event); + const start = pointById.get(segment.startId); + const end = pointById.get(segment.endId); + if (!target || !start || !end) return; + setRefinePreview({ segmentId: segment.id, placement: closestPointOnSketchSegment(segment, start, end, target) }); + }} + onPointerLeave={() => { + if (tool === "refine") setRefinePreview((current) => current?.segmentId === segment.id ? null : current); + }} onPointerDown={(event) => { const point = pointFromEvent(event); event.preventDefault(); event.stopPropagation(); if (event.button === 1) beginPan(event); else if (tool === "erase") onDeleteSegment(segment.id); - else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point); - else if (event.button === 0) onSelectSegment(segment.id); + else if (event.button === 0 && tool === "refine" && point) { + const start = pointById.get(segment.startId); + const end = pointById.get(segment.endId); + if (start && end) { + const placement = closestPointOnSketchSegment(segment, start, end, point); + onInsertPoint(segment.id, placement.point, placement.amount); + } + } + else if (event.button === 0 && tool === "select" && point) { + const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === segment.id)); + if (!closedPath) { + onSelectSegment(segment.id); + return; + } + const pointIds = closedPath.points.map((entry) => entry.id); + const segmentIds = closedPath.steps.map((step) => step.segment.id); + const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined })); + onSelectMany(pointIds, segmentIds, []); + beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints }); + } else if (event.button === 0) onSelectSegment(segment.id); }} /> ))} + {tool === "refine" && refinePreview ? ( + + ) : null} - {displayProfile.segments.map((segment) => { + {selected?.kind === "multiple" ? null : displayProfile.segments.map((segment) => { const dimension = segmentDimension(segment, pointById); if (!dimension) return null; const label = formatDimension(dimension.length, workspace.accuracy); @@ -816,6 +998,66 @@ export function SketchWorkspace({ ); })} + {selectedGeometryBounds && tool === "select" ? (() => { + const widthLabel = formatDimension(selectedGeometryBounds.width, workspace.accuracy); + const depthLabel = formatDimension(selectedGeometryBounds.depth, workspace.accuracy); + const widthPill = dimensionPillSize(widthLabel, screenUnit, 18); + const depthPill = dimensionPillSize(depthLabel, screenUnit, 18); + return ( + + { + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0 || selected?.kind !== "multiple") return; + const point = pointFromEvent(event); + if (!point) return; + const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined })); + beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints }); + }} + /> + + + {widthLabel} + + + + {depthLabel} + + {selectionResizeHandles.map((handle) => ( + { + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0 || selected?.kind !== "multiple") return; + const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined })); + const bounds = boundsForSketchPoints(startPoints); + if (!bounds) return; + beginEntityDrag(event, { kind: "resize-selection", pointerId: event.pointerId, handle: handle.id, current: { x: handle.x, z: handle.z }, startPoints, bounds }); + }} + /> + ))} + + ); + })() : null} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? : null} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? ( @@ -888,8 +1130,17 @@ export function SketchWorkspace({ } else if (tool === "erase" || tool === "refine") { onDeletePoint(point.id); } else if (event.button === 0 && tool === "select") { - onPointPress(point.id); - beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } }); + const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id)); + if (closedPath) { + const pointIds = closedPath.points.map((entry) => entry.id); + const segmentIds = closedPath.steps.map((step) => step.segment.id); + const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined })); + onSelectMany(pointIds, segmentIds, []); + beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: { x: point.x, z: point.z }, current: { x: point.x, z: point.z }, startPoints }); + } else { + onPointPress(point.id); + beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } }); + } } else if (event.button === 0) { onPointPress(point.id); } diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 8226e0b..4bb5fc5 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -44,7 +44,7 @@ import { import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings"; import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid"; -import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; +import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes"; import { sphereTessellation } from "@/lib/sphereTessellation"; import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol"; import { @@ -214,6 +214,15 @@ type WorkplaneViewportProps = { type WorkspaceSettings = WorkplaneWorkspaceSettings; type ViewCubeFace = "top" | "bottom" | "front" | "back" | "right" | "left"; +const VIEW_FACE_SHORTCUTS: Readonly> = { + "1": "front", + "2": "back", + "3": "left", + "4": "right", + "5": "top", + "6": "bottom", +}; + function readSavedWorkspaceDefault(key: string | null) { if (!key || typeof window === "undefined") { return null; @@ -816,6 +825,12 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string { segments: shape.segments, topRadius: shape.topRadius, baseRadius: shape.baseRadius, + taperTopWidth: shape.taperTopWidth, + taperTopDepth: shape.taperTopDepth, + taperBottomWidth: shape.taperBottomWidth, + taperBottomDepth: shape.taperBottomDepth, + taperTopScale: shape.taperTopScale, + taperBottomScale: shape.taperBottomScale, teeth: shape.teeth, toothSize: shape.toothSize, toothWidth: shape.toothWidth, @@ -872,12 +887,16 @@ function shapeMaterialSignature(shape: WorkplaneShape): string { } function shapeGeometrySignature(shape: WorkplaneShape): string { + const taper = shape.kind === "gear" || !shapeHasTaper(shape) + ? null + : { ...shapeTaperDimensions(shape), baseWidth: shapeWidth(shape), baseDepth: shapeDepth(shape) }; if (shape.groupedShapes?.length && !shape.importedMesh) { return JSON.stringify({ kind: "group", width: shapeWidth(shape), depth: shapeDepth(shape), height: shape.height, + taper, children: shape.groupedShapes.map((child) => [ child.id, child.hidden, @@ -894,6 +913,7 @@ function shapeGeometrySignature(shape: WorkplaneShape): string { return JSON.stringify({ kind: "mesh", mesh: shapeResourceId(shape.importedMesh), + taper, preserve: preservesEdgeTreatmentSize(shape) ? [shapeWidth(shape), shapeDepth(shape), shape.height, shape.edgeTreatments] : false, @@ -901,16 +921,16 @@ function shapeGeometrySignature(shape: WorkplaneShape): string { } if (shape.kind === "box" && !(shape.radius && shape.radius > 0)) { - return JSON.stringify({ kind: "box" }); + return JSON.stringify({ kind: "box", taper }); } if (shape.kind === "cylinder") { - return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments }); + return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments, taper }); } if (shape.kind === "sphere") { - return JSON.stringify({ kind: "sphere", steps: shape.steps }); + return JSON.stringify({ kind: "sphere", steps: shape.steps, taper }); } if (shape.kind === "polygon") { - return JSON.stringify({ kind: "polygon" }); + return JSON.stringify({ kind: "polygon", taper }); } return JSON.stringify({ @@ -926,6 +946,12 @@ function shapeGeometrySignature(shape: WorkplaneShape): string { segments: shape.segments, topRadius: shape.topRadius, baseRadius: shape.baseRadius, + taperTopWidth: shape.taperTopWidth, + taperTopDepth: shape.taperTopDepth, + taperBottomWidth: shape.taperBottomWidth, + taperBottomDepth: shape.taperBottomDepth, + taperTopScale: shape.taperTopScale, + taperBottomScale: shape.taperBottomScale, teeth: shape.teeth, toothSize: shape.toothSize, toothWidth: shape.toothWidth, @@ -1442,10 +1468,11 @@ function shapeCenter(shape: WorkplaneShape) { } function shapeLocalExtents(shape: WorkplaneShape) { + const footprint = shapeOverallFootprintDimensions(shape); return { - x: shapeWidth(shape) / 2, + x: footprint.width / 2, y: shape.height / 2, - z: shapeDepth(shape) / 2, + z: footprint.depth / 2, }; } @@ -1490,13 +1517,28 @@ function importedShapeProjectionBounds( const min = new THREE.Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); const max = new THREE.Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); const point = new THREE.Vector3(); + const tapered = shapeHasTaper(shape); + let taperMinY = Number.POSITIVE_INFINITY; + let taperMaxY = Number.NEGATIVE_INFINITY; + if (tapered) { + for (let index = 1; index < positions.length; index += 3) { + const localY = positions[index] * scaleY; + taperMinY = Math.min(taperMinY, localY); + taperMaxY = Math.max(taperMaxY, localY); + } + } + const taperHeight = Math.max(1e-6, taperMaxY - taperMinY); for (let index = 0; index + 2 < positions.length; index += 3) { + const localY = positions[index + 1] * scaleY; + const normalizedHeight = tapered ? (localY - taperMinY) / taperHeight : 0; + const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1; + const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1; point .set( - positions[index] * scaleX, - positions[index + 1] * scaleY - shape.height / 2, - positions[index + 2] * scaleZ, + positions[index] * scaleX * widthScale, + localY - shape.height / 2, + positions[index + 2] * scaleZ * depthScale, ) .applyQuaternion(quaternion) .add(center); @@ -1713,6 +1755,27 @@ function resizedShapePatchFromFrame(shape: WorkplaneShape, center: THREE.Vector3 return patch; } +function scaledHorizontalShapePatch(shape: WorkplaneShape, scaleX: number, scaleZ: number): Partial { + const width = Math.max(MIN_SHAPE_SIZE, shapeWidth(shape) * scaleX); + const depth = Math.max(MIN_SHAPE_SIZE, shapeDepth(shape) * scaleZ); + const patch: Partial = { + width, + depth, + size: resizedShapeSize(width, depth), + }; + if (shape.kind === "cone") { + patch.baseRadius = width / 2; + } + if (shapeHasTaper(shape)) { + const taper = shapeTaperDimensions(shape); + patch.taperTopWidth = Math.max(MIN_SHAPE_SIZE, taper.topWidth * scaleX); + patch.taperBottomWidth = Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scaleX); + patch.taperTopDepth = Math.max(MIN_SHAPE_SIZE, taper.topDepth * scaleZ); + patch.taperBottomDepth = Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scaleZ); + } + return patch; +} + function shapeScreenBounds(state: ThreeState, shape: WorkplaneShape) { const frame = selectionFrameForShapes([shape], [shape.id]); if (!frame) { @@ -1895,12 +1958,16 @@ function patchWithResizeAnchor( return patchWithPreservedWorldBottom(shape, patch); } - const width = Math.max(MIN_SHAPE_SIZE, patch.width ?? shapeWidth(shape)); - const depth = Math.max(MIN_SHAPE_SIZE, patch.depth ?? shapeDepth(shape)); + const draftShape = { ...shape, ...patch }; + const draftFrame = selectionFrameForShapes([draftShape], [shape.id]); + const width = Math.max(MIN_SHAPE_SIZE, draftFrame?.width ?? patch.width ?? shapeWidth(shape)); + const depth = Math.max(MIN_SHAPE_SIZE, draftFrame?.depth ?? patch.depth ?? shapeDepth(shape)); const center = resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, width, depth); return patchWithPreservedWorldBottom(shape, { ...patch, - ...resizedShapePatchFromFrame(shape, center, width, depth), + x: cleanNearZero(center.x, 0.0005), + z: cleanNearZero(center.z, 0.0005), + elevation: cleanNearZero(center.y - shape.height / 2, 0.0005), }); } @@ -1945,6 +2012,17 @@ function resizeShapeFromFrameHandle( const nextCenter = altKey ? frame.center.clone() : resizeCenterFromAnchor(frame, transform.scaleAnchorPoint ?? resizeAnchorPointForFrame(frame, signs), signs, nextWidth, nextDepth); + if (shapeHasTaper(shape)) { + const scaleX = nextWidth / Math.max(MIN_SHAPE_SIZE, width); + const scaleZ = nextDepth / Math.max(MIN_SHAPE_SIZE, depth); + const scaled = scaledHorizontalShapePatch(shape, scaleX, scaleZ); + return { + ...scaled, + x: cleanNearZero(nextCenter.x, 0.0005), + z: cleanNearZero(nextCenter.z, 0.0005), + elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005), + }; + } return resizedShapePatchFromFrame(shape, nextCenter, nextWidth, nextDepth); } @@ -2176,13 +2254,13 @@ function resizeSelectionFromHandle( .add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale)); const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260); const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, 260); + const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape)); + const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape)); const patch = { + ...scaledHorizontalShapePatch(item.startShape, actualScaleX, actualScaleZ), x: nextItemCenter.x, z: nextItemCenter.z, elevation: cleanNearZero(nextItemCenter.y - item.startShape.height / 2, 0.0005), - width, - depth, - size: resizedShapeSize(width, depth), } satisfies Partial; return { id: item.id, @@ -3722,13 +3800,45 @@ export function WorkplaneViewport({ if (Number.isFinite(value) && value > 0) { const nextValue = Math.max(MIN_SHAPE_SIZE, value); if (edit.axis === "width") { - const patch: Partial = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) }; - if (shape.kind === "cone") { - patch.baseRadius = nextValue / 2; + const frame = selectionFrameForShapes([shape], [shape.id]); + if (shapeHasTaper(shape) && frame) { + const scaleX = nextValue / Math.max(MIN_SHAPE_SIZE, frame.width); + const anchor = lastResizeAnchorRef.current; + const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "width") : { x: 0, z: 0 }; + const nextCenter = signs.x + ? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, nextValue, frame.depth) + : frame.center.clone(); + onUpdateShape(id, { + ...scaledHorizontalShapePatch(shape, scaleX, 1), + x: cleanNearZero(nextCenter.x, 0.0005), + z: cleanNearZero(nextCenter.z, 0.0005), + elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005), + }); + } else { + const patch: Partial = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) }; + if (shape.kind === "cone") { + patch.baseRadius = nextValue / 2; + } + onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current)); } - onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current)); } else if (edit.axis === "depth") { - onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current)); + const frame = selectionFrameForShapes([shape], [shape.id]); + if (shapeHasTaper(shape) && frame) { + const scaleZ = nextValue / Math.max(MIN_SHAPE_SIZE, frame.depth); + const anchor = lastResizeAnchorRef.current; + const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "depth") : { x: 0, z: 0 }; + const nextCenter = signs.z + ? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, frame.width, nextValue) + : frame.center.clone(); + onUpdateShape(id, { + ...scaledHorizontalShapePatch(shape, 1, scaleZ), + x: cleanNearZero(nextCenter.x, 0.0005), + z: cleanNearZero(nextCenter.z, 0.0005), + elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005), + }); + } else { + onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current)); + } } else { onUpdateShape(id, patchWithResizeAnchor(shape, { height: nextValue }, edit.axis, lastResizeAnchorRef.current)); } @@ -4740,6 +4850,9 @@ export function WorkplaneViewport({ } const key = event.key.toLowerCase(); + const shortcutView = !event.ctrlKey && !event.metaKey && !event.altKey + ? VIEW_FACE_SHORTCUTS[event.key] + : undefined; if (event.key === "Escape" && workplaneModeRef.current) { event.preventDefault(); onWorkplaneModeChange(false); @@ -4752,6 +4865,9 @@ export function WorkplaneViewport({ setRulerMoveMode(false); rulerPointDragRef.current = null; setRulerToolsOpen(false); + } else if (shortcutView) { + event.preventDefault(); + setViewCubeFace(shortcutView); } else if (key === "w") { event.preventDefault(); if (!event.shiftKey || !setPlacementWorkplaneAtSelection()) { @@ -4774,18 +4890,18 @@ export function WorkplaneViewport({ window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); - }, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]); + }, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, setViewCubeFace, togglePlacementWorkplane, toggleProjection, zoomCamera]); return (
event.stopPropagation()}>
- - - - - - + + + + + +
@@ -7088,6 +7204,7 @@ function createShapeObject( ); content.position.y = -shape.height / 2; group.add(content); + applyGroupedContentTaper(content, shape, contentBox); group.traverse((child) => { child.userData.shapeId = shape.id; }); @@ -7259,6 +7376,83 @@ function createImagePlateMaterials(shape: WorkplaneShape, sideMaterial: THREE.Me ]; } +function taperGeometryForShape(geometry: THREE.BufferGeometry, shape: WorkplaneShape) { + if (!shapeHasTaper(shape)) return geometry; + const tapered = geometry.userData.cached ? geometry.clone() : geometry; + if (tapered !== geometry) { + tapered.userData = {}; + } + tapered.computeBoundingBox(); + const box = tapered.boundingBox; + const position = tapered.getAttribute("position"); + if (!box || !position) return tapered; + const height = Math.max(1e-6, box.max.y - box.min.y); + const centerX = (box.min.x + box.max.x) / 2; + const centerZ = (box.min.z + box.max.z) / 2; + for (let index = 0; index < position.count; index += 1) { + const y = position.getY(index); + const normalizedHeight = (y - box.min.y) / height; + const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width"); + const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth"); + position.setXYZ( + index, + centerX + (position.getX(index) - centerX) * widthScale, + y, + centerZ + (position.getZ(index) - centerZ) * depthScale, + ); + } + position.needsUpdate = true; + tapered.computeVertexNormals(); + tapered.computeBoundingBox(); + tapered.computeBoundingSphere(); + return tapered; +} + +function applyGroupedContentTaper(content: THREE.Group, shape: WorkplaneShape, baseBounds: THREE.Box3) { + if (!shapeHasTaper(shape)) return; + const height = Math.max(1e-6, baseBounds.max.y - baseBounds.min.y); + const centerX = (baseBounds.min.x + baseBounds.max.x) / 2; + const centerZ = (baseBounds.min.z + baseBounds.max.z) / 2; + content.updateMatrixWorld(true); + const contentWorldInverse = content.matrixWorld.clone().invert(); + content.traverse((object) => { + if (!(object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.LineSegments)) return; + if (!(object.geometry instanceof THREE.BufferGeometry)) return; + const sourcePosition = object.geometry.getAttribute("position"); + if (!sourcePosition) return; + object.updateMatrixWorld(true); + const localToContent = new THREE.Matrix4().multiplyMatrices(contentWorldInverse, object.matrixWorld); + const contentToLocal = localToContent.clone().invert(); + if (object instanceof THREE.Mesh) { + releaseSharedShapeGeometry(object); + } + const nextGeometry = object.geometry.clone(); + nextGeometry.userData = {}; + const position = nextGeometry.getAttribute("position"); + const point = new THREE.Vector3(); + for (let index = 0; index < position.count; index += 1) { + point.fromBufferAttribute(position, index).applyMatrix4(localToContent); + const normalizedHeight = (point.y - baseBounds.min.y) / height; + const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width"); + const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth"); + point.x = centerX + (point.x - centerX) * widthScale; + point.z = centerZ + (point.z - centerZ) * depthScale; + point.applyMatrix4(contentToLocal); + position.setXYZ(index, point.x, point.y, point.z); + } + position.needsUpdate = true; + if (object instanceof THREE.Mesh) { + nextGeometry.computeVertexNormals(); + } + nextGeometry.computeBoundingBox(); + nextGeometry.computeBoundingSphere(); + object.geometry = nextGeometry; + if (object instanceof THREE.Mesh && content.userData.acceleratedPicking !== false) { + enableAcceleratedMeshPicking(object, nextGeometry, Boolean(shape.importedMesh)); + } + }); +} + function addMesh( group: THREE.Group, geometry: THREE.BufferGeometry, @@ -7268,7 +7462,8 @@ function addMesh( rotation?: THREE.Euler, scale?: THREE.Vector3, ) { - const prepared = geometry.userData.cached ? geometry : putGeometryOnBase(geometry); + const based = geometry.userData.cached ? geometry : putGeometryOnBase(geometry); + const prepared = taperGeometryForShape(based, shape); const mesh = new THREE.Mesh(prepared, material); mesh.userData.shapeSurface = true; retainSharedShapeGeometry(mesh, prepared); @@ -7375,7 +7570,7 @@ function getPreservedImportedMeshGeometry(shape: WorkplaneShape) { } function getEdgesGeometry(shape: WorkplaneShape, geometry: THREE.BufferGeometry, threshold: number) { - const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape) + const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape) && !shapeHasTaper(shape) ? getImportedMeshCache(shape.importedMesh).edges : null; let cache = importedCache ?? sharedEdgesGeometryCache.get(geometry); diff --git a/apps/web/src/components/workplane/ShapeInspector.tsx b/apps/web/src/components/workplane/ShapeInspector.tsx index 8ad542a..98d5f21 100644 --- a/apps/web/src/components/workplane/ShapeInspector.tsx +++ b/apps/web/src/components/workplane/ShapeInspector.tsx @@ -22,7 +22,7 @@ import { gearToothPitch, } from "@/lib/gearGeometry"; import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits"; -import { resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; +import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes"; import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve"; import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; @@ -104,18 +104,52 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step } function propertyUsesLengthUnit(label: string) { - return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole"].includes(label); + return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label); } function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] { - const width = shapeWidth(shape); - const depth = shapeDepth(shape); - const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" }); - const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) }, { resizeAxis: "depth" }); - const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" }); + const baseWidth = shapeWidth(shape); + const baseDepth = shapeDepth(shape); + const footprint = shapeOverallFootprintDimensions(shape); + const width = footprint.width; + const depth = footprint.depth; + const taper = shapeTaperDimensions(shape); + const widthPatch = (value: number): Partial => { + if (!shapeHasTaper(shape)) { + return { width: value, size: resizedShapeSize(value, baseDepth) }; + } + const scale = value / Math.max(MIN_SHAPE_SIZE, width); + const nextBaseWidth = Math.max(MIN_SHAPE_SIZE, baseWidth * scale); + return { + width: nextBaseWidth, + size: resizedShapeSize(nextBaseWidth, baseDepth), + taperTopWidth: Math.max(MIN_SHAPE_SIZE, taper.topWidth * scale), + taperBottomWidth: Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scale), + }; + }; + const depthPatch = (value: number): Partial => { + if (!shapeHasTaper(shape)) { + return { depth: value, size: resizedShapeSize(baseWidth, value) }; + } + const scale = value / Math.max(MIN_SHAPE_SIZE, depth); + const nextBaseDepth = Math.max(MIN_SHAPE_SIZE, baseDepth * scale); + return { + depth: nextBaseDepth, + size: resizedShapeSize(baseWidth, nextBaseDepth), + taperTopDepth: Math.max(MIN_SHAPE_SIZE, taper.topDepth * scale), + taperBottomDepth: Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scale), + }; + }; + const setWidth = (value: number) => onUpdate(widthPatch(value), { resizeAxis: "width" }); + const setDepth = (value: number) => onUpdate(depthPatch(value), { resizeAxis: "depth" }); + const setConeWidth = (value: number) => { + const patch = widthPatch(value); + patch.baseRadius = Math.max(MIN_SHAPE_SIZE, (patch.width ?? baseWidth) / 2); + onUpdate(patch, { resizeAxis: "width" }); + }; const setBaseRadius = (value: number) => { const diameter = value * 2; - onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, depth) }, { resizeAxis: "width" }); + onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, baseDepth) }, { resizeAxis: "width" }); }; const setHeight = (height: number) => onUpdate({ height }, { resizeAxis: "height" }); @@ -171,7 +205,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat if (shape.kind === "cone") { return [ { label: "Top Radius", value: shape.topRadius ?? 0, min: 0, max: 40, onChange: (topRadius) => onUpdate({ topRadius }) }, - { label: "Base Radius", value: shape.baseRadius ?? width / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius }, + { label: "Base Radius", value: shape.baseRadius ?? baseWidth / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius }, { label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth }, { label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth }, { label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight }, @@ -356,9 +390,41 @@ export function ShapeInspector({ const gearHelixProperties = shape.kind === "gear" ? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label)) : []; + const taper = shapeTaperDimensions(shape); + const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [ + { + label: "Top Length", + value: taper.topDepth, + min: MIN_SHAPE_SIZE, + max: 480, + onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }), + }, + { + label: "Top Width", + value: taper.topWidth, + min: MIN_SHAPE_SIZE, + max: 480, + onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }), + }, + { + label: "Bottom Length", + value: taper.bottomDepth, + min: MIN_SHAPE_SIZE, + max: 480, + onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }), + }, + { + label: "Bottom Width", + value: taper.bottomWidth, + min: MIN_SHAPE_SIZE, + max: 480, + onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }), + }, + ]; const isSketchRevolve = shape.sketchOperation === "revolve" || Boolean(shape.sketchRevolve); const inspectorRef = useRef(null); const [propertiesOpen, setPropertiesOpen] = useState(true); + const [taperOpen, setTaperOpen] = useState(false); const [gearTeethOpen, setGearTeethOpen] = useState(true); const [gearHelixOpen, setGearHelixOpen] = useState(true); const [colorOpen, setColorOpen] = useState(false); @@ -513,6 +579,25 @@ export function ShapeInspector({
) : null}
+ {shape.kind !== "gear" ? ( +
+ + {taperOpen ? ( +
+ +
+ ) : null} +
+ ) : null} {shape.kind === "gear" ? (