commit fd5ca47813ca605c44e06d7c7706d722b419a74f Author: superGeometry Date: Thu Nov 5 01:58:43 2026 +0200 supergeometry.app A free, open-source CAD modeler that runs in the browser on any device. Co-Authored-By: Claude Opus 5.5 diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..e2c397c --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,17 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "supergeometry-dev", + "runtimeExecutable": "C:\\Program Files\\nodejs\\npm.cmd", + "runtimeArgs": ["run", "dev", "--", "--port", "5173", "--strictPort"], + "port": 5173 + }, + { + "name": "supergeometry-preview", + "runtimeExecutable": "C:\\Program Files\\nodejs\\npm.cmd", + "runtimeArgs": ["run", "preview", "--", "--port", "4173", "--strictPort"], + "port": 4173 + } + ] +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..08dd4d1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +*.log +.wrangler/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..70a8b8b --- /dev/null +++ b/LICENSE @@ -0,0 +1,18 @@ +supergeometry.app — free browser-based solid modeler +Copyright (C) 2026 supergeometry.app contributors + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +SPDX-License-Identifier: AGPL-3.0-or-later +(Full license text: https://www.gnu.org/licenses/agpl-3.0.txt) diff --git a/README.md b/README.md new file mode 100644 index 0000000..f5d4a92 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# supergeometry.app + +A free 3D solid modeler that runs in the browser on any device: desktop, iPad (with +Apple Pencil), Android tablets and phones. No account, no server, no subscription. + +The workflow is inspired by tablet-first CAD apps: you select something and the +tools for it appear; you drag a handle or type a number; every step lands in an +editable history. Geometry is computed by [OpenCascade](https://dev.opencascade.org/) +(via [replicad](https://replicad.xyz)) compiled to WebAssembly, running in a Web Worker. + +## Run it + +```bash +npm install +npm run dev +``` + +Open the printed URL. `--host` is on, so a tablet on the same Wi-Fi can open the +"Network" URL too. + +## Build & publish + +```bash +npm run build +``` + +`dist/` is a static site. Upload it anywhere: GitHub Pages, Cloudflare Pages, +Netlify, any web server. No backend needed. + +## Using it + +| | Mouse / keyboard | Touch / pen | +|---|---|---| +| Orbit | left-drag empty space | one-finger drag | +| Pan | right/middle-drag, shift+drag | two-finger drag | +| Zoom | wheel | pinch | +| Select | click (adds to selection) | tap (pen or finger) | +| Select body | double-click | double-tap | +| Clear selection | Esc / click empty | tap empty | + +While the pen touches the screen, fingers are ignored (palm rejection). + +Shortcuts: `S` sketch · in sketch `L` line, `R` rectangle, `C` circle, `G` polygon, +`V` select · `E` extrude · `F` fillet · `C` chamfer · `Del` delete · `Enter` done · +`Esc` cancel/exit · `Ctrl Z / Ctrl Y` undo/redo · `Ctrl S` save. + +## Docs + +- [docs/FEATURES.md](docs/FEATURES.md): what exists and what's planned +- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how it's built and why + +## License + +AGPL-3.0-or-later: anyone can use, study, change and host it, but modified +versions that are offered to the public must stay open source. +OpenCascade (via `replicad-opencascadejs`) is LGPL-2.1; replicad and three.js are MIT. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..48e26f7 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,104 @@ +# Architecture + +supergeometry.app is a static web app. There is no server: everything (geometry kernel +included) runs in the browser, so it can be hosted for free and works offline. + +``` + ┌──────────────── main thread ────────────────┐ ┌──────── Web Worker ────────┐ + │ UI (toolbar, history, hints) │ │ Kernel adapter │ + │ Tools (sketch, extrude, fillet, …) │ doc │ replicad + OpenCascade │ + │ Document store ── features[] (JSON) ──────┼───────▶│ (WebAssembly) │ + │ undo/redo, autosave │ │ Regenerate features[] │ + │ Viewport (three.js) ◀── meshes + topology ─┼────────┤ → bodies → meshes │ + │ Input (pointer events: pen/touch/mouse) │ │ feature cache │ + └─────────────────────────────────────────────┘ └────────────────────────────┘ +``` + +## Key decisions + +1. **The document is a list of features, not geometry.** `src/doc/types.ts`. + A project file is small JSON (`{ features: [...] }`). Geometry is always + *regenerated* from features, which is what makes history editable. Undo/redo + is just snapshots of that JSON. + +2. **The kernel runs in a Web Worker behind an interface.** `src/kernel/`. + The main thread never blocks on geometry. Only `worker.ts` knows about + replicad/OpenCascade; everything else talks to it through `protocol.ts`. + Swapping the kernel later means rewriting one file. + +3. **References to faces/edges are geometric, not index-based.** + The "topological naming problem": after you edit an early feature, face #7 + may not be face #7 anymore. Features therefore store a *signature* of the + face/edge they act on (center, normal, area / midpoint, direction, length), + and the kernel resolves it to the best-matching face/edge in the rebuilt + body (`resolveFace` / `resolveEdge` in `worker.ts`). This is simple and + survives most edits; it can be upgraded to a smarter naming scheme later + without changing the file format (the signature is just data). + +4. **Incremental regeneration.** The worker caches the bodies produced after + each feature, keyed by a hash of all features up to that point. Editing + feature *k* rebuilds only from *k* onwards. Live previews (dragging an + extrude arrow) only rebuild the last feature. + +5. **One input model for every device.** `src/view/input.ts` + - Pen or mouse-left: tool actions (tap = place/select, drag = handle). + - Touch: tap = place/select; one-finger drag on empty space = orbit; + two fingers = pan + pinch zoom. While a pen is touching the screen, + touches are ignored (palm rejection). + - Mouse: left-drag on empty = orbit, right/middle-drag = pan, wheel = zoom + to cursor. + +6. **Z-up, millimetres.** World units are mm, Z is up, sketches live on planes + `{ origin, xDir, normal }`. + +## Folder layout + +``` +src/ + main.ts, app.ts bootstrap; app state (selection, tools, section, pins), menus + settings.ts per-device preferences (snapping, grid, display, camera) + units.ts units + expression evaluation (variables, unit suffixes) + doc/ + types.ts feature & document types (the file format) + store.ts undo/redo, IndexedDB autosave, file migration + sketch/ pure 2D code, shared by UI and kernel + curves.ts entities → primitives (line/arc/ellipse/spline), evaluation + regions.ts planar arrangement → regions with holes (+ stable refs) + edit.ts trim, extend, offset, fillet, transforms, edge projection + text.ts text → outline curves (opentype.js + Roboto) + kernel/ + protocol.ts messages between main thread and worker + engine.ts feature replay on OpenCascade/replicad (testable in Node) + sketchGeom.ts regions → exact OpenCascade faces/wires + worker.ts Web Worker entry + client.ts promise-based client for the worker + view/ + viewport.ts three.js scene, display modes, section, picking + camera.ts orbit camera, ortho/perspective, plane-aligned views + grid.ts adaptive grid shader + viewcube.ts CSS-3D view cube + input.ts pointer-event router (pen/touch/mouse) + tools/ + tool.ts tool interface, selection → reference helpers + featureOp.ts base for operations: pick slots + values + preview + slots.ts axis / plane / direction / path / faces / profiles slots + ops.ts extrude, fillet, revolve, sweep, loft, shell, transforms, split, plane, axis + select.ts selection-driven menus + default handles + sketch.ts the sketch tool (all drawing & editing tools) + section.ts, measure.ts + io/insert.ts STEP/STL/OBJ/DXF/project import, images, variables + ui/ DOM chrome: tool column + flyouts, right column, panel, history +tests/ Node tests (npx tsx tests/.test.ts) +``` + +## Roadmap (order matters) + +1. ✅ Skeleton: viewport, input, kernel worker, document + history. +2. ✅ Sketch (line/rect/circle/polygon) → extrude → push/pull → fillet/chamfer → booleans. +3. Sketch constraints + driving dimensions with PlaneGCS (`@salusoft89/planegcs`). +4. Region detection (overlapping sketch shapes split into selectable regions). +5. Revolve, sweep, loft, shell, offset face. +6. Transform tools (gizmo), patterns, mirror. +7. Construction planes/axes, variables. +8. Import (STEP/STL/images), measure, section view. +9. Service worker (offline), file handling, iPad polish (Apple Pencil hover). diff --git a/docs/FEATURES.md b/docs/FEATURES.md new file mode 100644 index 0000000..7606b55 --- /dev/null +++ b/docs/FEATURES.md @@ -0,0 +1,78 @@ +# Feature catalog + +Functionality list. Implemented from scratch on OpenCascade. +Visualization, cloud sync, XR, sharing and accounts are out of scope. + +Legend: ✅ done · 🚧 partial · ⬜ planned + +## Sketch +| Feature | Status | +|---|---| +| Sketch → origin planes (XY/XZ/YZ), flat faces, construction planes, existing sketches | ✅ | +| Camera turns normal to the plane, orthographic; Line armed | ✅ | +| Line (chains; tap first point to close) | ✅ | +| Arc (2 endpoints + bend point) | ✅ | +| Spline (fit points / control points, open or closed) | ✅ | +| Rectangle (diagonal / center / 3 points) | ✅ | +| Circle, Ellipse, Polygon (n sides) | ✅ | +| Text (outline font → regions) | ✅ | +| Project body edges onto the sketch | ✅ | +| Offset edge | ✅ | +| Sketch fillet (corner of two lines) | ✅ | +| Move/Rotate, Scale, Pattern linear/circular, Rotate around point, Mirror (with copy) | ✅ | +| Trim, Extend, Delete | ✅ | +| Construction geometry toggle | ✅ | +| Overlapping shapes split into selectable regions (with holes) | ✅ | +| Live dimensions + type exact values while drawing | ✅ | +| Edit size of a selected curve (length, W/H, radius, sides…) | ✅ | +| Snapping: grid, guide points (end/mid/center), guide lines (H/V alignment), 3D points, distant edges | ✅ | +| Constraints (parallel, tangent, coincident…) + driving dimensions | ⬜ next (PlaneGCS) | + +## Selection-driven tools +| Selection | Tools | Status | +|---|---|---| +| Profile | Sketch, Move/Rotate, Scale Sketch, Patterns, **Extrude**, Axis ⊥, Plane offset, Text, Rotate, Mirror, Loft, Split, Revolve, Sweep, Offset Edge, Delete | ✅ | +| Profile | Fill, Project as Sketch/Edge, Wrap & Emboss | ⬜ | +| Face | Sketch, Move/Rotate, Scale, **Offset Face**, Fillet/Chamfer (face edges), Extrude, Shell, Axis ⊥, Plane offset, Patterns, Translate, Rotate, Mirror, Loft, Split, Revolve, Sweep, Project as Sketch, Offset Edge, Text, Delete | ✅ | +| Face | Align, Fill, Replace Face, Project as Edge | ⬜ | +| Edge | **Fillet**, Chamfer, Move/Rotate, Axis along edge, Plane ⊥ edge, Translate, Rotate | ✅ | +| Body | Move/Rotate, Scale, Translate, Patterns, Rotate, Mirror, Union/Subtract/Intersect, Split, Shell, Delete | ✅ | +| Plane / Axis | Sketch, Plane offset, Split, Delete | ✅ | + +## Top-level menus +| Feature | Status | +|---|---| +| Insert → Variable (usable in every field: `width*2`, `1in + 3mm`) | ✅ | +| Insert → Image (reference on a plane) | ✅ | +| Insert → File: STEP/STP, STL, OBJ, DXF; DWG explains how to convert | ✅ | +| Insert → Project (append another .super history) | ✅ | +| Construct → Offset plane, Midplane, Axis | ✅ | +| Construct → Plane through 3 points / on curve | ⬜ | +| Transform → Move/Rotate, Scale, Translate, Pattern, Rotate Around Axis, Mirror | ✅ | +| Transform → Align | ⬜ | +| Tools → every solid tool (waits for the right selection) | ✅ | +| Section View: plane/face, drag, flip, caps, stays on | ✅ | +| Section View: 2D section, section only | ⬜ | +| Measure: area, length, radius, size, volume, distance, min distance, angle, XYZ deltas, pins | ✅ | + +## Right column +| Feature | Status | +|---|---| +| Snapping toggles | ✅ | +| Units (mm/cm/m/in/ft), lock grid size, degree format | ✅ | +| Adaptive grid 0.001 mm … 1 000 000 mm, on the sketch plane while sketching | ✅ | +| Views: default, 6 presets, saved views; Appearance (animate, ortho, grid, axes, pins) | ✅ | +| Display modes: Shaded / X-Ray / Wireframe, edges, hidden edges | ✅ | +| Zebra / curvature analysis | ⬜ | +| Screenshot (PNG) | ✅ | +| View cube (click faces, drag to orbit, 90° roll) | ✅ | +| History (edit, suppress, delete any step) | ✅ | + +## Document & platform +| Feature | Status | +|---|---| +| Editable history for every feature type | ✅ | +| Undo / redo, autosave (IndexedDB), open/save `.super`, export STL/STEP | ✅ | +| Migration of older project files | ✅ | +| Any browser; pen/finger/mouse; palm rejection; phone layout | ✅ | +| Offline service worker | ⬜ | diff --git a/index.html b/index.html new file mode 100644 index 0000000..db68ed8 --- /dev/null +++ b/index.html @@ -0,0 +1,93 @@ + + + + + + + + + + + + + supergeometry.app + + + +
+ +
+
supergeometry.app
+ + + + +
+ + + + +
+ + + + + + + + + + +
+ + + + + + + + + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..06a35ae --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1837 @@ +{ + "name": "tessel", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tessel", + "version": "0.1.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@fontsource/roboto": "^5.3.0", + "opentype.js": "^2.0.0", + "replicad": "^1.2.0", + "replicad-opencascadejs": "^1.1.0", + "three": "^0.187.0" + }, + "devDependencies": { + "@types/opentype.js": "^1.3.10", + "@types/three": "^0.187.0", + "tsx": "^4.23.15", + "typescript": "^7.0.2", + "vite": "^8.3.5" + } + }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fontsource/roboto": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.3.0.tgz", + "integrity": "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", + "integrity": "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.16.tgz", + "integrity": "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.16.tgz", + "integrity": "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.16.tgz", + "integrity": "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.16.tgz", + "integrity": "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.16.tgz", + "integrity": "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.16.tgz", + "integrity": "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.16.tgz", + "integrity": "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.16.tgz", + "integrity": "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.16.tgz", + "integrity": "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.16.tgz", + "integrity": "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.16.tgz", + "integrity": "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.16.tgz", + "integrity": "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.16.tgz", + "integrity": "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.16.tgz", + "integrity": "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/opentype.js": { + "version": "1.3.10", + "resolved": "https://registry.npmjs.org/@types/opentype.js/-/opentype.js-1.3.10.tgz", + "integrity": "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ==", + "license": "MIT" + }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz", + "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/flatbush": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/flatbush/-/flatbush-4.7.0.tgz", + "integrity": "sha512-oFBkbYI3Rx6snZEBQOiJSaxt1MfZtbH2p862dRmIOOYRVxQWDyAn4oyKjoJv7TgmOft2yIavvooOU5itliagOw==", + "license": "ISC", + "dependencies": { + "flatqueue": "^3.1.0" + } + }, + "node_modules/flatqueue": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/flatqueue/-/flatqueue-3.1.0.tgz", + "integrity": "sha512-Ia4qIYrrsEqIRx3c3XhkT+QDLQuUV5ovsr6ah1rIgKT5wclhoGK3lAMS1bWRAWxlx7wtlTBpV7QXB5d9fOSRxA==", + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/opentype.js": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-2.0.0.tgz", + "integrity": "sha512-kCyjv6xdDY1W/jLWZ/L3QhhTlKUqDZMQ5+Jdlw12b3dXkKNpYBqqlMMj0YDQPShWFTMwgZI1hG14kN3XUDSg/A==", + "license": "MIT", + "bin": { + "ot": "bin/ot" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/replicad": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/replicad/-/replicad-1.2.0.tgz", + "integrity": "sha512-cbpI9pm+7Hz6AissKS62++GtkK8T+bPHNMIapnvMW6eM9bHtSM3NSUVpVUzrfogPJJyhq1bi8Zc3f0DSdRzXPQ==", + "license": "MIT", + "dependencies": { + "@types/opentype.js": "^1.3.10", + "flatbush": "^4.0.0", + "opentype.js": "2.0.0" + } + }, + "node_modules/replicad-opencascadejs": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/replicad-opencascadejs/-/replicad-opencascadejs-1.1.0.tgz", + "integrity": "sha512-s0KHR5V+ivsOE4nZXfuoW70lW0/rldkb3ZDY34LpXOQRFLQN5qVydQm3BRo7boZPdFkkAZBERJ+NzB0DYxrivw==", + "license": "LGPL-2.1-only" + }, + "node_modules/rolldown": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.16.tgz", + "integrity": "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.16", + "@rolldown/binding-android-arm64": "1.2.16", + "@rolldown/binding-darwin-arm64": "1.2.16", + "@rolldown/binding-darwin-x64": "1.2.16", + "@rolldown/binding-freebsd-x64": "1.2.16", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", + "@rolldown/binding-linux-arm64-gnu": "1.2.16", + "@rolldown/binding-linux-arm64-musl": "1.2.16", + "@rolldown/binding-linux-ppc64-gnu": "1.2.16", + "@rolldown/binding-linux-s390x-gnu": "1.2.16", + "@rolldown/binding-linux-x64-gnu": "1.2.16", + "@rolldown/binding-linux-x64-musl": "1.2.16", + "@rolldown/binding-openharmony-arm64": "1.2.16", + "@rolldown/binding-win32-arm64-msvc": "1.2.16", + "@rolldown/binding-win32-x64-msvc": "1.2.16" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", + "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..78adc31 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "supergeometry", + "private": true, + "version": "0.2.0", + "description": "Free, browser-based solid modeler for every device.", + "license": "AGPL-3.0-or-later", + "type": "module", + "scripts": { + "dev": "vite --host", + "build": "tsc --noEmit && vite build", + "preview": "vite preview --host", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@fontsource/roboto": "^5.3.0", + "opentype.js": "^2.0.0", + "replicad": "^1.2.0", + "replicad-opencascadejs": "^1.1.0", + "three": "^0.187.0" + }, + "devDependencies": { + "@types/opentype.js": "^1.3.10", + "@types/three": "^0.187.0", + "tsx": "^4.23.15", + "typescript": "^7.0.2", + "vite": "^8.3.5" + } +} diff --git a/public/_headers b/public/_headers new file mode 100644 index 0000000..7221468 --- /dev/null +++ b/public/_headers @@ -0,0 +1,18 @@ +# Cache rules for Cloudflare (copied into dist/ by the build). +# +# The page itself must always be fresh, so a push shows up right away. +# Everything in /assets/ has a content hash in its file name: a new build +# gets new names, so browsers may keep those files forever (fast repeat visits, +# and the 23 MB geometry engine is downloaded once). + +/ + Cache-Control: no-cache + +/index.html + Cache-Control: no-cache + +/manifest.webmanifest + Cache-Control: no-cache + +/assets/* + Cache-Control: public, max-age=31536000, immutable diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 0000000..e9ff6cf --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..707db1b --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,10 @@ +{ + "name": "supergeometry.app", + "short_name": "supergeometry", + "description": "Free 3D solid modeler for every device.", + "start_url": "./", + "display": "standalone", + "background_color": "#1f2125", + "theme_color": "#1f2125", + "icons": [{ "src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }] +} diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..b038f52 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,734 @@ +import { DocStore, parseProject } from "./doc/store"; +import type { EdgeFeature, ExtrudeFeature, ExtrudeSource, Feature, ImageFeature, LoftFeature, PinDef, PlaneDef, PlaneFeature, RevolveFeature, ShellFeature, SketchEntity, SketchFeature, SplitFeature, SweepFeature, TransformFeature, Units, Vec3 } from "./doc/types"; +import { emptyDoc } from "./doc/types"; +import { createVariable, editVariables, insertFile, insertImage } from "./io/insert"; +import { KernelClient } from "./kernel/client"; +import type { ExportFormat, RegenResult } from "./kernel/protocol"; +import { settings } from "./settings"; +import { PinLayer } from "./tools/annotate"; +import { MeasureTool } from "./tools/measure"; +import { ItemsPanel } from "./ui/items"; +import { AxisOp, EdgeOp, ExtrudeOp, ImageOp, LoftOp, MidplaneOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./tools/ops"; +import { toWorld, xDirFor } from "./geom"; +import { entityPolylines } from "./sketch/curves"; +import { FreeformTool } from "./tools/freeform"; +import { sectionPlane, SectionTool, type SectionState } from "./tools/section"; +import { SelectTool } from "./tools/select"; +import { SketchTool } from "./tools/sketch"; +import { bodiesOf, edgeRefOf, faceRefOf, sameSel, sourcesOf, type AppContext, type Sel, type Tool } from "./tools/tool"; +import { setupRightColumn } from "./ui/panels"; +import type { ToolItem } from "./ui/ui"; +import { UI } from "./ui/ui"; +import { setUnits, setVariables } from "./units"; +import { InputRouter } from "./view/input"; +import { ViewCube } from "./view/viewcube"; +import { PivotButton } from "./ui/pivot"; +import { Viewport } from "./view/viewport"; + +const SOON = "Coming soon"; + +export class App implements AppContext { + readonly store = new DocStore(); + readonly kernel = new KernelClient(); + readonly view: Viewport; + readonly ui = new UI(); + private input: InputRouter; + result: RegenResult | null = null; + selection: Sel[] = []; + section: SectionState | null = null; + isolated: string[] | null = null; + private hover: Sel | null = null; + private selectTool: SelectTool; + private tool: Tool; + private shownErrors = ""; + private pinLayer: PinLayer; + private items: ItemsPanel; + + constructor(canvas: HTMLCanvasElement) { + this.view = new Viewport(canvas); + this.input = new InputRouter(this.view); + this.selectTool = new SelectTool(this); + this.tool = this.selectTool; + this.input.handler = this.tool; + // A spinner while the geometry engine works on something that takes a moment. + const busy = document.createElement("div"); + busy.id = "busy"; + busy.hidden = true; + busy.innerHTML = `Working…`; + document.body.append(busy); + let busyTimer = 0; + this.kernel.onBusy = (on) => { + clearTimeout(busyTimer); + // Only for waits you would notice (not every quick preview while dragging). + if (on) busyTimer = window.setTimeout(() => (busy.hidden = false), 300); + else busy.hidden = true; + }; + document.getElementById("viewcube-host")!.append(new ViewCube(this.view).el, new PivotButton(this.view, (t) => this.ui.toast(t)).el); + setupRightColumn(this.ui, this.view, this.store, (u) => this.setUnits(u)); + this.pinLayer = new PinLayer(this.view); + // ƒx buttons on number fields create named variables. + this.ui.variableFactory = (current) => createVariable(this, current); + settings.onChange(() => this.showPins()); + this.items = new ItemsPanel(this.store, { + selectBody: (id) => (this.setTool(null), this.setSelection([{ kind: "body", body: id }])), + editSketch: (id) => this.setTool(new SketchTool(this, { sketchId: id })), + selectPlane: (id) => (this.setTool(null), this.setSelection([{ kind: "plane", id }])), + deleteBody: (id) => this.store.add({ ...this.store.newIdentity("delete"), type: "delete", bodies: [id] }), + deleteFeature: (id) => this.store.remove(id), + selectImage: (id) => (this.setTool(null), this.setSelection([{ kind: "image", id }])), + rename: async (id, current, isBody) => { + const v = await this.ui.dialog("Rename", [{ key: "name", label: "Name", value: current }]); + const name = v?.name.trim(); + if (!name) return; + if (isBody) this.store.commit((d) => (d.names = { ...(d.names ?? {}), [id]: name })); + else this.store.update(id, { name }); + }, + askName: async (title, current) => (await this.ui.dialog(title, [{ key: "name", label: "Name", value: current }]))?.name.trim() || null, + isolated: () => this.isolated, + }); + + this.store.onChange(() => this.docChanged()); + window.addEventListener("keydown", (e) => this.onKey(e)); + this.wireTopbar(); + this.tool.enter?.(); + + this.ui.setStatus("Loading geometry kernel…"); + Promise.all([this.kernel.ready, this.store.load()]) + .then(async () => { + this.ui.setStatus(null); + await this.regenerate(); + this.view.cam.fit(this.view.bounds(), false); + }) + .catch((err) => this.ui.setStatus(`Could not start the geometry kernel: ${err.message ?? err}`)); + } + + // ------------------------------------------------------------ state + + setSelection(sel: Sel[]): void { + this.selection = sel; + this.refreshHighlights(); + if (this.tool === this.selectTool) this.selectTool.refresh(); + } + + setHover(h: Sel | null): void { + if (h === this.hover || (h && this.hover && sameSel(h, this.hover))) return; + this.hover = h; + this.refreshHighlights(); + } + + setTool(tool: Tool | null): void { + const next = tool ?? this.selectTool; + const leavingOp = this.tool !== this.selectTool; + this.tool.exit?.(); + this.tool = next; + this.input.handler = next; + this.hover = null; + this.ui.closeFlyout(); + next.enter?.(); + // Leaving an operation drops its preview. + if (leavingOp && next === this.selectTool) void this.regenerate(); + else this.refreshSketches(); + this.renderHistory(); + } + + /** The last section used: Section View off and on again brings it back. */ + private lastSection: SectionState | null = null; + + /** + * Section View button: on → off (remembered); off → the remembered section, + * or a new one — straight from a selected flat face if there is one. + */ + private toggleSection(): void { + if (this.section) { + const keep = this.section; + if (this.tool instanceof SectionTool) this.setTool(null); + this.setSection(null); + this.lastSection = keep; + this.refreshTools(); + return; + } + const s = this.selection[0]; + const face = s?.kind === "face" ? this.view.body(s.body)?.faces[s.face] : undefined; + if (face?.plane) { + // Cut a hair inside the face so the face itself shows the cut. + this.setSection({ plane: face.plane, offset: -this.view.cam.worldPerPixel(this.view.height), flipped: false }); + } else if (this.lastSection) this.setSection(this.lastSection); + this.setTool(new SectionTool(this)); + } + + /** Re-draw the tool columns (e.g. after Section View changed). */ + private refreshTools(): void { + if (this.tool === this.selectTool) this.selectTool.refresh(); + else this.ui.setBottom(this.bottomTools()); + } + + setSection(s: SectionState | null): void { + this.section = s; + // A section on screen is the one to remember (a deleted one is forgotten). + if (s) this.lastSection = null; + this.view.setSection(s ? sectionPlane(s) : null); + } + + get pins(): PinDef[] { + return this.store.doc.pins; + } + + setPins(p: PinDef[]): void { + this.store.commit((d) => (d.pins = p)); + } + + addPin(pin: PinDef): void { + this.setPins([...this.pins, pin]); + this.ui.toast(`Pinned ${pin.text}`); + } + + private showPins(): void { + this.pinLayer.set(this.pins, settings.value.showPinned); + } + + isolate(bodies: string[] | null): void { + this.isolated = bodies?.length ? bodies : null; + this.applyVisibility(); + // Isolated bodies are all there is: sketches, planes, axes and images step out too. + this.refreshConstruction(); + this.refreshSketches(); + if (this.tool === this.selectTool) this.selectTool.refresh(); + this.items.render(this.result); + } + + /** Hidden (Items) + not isolated → invisible and unpickable. */ + private applyVisibility(): void { + const hidden = new Set(this.store.doc.hidden); + if (this.isolated) for (const b of this.result?.bodies ?? []) if (!this.isolated.includes(b.id)) hidden.add(b.id); + this.view.setHidden(hidden); + } + + sketchPlane(id: string): PlaneDef | undefined { + return this.result?.sketchPlanes[id] ?? this.store.find(id)?.plane; + } + + sketchCurves(id: string): SketchEntity[] { + return [...(this.store.find(id)?.entities ?? []), ...(this.result?.sketchBoundaries[id] ?? [])]; + } + + async preview(features: Feature[]): Promise { + const r = await this.kernel.regenerate(features); + if (r) this.apply(r, features); + return r; + } + + private docChanged(): void { + setUnits(this.store.doc.units); + setVariables(this.store.doc.variables); + this.ui.refreshRight(); + this.showPins(); + this.view.setBodyColors(this.store.doc.colors ?? {}); + void this.regenerate(); + } + + private setUnits(u: Units): void { + this.store.commit((d) => (d.units = u)); + } + + private async regenerate(): Promise { + const features = this.store.doc.features; + const r = await this.kernel.regenerate(features); + if (r) this.apply(r, features); + } + + private apply(r: RegenResult, features: readonly Feature[]): void { + this.result = r; + if (this.isolated) this.isolated = this.isolated.filter((id) => r.bodies.some((b) => b.id === id)); + if (!this.isolated?.length) this.isolated = null; + this.view.setBodies(r.bodies); + this.applyVisibility(); + this.refreshConstruction(features); + this.refreshSketches(features); + // Drop selections that point at geometry that no longer exists. + this.selection = this.selection.filter((s) => { + if (s.kind === "profile" || s.kind === "curve" || s.kind === "point") return !!this.store.find(s.sketch) || features.some((f) => f.id === s.sketch); + if (s.kind === "plane" || s.kind === "axis") return !!this.view.planeOf(s.id) || !!this.view.axisOf(s.id); + if (s.kind === "image") return features.some((f) => f.id === s.id); + const b = this.view.body(s.body); + if (!b) return false; + if (s.kind === "face") return s.face < b.faces.length; + if (s.kind === "edge") return s.edge < b.edges.length; + if (s.kind === "vertex") return !!this.view.vertexOf(s.body, s.vertex); + return true; + }); + this.refreshHighlights(); + this.tool.refresh?.(); + if (this.tool === this.selectTool) this.selectTool.refresh(); + this.renderHistory(); + this.items.render(r); + const open = this.openBodies(r); + this.ui.setWarning( + open.length + ? `⚠ ${open.length === 1 ? (this.store.doc.names?.[open[0].id] ?? open[0].name) : `${open.length} bodies`} not closed — ${open.reduce((s, b) => s + b.openEdges.length, 0)} open edge(s) shown in orange` + : this.store.problems[0] + ? `⚠ ${this.store.problems[0]}` + : null, + ); + const errs = r.errors.map((e) => e.featureId + e.message).join(); + if (errs && errs !== this.shownErrors && this.tool === this.selectTool) { + this.ui.toast(`${r.errors.length} step${r.errors.length > 1 ? "s" : ""} failed to rebuild — see History`, "error"); + } + this.shownErrors = errs; + } + + private refreshConstruction(features: readonly Feature[] = this.store.doc.features): void { + const r = this.result; + if (!r) return; + const hidden = new Set(this.store.doc.hidden); + const iso = !!this.isolated; + this.view.setConstruction(iso ? [] : r.planes.filter((p) => !hidden.has(p.id)), iso ? [] : r.axes.filter((a) => !hidden.has(a.id))); + this.view.setImages(iso ? [] : features.filter((f): f is ImageFeature => f.type === "image" && !f.suppressed && !hidden.has(f.id))); + } + + private refreshSketches(features: readonly Feature[] = this.store.doc.features): void { + const hidden = new Set(this.store.doc.hidden); + const sketches = features + .filter((f): f is SketchFeature => f.type === "sketch" && !f.suppressed && ((!hidden.has(f.id) && !this.isolated) || f.id === this.tool.activeSketch)) + .map((s) => ({ ...s, plane: this.result?.sketchPlanes[s.id] ?? s.plane, boundary: this.result?.sketchBoundaries[s.id] })); + this.view.setSketches(sketches, this.tool.activeSketch); + } + + private refreshHighlights(): void { + this.view.setHighlights(this.selection, this.hover); + } + + // ------------------------------------------------------------ history + + /** + * Bodies with open edges — except freeform surfaces that are meant to be + * open sheets (not thickened): those aren't a problem. + */ + private openBodies(r: RegenResult | null) { + return (r?.bodies ?? []).filter((b) => { + if (!b.openEdges?.length) return false; + const f = this.store.find(b.id.split(":")[0]); + return !(f?.type === "freeform" && f.surface && !f.thickness); + }); + } + + private renderHistory(): void { + // The rows are rebuilt: a hover on an old row is over. + this.view.setStepHover(null); + const warnings = new Map(); + for (const b of this.openBodies(this.result)) warnings.set(b.id.split(":")[0], `${b.name}: not closed — ${b.openEdges.length} open edge(s)`); + this.ui.renderHistory(this.store.doc.features, this.result?.errors ?? [], this.tool.editingId ?? this.tool.activeSketch ?? null, { + edit: (id) => this.editFeature(id), + hover: (id) => this.view.setStepHover(id ? this.stepTargets(id) : null), + toggle: (id) => { + const f = this.store.find(id); + if (f) this.store.update(id, { suppressed: !f.suppressed }); + }, + remove: (id) => { + if (this.tool !== this.selectTool) this.setTool(null); + this.store.remove(id); + }, + }, warnings); + } + + /** What a History step works on: its bodies (made or changed), sketches, and the edges it names. */ + private stepTargets(id: string): { bodies: string[]; lines: Vec3[][] } { + const f = this.store.find(id); + const bodies = new Set(); + const sketches = new Set(); + const edges: [Vec3, Vec3][] = []; + if (!f) return { bodies: [], lines: [] }; + if (f.type === "sketch") sketches.add(f.id); + // Bodies this step made (its own id, or copies "id:…"). + for (const b of this.result?.bodies ?? []) if (b.id === f.id || b.id.startsWith(`${f.id}:`)) bodies.add(b.id); + const walk = (v: unknown, key = ""): void => { + if (Array.isArray(v)) return v.forEach((x) => walk(x, key)); + if (!v || typeof v !== "object") { + if (typeof v === "string" && (key === "body" || key === "bodies" || key === "target")) bodies.add(v); + if (typeof v === "string" && key === "sketch") sketches.add(v); + return; + } + const o = v as Record; + // An edge reference: draw the edge itself. + if (Array.isArray(o.mid) && Array.isArray(o.dir) && typeof o.length === "number") { + const m = o.mid as Vec3; + const d = o.dir as Vec3; + const h = (o.length as number) / 2; + edges.push([[m[0] - d[0] * h, m[1] - d[1] * h, m[2] - d[2] * h], [m[0] + d[0] * h, m[1] + d[1] * h, m[2] + d[2] * h]]); + } + for (const [k, x] of Object.entries(o)) if (k !== "exprs") walk(x, k); + }; + walk(f); + // Only what's still there. + const have = new Set((this.result?.bodies ?? []).map((b) => b.id)); + // Sketch curves in 3D. + const lines: Vec3[][] = [...edges]; + for (const sid of sketches) { + const plane = this.sketchPlane(sid); + const sk = this.store.find(sid); + if (!plane || !sk) continue; + for (const e of sk.entities) for (const pl of entityPolylines(e)) lines.push(pl.map((uv) => toWorld(plane, uv))); + } + return { bodies: [...bodies].filter((b) => have.has(b)), lines }; + } + + private editFeature(id: string): void { + const f = this.store.find(id); + if (!f) return; + this.setSelection([]); + switch (f.type) { + case "sketch": + return this.setTool(new SketchTool(this, { sketchId: f.id })); + case "extrude": + return this.setTool(new ExtrudeOp(this, f.source, f as ExtrudeFeature)); + case "fillet": + case "chamfer": + return this.setTool(new EdgeOp(this, f.type, f.edges, f as EdgeFeature)); + case "revolve": + return this.setTool(new RevolveOp(this, f.source, f as RevolveFeature)); + case "sweep": + return this.setTool(new SweepOp(this, f.source, f as SweepFeature)); + case "loft": + return this.setTool(new LoftOp(this, f.sections, [], f as LoftFeature)); + case "shell": + return this.setTool(new ShellOp(this, f.body, f.faces, f as ShellFeature)); + case "split": + return this.setTool(new SplitOp(this, f.body, f as SplitFeature)); + case "plane": + return this.setTool(new PlaneOp(this, f.plane, f.face, f as PlaneFeature)); + case "transform": { + if (f.op.kind === "scale" || f.op.kind === "scaleXYZ") return this.setTool(new ScaleOp(this, f.op.kind === "scaleXYZ", f.bodies, f as TransformFeature)); + return this.setTool(new TransformOp(this, f.op.kind, f.bodies, f as TransformFeature)); + } + case "scaleFace": + return this.setTool(new ScaleFaceOp(this, f.face, { origin: f.face.center, normal: f.face.normal, xDir: f.u }, f)); + case "replaceFace": + return this.setTool(new ReplaceFaceOp(this, f.face, f)); + case "image": + return this.setTool(new ImageOp(this, f as ImageFeature)); + case "freeform": + return this.setTool(new FreeformTool(this, { feature: f })); + case "moveFace": { + const target = f.face ? { face: f.face, plane: { origin: f.face.center, normal: f.face.normal, xDir: xDirFor(f.face.normal) } } : f.edge ? { edge: f.edge } : f.vertex ? { vertex: f.vertex } : null; + if (target) return this.setTool(new MoveFaceOp(this, target, f)); + break; + } + default: + this.ui.toast(`${f.name} has no values to edit. You can suppress or delete it.`); + } + } + + // ------------------------------------------------------------ menus + + /** Nothing selected: the top-level menu (the left tool column). */ + mainTools(): ToolItem[] { + const wait = (label: string, accepts: Sel["kind"][], run: () => void) => () => { + this.selectTool.waitFor(label, accepts, run); + this.selectTool.refresh(); + }; + const bodies = () => bodiesOf(this.selection); + const transform = (kind: ConstructorParameters[1], label: string) => + wait(label, ["body", "face", "edge"], () => this.setTool(new TransformOp(this, kind, bodies()))); + const src = () => sourcesOf(this, this.selection)[0]; + return [ + { id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", run: () => this.setTool(new SketchTool(this)) }, + { + // Smooth shapes from a control cage. + id: "freeform", + label: "Freeform", + icon: "freeform", + children: (["box", "sphere", "cylinder", "plane"] as const).map((k) => ({ + id: `ff-${k}`, + label: { box: "Box", sphere: "Sphere", cylinder: "Cylinder", plane: "Surface (plane)" }[k], + icon: "freeform" as const, + run: () => this.setTool(new FreeformTool(this, { primitive: k })), + })), + }, + { + id: "insert", + label: "Insert", + icon: "insert", + children: [ + { id: "var", label: "Create Variable", icon: "variable", run: () => void createVariable(this) }, + { id: "vars", label: "Variables", icon: "variable", sub: `${this.store.doc.variables.length} defined`, run: () => void editVariables(this) }, + { id: "image", label: "Image", icon: "image", run: () => void insertImage(this) }, + { id: "file", label: "File", icon: "file", sub: "STEP, STL, OBJ, DXF, SVG", run: () => void insertFile(this) }, + { id: "project", label: "Project", icon: "file", sub: ".super", run: () => void insertFile(this) }, + ], + }, + { + id: "construct", + label: "Construct", + icon: "construct", + children: [ + { + id: "plane", + label: "Plane", + icon: "plane", + children: [ + { id: "offset", label: "Offset Plane", icon: "plane", run: () => this.setTool(new PlaneOp(this, null, undefined)) }, + { id: "mid", label: "Midplane", icon: "plane", run: () => this.setTool(new MidplaneOp(this)) }, + { id: "3pt", label: "Plane Through 3 Points", icon: "plane", disabled: true, why: SOON }, + { id: "curve", label: "Plane on Curve at Point", icon: "plane", disabled: true, why: SOON }, + ], + }, + { + id: "axis", + label: "Axis", + icon: "axis", + run: wait("Axis", ["face", "edge"], () => { + const s = this.selection[0]; + if (s.kind === "face") { + const f = this.view.body(s.body)?.faces[s.face]; + if (f) this.setTool(new AxisOp(this, f.center, f.normal)); + } else if (s.kind === "edge") { + const e = this.view.body(s.body)?.edges[s.edge]; + if (e) this.setTool(new AxisOp(this, e.start, e.dir)); + } + }), + }, + ], + }, + { + id: "transform", + label: "Transform", + icon: "transform", + children: [ + { id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", run: transform("move", "Move/Rotate") }, + { id: "scale", label: "Scale", icon: "scale", run: wait("Scale", ["body", "face", "edge"], () => this.setTool(new ScaleOp(this, false, bodies()))) }, + { id: "translate", label: "Translate", icon: "translate", run: transform("translate", "Translate") }, + { + id: "pattern", + label: "Pattern", + icon: "patternLinear", + children: [ + { id: "linear", label: "Linear", icon: "patternLinear", run: transform("linear", "Pattern – Linear") }, + { id: "circular", label: "Circular", icon: "patternCircular", run: transform("circular", "Pattern – Circular") }, + ], + }, + { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: transform("rotate", "Rotate Around Axis") }, + { id: "align", label: "Align", icon: "align", disabled: true, why: SOON }, + { id: "mirror", label: "Mirror", icon: "mirror", run: transform("mirror", "Mirror") }, + ], + }, + { + id: "tools", + label: "Tools", + icon: "tools", + children: [ + { id: "offsetFace", label: "Offset Face", icon: "offsetFace", run: wait("Offset Face", ["face"], () => src() && this.setTool(new ExtrudeOp(this, src()!))) }, + { id: "fillet", label: "Fillet", icon: "fillet", run: wait("Fillet", ["edge"], () => this.setTool(new EdgeOp(this, "fillet", this.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this, s)!] : []))))) }, + { id: "chamfer", label: "Chamfer", icon: "chamfer", run: wait("Chamfer", ["edge"], () => this.setTool(new EdgeOp(this, "chamfer", this.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this, s)!] : []))))) }, + { id: "extrude", label: "Extrude", icon: "extrude", run: wait("Extrude", ["profile", "face"], () => src() && this.setTool(new ExtrudeOp(this, src()!))) }, + { id: "shell", label: "Shell", icon: "shell", run: wait("Shell", ["face", "body"], () => { + const s = this.selection[0]; + const faces = this.selection.flatMap((x) => (x.kind === "face" ? [faceRefOf(this, x)!] : [])); + this.setTool(new ShellOp(this, bodiesOf([s])[0], faces)); + }) }, + { id: "loft", label: "Loft", icon: "loft", run: wait("Loft", ["profile", "face"], () => this.setTool(new LoftOp(this, sourcesOf(this, this.selection).flatMap((s): ExtrudeSource[] => (s.kind === "profile" ? s.regions.map((r) => ({ ...s, regions: [r] })) : [s])), this.selection))) }, + { id: "union", label: "Union", icon: "union", run: wait("Union (double-tap bodies)", ["body"], () => this.selectTool.refresh()) }, + { id: "subtract", label: "Subtract", icon: "subtract", run: wait("Subtract (double-tap bodies)", ["body"], () => this.selectTool.refresh()) }, + { id: "intersect", label: "Intersect", icon: "intersect", run: wait("Intersect (double-tap bodies)", ["body"], () => this.selectTool.refresh()) }, + { id: "split", label: "Split Body", icon: "split", run: wait("Split Body", ["body", "face"], () => this.setTool(new SplitOp(this, bodiesOf(this.selection)[0]))) }, + { id: "revolve", label: "Revolve", icon: "revolve", run: wait("Revolve", ["profile", "face"], () => src() && this.setTool(new RevolveOp(this, src()!))) }, + { id: "sweep", label: "Sweep", icon: "sweep", run: wait("Sweep", ["profile", "face"], () => src() && this.setTool(new SweepOp(this, src()!))) }, + { id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON }, + { id: "replace", label: "Replace Face", icon: "replaceFace", disabled: true, why: SOON }, + { id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON }, + { id: "wrap", label: "Wrap & Emboss", icon: "wrap", disabled: true, why: SOON }, + ], + }, + ]; + } + + bottomTools(): ToolItem[] { + return [ + { id: "section", label: "Section View", icon: "section", sub: this.section ? "On" : this.lastSection ? "Off · tap to show" : "Off", active: !!this.section, run: () => this.toggleSection() }, + { id: "measure", label: "Measure", icon: "measure", run: () => this.setTool(new MeasureTool(this)) }, + this.isolated + ? { id: "isolate", label: "Isolate", icon: "isolate", sub: "On — tap to show all", active: true, run: () => this.isolate(null) } + : { + id: "isolate", + label: "Isolate", + icon: "isolate", + sub: "Off", + disabled: !bodiesOf(this.selection).length, + why: "Select a body, face or edge to isolate", + run: () => this.isolate(bodiesOf(this.selection)), + }, + ]; + } + + private onKey(e: KeyboardEvent): void { + // Typing while holding a drag sets an exact value; Enter applies it and finishes. + // (Checked first: a panel field may still have focus from before the drag.) + if (this.input.dragging && this.tool.dragKey?.(e)) { + e.preventDefault(); + (document.activeElement as HTMLElement | null)?.blur?.(); + if (e.key === "Enter") this.input.endDrag(); + return; + } + const target = e.target as HTMLElement; + if (target.tagName === "INPUT" || target.tagName === "TEXTAREA") return; + const mod = e.ctrlKey || e.metaKey; + const k = e.key.toLowerCase(); + if (mod && k === "z") { + e.preventDefault(); + if (this.tool !== this.selectTool && !(this.tool instanceof SketchTool)) this.setTool(null); + if (e.shiftKey) this.store.redo(); + else this.store.undo(); + return; + } + if (mod && k === "y") { + e.preventDefault(); + this.store.redo(); + return; + } + if (mod && k === "s") { + e.preventDefault(); + this.save(); + return; + } + if (this.tool.key?.(e)) { + e.preventDefault(); + return; + } + if (mod) return; + if (this.tool !== this.selectTool) return; + if (k === "s" && !this.selection.length) this.setTool(new SketchTool(this)); + else if (k === "f" && !this.selection.length) this.fit(); + } + + private fit(): void { + this.view.cam.fit(this.view.bounds()); + } + + // ------------------------------------------------------------ files + + private wireTopbar(): void { + const on = (id: string, fn: () => void) => document.getElementById(id)!.addEventListener("click", fn); + const menu = document.getElementById("file-menu")!; + const more = document.getElementById("more-menu")!; + on("file-btn", () => ((more.hidden = true), menu.toggleAttribute("hidden"))); + on("more-btn", () => ((menu.hidden = true), more.toggleAttribute("hidden"))); + document.getElementById("m-version")!.textContent = `Version ${__APP_VERSION__}`; + const moreItem = (id: string, fn: () => void) => on(id, () => ((more.hidden = true), fn())); + // Fullscreen (the label follows the state; Esc also leaves it). + const fs = document.getElementById("m-fullscreen")!; + const doc = document as Document & { webkitFullscreenElement?: Element; webkitExitFullscreen?: () => void }; + const root = document.documentElement as HTMLElement & { webkitRequestFullscreen?: () => void }; + const isFull = () => !!(document.fullscreenElement ?? doc.webkitFullscreenElement); + const paint = () => (fs.firstChild!.textContent = isFull() ? "Exit fullscreen" : "Fullscreen"); + document.addEventListener("fullscreenchange", paint); + document.addEventListener("webkitfullscreenchange", paint); + moreItem("m-fullscreen", () => { + if (isFull()) return void (document.exitFullscreen?.() ?? doc.webkitExitFullscreen?.()); + if (root.requestFullscreen) void root.requestFullscreen().catch(() => this.ui.toast("This browser won't go fullscreen here")); + else if (root.webkitRequestFullscreen) root.webkitRequestFullscreen(); + // iPhone Safari has no fullscreen for pages: the Home Screen app is. + else this.ui.toast("Tip: Share → Add to Home Screen opens supergeometry.app full screen"); + }); + // Help and Tutorial: placeholders for now. + moreItem("m-help", () => {}); + moreItem("m-tutorial", () => {}); + // About → the project on GitHub; support → MakerWorld (new tab, no access back to this page). + const openTab = (url: string) => window.open(url, "_blank", "noopener"); + moreItem("m-about", () => openTab("https://github.com/superGeometry/supergeometry.app")); + moreItem("m-donate", () => openTab("https://makerworld.com/en/@supergeometry/upload")); + document.addEventListener("pointerdown", (e) => { + if (!(e.target as HTMLElement).closest("#file-menu, #file-btn")) menu.hidden = true; + if (!(e.target as HTMLElement).closest("#more-menu, #more-btn")) more.hidden = true; + }); + const item = (id: string, fn: () => void) => + on(id, () => { + menu.hidden = true; + fn(); + }); + item("m-new", () => { + if (this.store.features.length && !confirm("Start a new project? (You can undo this.)")) return; + this.setTool(null); + this.setSection(null); + this.store.replace(emptyDoc()); + }); + item("m-open", () => this.open()); + item("m-save", () => this.save()); + item("m-stl", () => void this.export("stl")); + item("m-step", () => void this.export("step")); + on("undo-btn", () => this.store.undo()); + on("redo-btn", () => this.store.redo()); + this.store.onChange(() => this.updateUndo()); + this.updateUndo(); + + // Project name: click and type; Enter or leaving the field renames. + const name = document.getElementById("project-name") as HTMLInputElement; + const show = () => { + if (document.activeElement !== name) name.value = this.store.doc.name; + document.title = `${this.store.doc.name} – supergeometry.app`; + }; + const rename = () => { + const v = name.value.trim(); + if (v && v !== this.store.doc.name) this.store.commit((d) => (d.name = v)); + else name.value = this.store.doc.name; + }; + name.addEventListener("change", rename); + name.addEventListener("keydown", (e) => { + e.stopPropagation(); + if (e.key === "Enter") name.blur(); + if (e.key === "Escape") (name.value = this.store.doc.name), name.blur(); + }); + name.addEventListener("focus", () => name.select()); + this.store.onChange(show); + show(); + } + + private updateUndo(): void { + (document.getElementById("undo-btn") as HTMLButtonElement).disabled = !this.store.canUndo; + (document.getElementById("redo-btn") as HTMLButtonElement).disabled = !this.store.canRedo; + } + + private save(): void { + download(new Blob([JSON.stringify(this.store.doc)], { type: "application/json" }), `${this.store.doc.name}.super`); + } + + private open(): void { + const input = document.createElement("input"); + input.type = "file"; + input.accept = ".super,.tessel,application/json"; + input.onchange = async () => { + const file = input.files?.[0]; + if (!file) return; + try { + const doc = parseProject(await file.text()); + doc.name = file.name.replace(/\.(super|tessel)$/i, ""); + this.setTool(null); + this.store.replace(doc); + setTimeout(() => this.fit(), 400); + } catch (err) { + this.ui.toast(`Could not open: ${(err as Error).message}`, "error"); + } + }; + input.click(); + } + + private async export(format: ExportFormat): Promise { + // Selected bodies win; otherwise what's isolated; otherwise everything. + const picked = bodiesOf(this.selection); + const bodies = picked.length ? picked : (this.isolated ?? []); + try { + this.ui.setStatus(`Exporting ${bodies.length ? `${bodies.length} bod${bodies.length > 1 ? "ies" : "y"} as ` : ""}${format.toUpperCase()}…`); + const blob = await this.kernel.export(this.store.doc.features, format, bodies.length ? bodies : undefined); + download(blob, `${this.store.doc.name}.${format === "step" ? "step" : "stl"}`); + } catch (err) { + this.ui.toast(`Export failed: ${(err as Error).message}`, "error"); + } finally { + this.ui.setStatus(null); + } + } +} + +function download(blob: Blob, name: string): void { + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = name; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); +} diff --git a/src/doc/params.ts b/src/doc/params.ts new file mode 100644 index 0000000..10ec2fb --- /dev/null +++ b/src/doc/params.ts @@ -0,0 +1,53 @@ +// Parametric document: evaluate expressions (variables) into feature values and +// re-solve sketch constraints, so the document's numbers are always consistent. + +import { solve } from "../sketch/constraints"; +import { evaluate, setVariables } from "../units"; +import type { Feature, ProjectDoc } from "./types"; + +/** Kind of value stored at a path (for units: lengths are mm, angles degrees). */ +export function kindOfPath(path: string): "length" | "angle" | "number" { + const last = path.split(".").pop() ?? ""; + if (/angle|rot/i.test(last) || /rotate/.test(path)) return "angle"; + if (/count|factor|sides|opacity/i.test(last)) return "number"; + return "length"; +} + +export function getPath(obj: unknown, path: string): unknown { + return path.split(".").reduce((o, k) => (o == null ? undefined : (o as Record)[k]), obj); +} + +export function setPath(obj: unknown, path: string, value: unknown): void { + const keys = path.split("."); + let o = obj as Record; + for (const k of keys.slice(0, -1)) { + if (o[k] == null) return; + o = o[k] as Record; + } + o[keys[keys.length - 1]] = value; +} + +/** Recompute every expression-driven value and re-solve constrained sketches (in place). */ +export function resolveDoc(doc: ProjectDoc): string[] { + const problems: string[] = []; + setVariables(doc.variables ?? []); + for (const f of doc.features as Feature[]) { + for (const [path, expr] of Object.entries(f.exprs ?? {})) { + const v = evaluate(expr, kindOfPath(path)); + if (v === null) problems.push(`${f.name}: "${expr}" can't be evaluated`); + else setPath(f, path, v); + } + if (f.type === "sketch" && f.constraints?.length) { + for (const c of f.constraints) { + if (!c.expr) continue; + const v = evaluate(c.expr, c.prop === "angle" ? "angle" : "length"); + if (v === null) problems.push(`${f.name}: "${c.expr}" can't be evaluated`); + else c.value = v; + } + const r = solve(f.entities, f.constraints); + f.entities = r.entities; + if (!r.ok) problems.push(`${f.name}: constraints can't all be met`); + } + } + return problems; +} diff --git a/src/doc/store.ts b/src/doc/store.ts new file mode 100644 index 0000000..2d96973 --- /dev/null +++ b/src/doc/store.ts @@ -0,0 +1,263 @@ +import { entityPolylines } from "../sketch/curves"; +import { arrangement, regionRef } from "../sketch/regions"; +import { pointInPoly } from "../sketch/curves"; +import { resolveDoc } from "./params"; +import { emptyDoc, type Feature, type FeatureType, type ProjectDoc, type SketchEntity } from "./types"; + +// Earlier builds were called "Tessel": their autosave is still picked up. +const LEGACY_KEY = "tessel.autosave.v1"; +const DB_NAME = "supergeometry"; +const OLD_DB_NAME = "tessel"; +const MAX_UNDO = 200; + +type Listener = () => void; + +const LABELS: Record = { + sketch: "Sketch", + extrude: "Extrude", + fillet: "Fillet", + chamfer: "Chamfer", + boolean: "Boolean", + delete: "Delete", + revolve: "Revolve", + sweep: "Sweep", + loft: "Loft", + shell: "Shell", + transform: "Transform", + split: "Split", + plane: "Plane", + axis: "Axis", + import: "Import", + image: "Image", + deleteGeom: "Delete", + moveFace: "Move Face", + freeform: "Freeform", + scaleFace: "Scale Face", + replaceFace: "Replace Face", +}; + +/** + * Holds the document and its undo/redo history. Every change goes through + * `commit`, which snapshots the previous state, so undo is exact. + */ +export class DocStore { + doc: ProjectDoc = emptyDoc(); + private undoStack: string[] = []; + private redoStack: string[] = []; + private listeners = new Set(); + private saveTimer = 0; + + /** Restore the autosaved project (IndexedDB, or the old localStorage slot). */ + async load(): Promise { + const saved = (await idbGet("autosave")) ?? (await idbGet("autosave", OLD_DB_NAME)) ?? legacyAutosave(); + if (saved) { + try { + this.doc = migrate(JSON.parse(saved)); + } catch { + // A broken autosave must never block the app. + } + } + this.listeners.forEach((fn) => fn()); + } + + onChange(fn: Listener): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + get features(): readonly Feature[] { + return this.doc.features; + } + + find(id: string): T | undefined { + return this.doc.features.find((f) => f.id === id) as T | undefined; + } + + /** Unique id + "Extrude 03"-style name for a new feature. */ + newIdentity(type: FeatureType, label = LABELS[type]): { id: string; name: string } { + const n = this.doc.features.filter((f) => f.name.startsWith(label + " ")).length + 1; + return { id: newId(type), name: `${label} ${String(n).padStart(2, "0")}` }; + } + + /** Expressions that couldn't be evaluated / sketches that can't be solved. */ + problems: string[] = []; + private transientBase: string | null = null; + + /** Apply a mutation as one undoable step. */ + commit(mutate: (doc: ProjectDoc) => void): void { + const before = this.transientBase ?? JSON.stringify(this.doc); + const next = JSON.parse(JSON.stringify(this.doc)) as ProjectDoc; + mutate(next); + this.problems = resolveDoc(next); + this.transientBase = null; + if (JSON.stringify(next) === before) return; + this.undoStack.push(before); + if (this.undoStack.length > MAX_UNDO) this.undoStack.shift(); + this.redoStack = []; + this.doc = next; + this.changed(); + } + + /** + * Live edits during a drag: update the document and notify, but leave undo + * alone; the next `commit` records everything since the drag began as one step. + */ + transient(mutate: (doc: ProjectDoc) => void): void { + this.transientBase ??= JSON.stringify(this.doc); + const next = JSON.parse(JSON.stringify(this.doc)) as ProjectDoc; + mutate(next); + this.doc = next; + this.listeners.forEach((fn) => fn()); + } + + add(feature: Feature): void { + this.commit((d) => d.features.push(feature)); + } + + update(id: string, patch: Partial): void { + this.commit((d) => { + const i = d.features.findIndex((f) => f.id === id); + if (i >= 0) d.features[i] = { ...d.features[i], ...patch } as Feature; + }); + } + + remove(id: string): void { + this.commit((d) => { + d.features = d.features.filter((f) => f.id !== id); + }); + } + + get canUndo(): boolean { + return this.undoStack.length > 0; + } + get canRedo(): boolean { + return this.redoStack.length > 0; + } + + undo(): void { + const prev = this.undoStack.pop(); + if (!prev) return; + this.redoStack.push(JSON.stringify(this.doc)); + this.doc = JSON.parse(prev); + this.changed(); + } + + redo(): void { + const next = this.redoStack.pop(); + if (!next) return; + this.undoStack.push(JSON.stringify(this.doc)); + this.doc = JSON.parse(next); + this.changed(); + } + + /** Replace the whole document (open file / new project). Undoable. */ + replace(doc: ProjectDoc): void { + this.commit((d) => { + // Drop every key first: anything the new document doesn't have (folders, + // colours, custom names…) must not linger from the old one. + for (const k of Object.keys(d)) delete (d as unknown as Record)[k]; + Object.assign(d, structuredClone(doc)); + }); + } + + private changed(): void { + this.listeners.forEach((fn) => fn()); + clearTimeout(this.saveTimer); + this.saveTimer = window.setTimeout(() => void idbSet("autosave", JSON.stringify(this.doc)), 400); + } +} + +export function newId(prefix: string): string { + return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; +} + +export function parseProject(text: string): ProjectDoc { + return migrate(JSON.parse(text)); +} + +// ------------------------------------------------------------------ migration + +/** Bring any saved project up to the current format. */ +export function migrate(raw: unknown): ProjectDoc { + const doc = raw as ProjectDoc & { version: number }; + // "tessel" is the format name of files saved before the rename. + if (!doc || (doc.format !== "super" && (doc.format as string) !== "tessel") || !Array.isArray(doc.features)) throw new Error("Not a supergeometry.app project file"); + if (doc.version === 2) return { ...emptyDoc(), ...doc, format: "super" }; + + // v1: rect {a, b}; extrude profiles referenced entity ids. + const sketches = new Map(); + for (const f of doc.features as unknown as Array>) { + if (f.type === "sketch") { + f.entities = f.entities.map((e: any) => { + if (e.kind === "rect" && e.a) { + return { id: e.id, kind: "rect", center: [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2], w: Math.abs(e.b[0] - e.a[0]), h: Math.abs(e.b[1] - e.a[1]), rotation: 0 }; + } + return e; + }); + sketches.set(f.id, f.entities); + } + if (f.type === "extrude" && f.source?.kind === "profile" && f.source.entities) { + const entities = sketches.get(f.source.sketch) ?? []; + f.source = { kind: "profile", sketch: f.source.sketch, regions: regionsForEntities(entities, f.source.entities) }; + } + } + return { ...emptyDoc(), ...doc, format: "super", version: 2 } as ProjectDoc; +} + +/** v1 profiles were "entity minus what's inside it": pick the regions that matches. */ +function regionsForEntities(entities: SketchEntity[], ids: string[]) { + const arr = arrangement(entities); + const outline = (e: SketchEntity) => entityPolylines(e).flat(); + const areaOf = (pts: [number, number][]) => { + let a = 0; + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += (pts[j][0] + pts[i][0]) * (pts[j][1] - pts[i][1]); + return Math.abs(a / 2); + }; + return arr.regions + .filter((r) => { + const owners = entities.filter((e) => pointInPoly(r.centroid, outline(e))); + if (!owners.length) return false; + const smallest = owners.reduce((a, b) => (areaOf(outline(a)) < areaOf(outline(b)) ? a : b)); + return ids.includes(smallest.id); + }) + .map(regionRef); +} + +// ---------------------------------------------------------------- IndexedDB + +function db(name = DB_NAME): Promise { + return new Promise((resolve) => { + try { + const req = indexedDB.open(name, 1); + req.onupgradeneeded = () => req.result.createObjectStore("kv"); + req.onsuccess = () => resolve(req.result); + req.onerror = () => resolve(null); + } catch { + resolve(null); + } + }); +} + +async function idbGet(key: string, dbName = DB_NAME): Promise { + const d = await db(dbName); + if (!d) return null; + return new Promise((resolve) => { + const req = d.transaction("kv").objectStore("kv").get(key); + req.onsuccess = () => resolve((req.result as string) ?? null); + req.onerror = () => resolve(null); + }); +} + +async function idbSet(key: string, value: string): Promise { + const d = await db(); + if (!d) return; + d.transaction("kv", "readwrite").objectStore("kv").put(value, key); +} + +function legacyAutosave(): string | null { + try { + return localStorage.getItem(LEGACY_KEY); + } catch { + return null; + } +} diff --git a/src/doc/types.ts b/src/doc/types.ts new file mode 100644 index 0000000..d906db5 --- /dev/null +++ b/src/doc/types.ts @@ -0,0 +1,408 @@ +// The project file format. Everything the user builds is a list of features; +// geometry is always regenerated from these, which is what makes history editable. + +export type Vec2 = [number, number]; +export type Vec3 = [number, number, number]; + +/** A plane in world space. xDir and normal are unit vectors, perpendicular. */ +export interface PlaneDef { + origin: Vec3; + xDir: Vec3; + normal: Vec3; +} + +interface EntityBase { + id: string; + /** Construction geometry is drawn dashed and never forms regions. */ + construction?: boolean; +} + +export type SketchEntity = EntityBase & + ( + | { kind: "line"; a: Vec2; b: Vec2 } + /** Arc through a (start), m (any point on it) and b (end). */ + | { kind: "arc"; a: Vec2; m: Vec2; b: Vec2 } + | { kind: "circle"; center: Vec2; radius: number } + | { kind: "ellipse"; center: Vec2; rx: number; ry: number; rotation: number } + | { kind: "spline"; points: Vec2[]; closed: boolean; mode: "fit" | "control" } + | { kind: "rect"; center: Vec2; w: number; h: number; rotation: number } + | { kind: "polygon"; center: Vec2; radius: number; sides: number; angle: number } + | { kind: "polyline"; points: Vec2[]; closed: boolean } + ); + +export type EntityKind = SketchEntity["kind"]; + +/** A sketch region, referenced by where it is rather than an index (see regions.ts). */ +export interface RegionRef { + c: Vec2; + a: number; +} + +/** + * Geometric signature of a face. Features store this instead of a face index so + * the reference survives edits to earlier features (see docs/ARCHITECTURE.md). + */ +export interface FaceRef { + body: string; + center: Vec3; + normal: Vec3; + area: number; +} + +export interface EdgeRef { + body: string; + mid: Vec3; + dir: Vec3; + length: number; +} + +export type ExtrudeSource = + | { kind: "profile"; sketch: string; regions: RegionRef[] } + | { kind: "face"; face: FaceRef }; + +interface FeatureBase { + id: string; + name: string; + /** Suppressed features are skipped during regeneration. */ + suppressed?: boolean; + /** + * Parametric values: field path → expression (e.g. "distance": "depth*2"). + * The number at that path is recomputed from the expression on every change. + */ + exprs?: Record; +} + +/** A point of a sketch entity: "a"/"b" ends, "m" arc mid, "c" centre, "k" i-th corner/point. */ +export interface PointRef { + e: string; + p: string; +} + +export type ConstraintType = + | "coincident" + | "horizontal" + | "vertical" + | "parallel" + | "perpendicular" + | "equal" + | "tangent" + | "concentric" + | "midpoint" + | "symmetric" + | "fix" + | "distance" + | "dim"; + +/** + * Sketch constraint. Geometry refs: `pts` (points) and `curves` (entity ids). + * Dimensions ("distance", "dim") carry a value, optionally driven by `expr`. + */ +export interface SketchConstraint { + id: string; + type: ConstraintType; + pts?: PointRef[]; + curves?: string[]; + /** dim: which size — length, radius, diameter, w, h, rx, ry, angle. */ + prop?: string; + value?: number; + expr?: string; + /** fix: where the point is held. */ + at?: Vec2; +} + +export interface SketchFeature extends FeatureBase { + type: "sketch"; + plane: PlaneDef; + /** When drawn on a body face, the sketch follows that face when it moves. */ + attachedTo?: FaceRef; + entities: SketchEntity[]; + constraints?: SketchConstraint[]; + /** What was done in the sketch, in order (shown under it in History); repeats are counted. */ + log?: { op: string; n: number }[]; +} + +export interface ExtrudeFeature extends FeatureBase { + type: "extrude"; + source: ExtrudeSource; + distance: number; + /** auto: join `target` when distance > 0, cut it when < 0; new body without a target. */ + mode: "auto" | "new" | "join" | "cut"; + target?: string; +} + +export interface EdgeFeature extends FeatureBase { + type: "fillet" | "chamfer"; + edges: EdgeRef[]; + radius: number; +} + +export interface BooleanFeature extends FeatureBase { + type: "boolean"; + op: "union" | "subtract" | "intersect"; + target: string; + tools: string[]; +} + +export interface DeleteFeature extends FeatureBase { + type: "delete"; + bodies: string[]; +} + +/** + * An axis in space. When `ref` is set the axis follows that sketch line or + * construction axis; origin/dir are the fallback (and the value at creation). + */ +export interface AxisRef { + origin: Vec3; + dir: Vec3; + ref?: { kind: "sketchLine"; sketch: string; entity: string } | { kind: "axis"; feature: string }; +} + +export type PathRef = { kind: "sketch"; sketch: string; entities: string[] } | { kind: "edges"; edges: EdgeRef[] }; + +type BodyMode = "auto" | "new" | "join" | "cut"; + +export interface RevolveFeature extends FeatureBase { + type: "revolve"; + source: ExtrudeSource; + axis: AxisRef; + /** Degrees (more than 360 winds round again: with travel, a thread or spring). */ + angle: number; + /** Distance moved along the axis over the whole angle (0: a plain revolve). */ + travel?: number; + mode: BodyMode; + target?: string; +} + +export interface SweepFeature extends FeatureBase { + type: "sweep"; + source: ExtrudeSource; + path: PathRef; + mode: BodyMode; + target?: string; +} + +export interface LoftFeature extends FeatureBase { + type: "loft"; + sections: ExtrudeSource[]; + ruled: boolean; + mode: BodyMode; + target?: string; +} + +export interface ShellFeature extends FeatureBase { + type: "shell"; + body: string; + /** Faces to open (removed); may be empty for a hollow closed body. */ + faces: FaceRef[]; + thickness: number; +} + +/** Move/rotate/scale/mirror/pattern bodies. With `copy`, the originals stay. */ +export interface TransformFeature extends FeatureBase { + type: "transform"; + bodies: string[]; + copy: boolean; + op: + | { kind: "move"; translate: Vec3; rotate?: { origin: Vec3; axis: Vec3; angle: number } } + | { kind: "scale"; center: Vec3; factor: number } + /** Different factors along X, Y and Z (freeform bodies: rebuilt from their cage). */ + | { kind: "scaleXYZ"; center: Vec3; factors: Vec3 } + | { kind: "mirror"; plane: PlaneDef } + | { kind: "linear"; dir: Vec3; spacing: number; count: number } + | { kind: "circular"; axis: AxisRef; count: number; angle: number }; +} + +export interface SplitFeature extends FeatureBase { + type: "split"; + body: string; + plane: PlaneDef; +} + +/** Construction plane. Optionally follows a face (offset along its normal). */ +export interface PlaneFeature extends FeatureBase { + type: "plane"; + plane: PlaneDef; + face?: FaceRef; + offset: number; +} + +export interface AxisFeature extends FeatureBase { + type: "axis"; + origin: Vec3; + dir: Vec3; +} + +/** A body imported from a file. The file content travels inside the project. */ +export interface ImportFeature extends FeatureBase { + type: "import"; + format: "step" | "stl"; + fileName: string; + /** Base64 of the file. */ + data: string; +} + +/** A reference image placed on a plane (for tracing). */ +export interface ImageFeature extends FeatureBase { + type: "image"; + plane: PlaneDef; + /** data: URL */ + src: string; + width: number; + height: number; + opacity: number; +} + +/** + * Remove faces/edges/vertices from a body; the surrounding faces extend to + * close the gap (fillets, chamfers, holes, imprinted edges). + */ +export interface DeleteGeomFeature extends FeatureBase { + type: "deleteGeom"; + body: string; + faces: FaceRef[]; + edges: EdgeRef[]; + vertices: Vec3[]; +} + +/** + * Move/tilt one flat face — or one straight edge between two flat faces (both + * faces turn to follow it). The neighbouring faces extend or trim. + */ +export interface MoveFaceFeature extends FeatureBase { + type: "moveFace"; + face?: FaceRef; + edge?: EdgeRef; + /** One corner moves; the flat faces meeting there turn about their far edge to follow. */ + vertex?: { body: string; at: Vec3 }; + translate: Vec3; + rotate?: { origin: Vec3; axis: Vec3; angle: number }; +} + +/** + * A freeform body: a quad control cage whose smooth subdivision surface + * becomes the body (a solid when the cage is closed, a surface otherwise). + */ +export interface FreeformFeature extends FeatureBase { + type: "freeform"; + cage: { verts: Vec3[]; faces: [number, number, number, number][] }; + /** Made as an open surface on purpose (a sheet): no "not closed" warning. */ + surface?: boolean; + /** An open freeform becomes a solid this thick (0 / missing: stays a surface). */ + thickness?: number; + /** Which way the thickness goes from the surface (its normal side is "up"). */ + thickSide?: "up" | "down" | "both"; +} + +/** + * Scale one flat face within its own plane (factors along its u and v axes); + * the flat faces around it tilt to follow its edges. + */ +export interface ScaleFaceFeature extends FeatureBase { + type: "scaleFace"; + face: FaceRef; + /** The face's in-plane u axis (v = normal × u). */ + u: Vec3; + factors: [number, number]; +} + +/** Move a flat face onto another plane / flat face (the neighbours follow). */ +export interface ReplaceFaceFeature extends FeatureBase { + type: "replaceFace"; + face: FaceRef; + plane: PlaneDef; + /** Follow this face when it moves (else `plane` is used as is). */ + target?: FaceRef; +} + +export type Feature = + | ScaleFaceFeature + | ReplaceFaceFeature + | FreeformFeature + | DeleteGeomFeature + | MoveFaceFeature + | SketchFeature + | ExtrudeFeature + | EdgeFeature + | BooleanFeature + | DeleteFeature + | RevolveFeature + | SweepFeature + | LoftFeature + | ShellFeature + | TransformFeature + | SplitFeature + | PlaneFeature + | AxisFeature + | ImportFeature + | ImageFeature; +export type FeatureType = Feature["type"]; + +export interface Variable { + name: string; + /** Expression; may reference other variables. */ + expr: string; +} + +export interface SavedView { + name: string; + target: Vec3; + distance: number; + azimuth: number; + elevation: number; + ortho: boolean; +} + +export type Units = "mm" | "cm" | "m" | "in" | "ft"; + +/** A measurement pinned in 3D: a label, optionally with a dimension line a→b. */ +export interface PinDef { + text: string; + at: Vec3; + a?: Vec3; + b?: Vec3; +} + +export interface ProjectDoc { + format: "super"; + version: 2; + name: string; + features: Feature[]; + variables: Variable[]; + views: SavedView[]; + units: Units; + /** Ids of bodies / sketches / planes hidden from the Items panel. */ + hidden: string[]; + pins: PinDef[]; + /** Custom names for bodies (by body id), set from Items. */ + names: Record; + /** Items folders: any bodies / sketches / planes / images, grouped. */ + folders?: ItemFolder[]; + /** Body colours (by body id), "#rrggbb"; missing = the default grey. */ + colors?: Record; +} + +/** The body colours offered by the Color tool (first = default). */ +export const BODY_COLORS: { name: string; hex: string }[] = [ + { name: "Grey", hex: "#b9bec7" }, + { name: "Red", hex: "#e05a4f" }, + { name: "Orange", hex: "#f08c3a" }, + { name: "Yellow", hex: "#e8c547" }, + { name: "Green", hex: "#5fbf5a" }, + { name: "Teal", hex: "#3fb6a8" }, + { name: "Blue", hex: "#4f8ce0" }, + { name: "Violet", hex: "#8a6be0" }, + { name: "Pink", hex: "#e06bb5" }, + { name: "Brown", hex: "#9a7454" }, +]; + +export interface ItemFolder { + id: string; + name: string; + /** Body ids and feature ids. */ + items: string[]; +} + +export function emptyDoc(): ProjectDoc { + return { format: "super", version: 2, name: "Untitled", features: [], variables: [], views: [], units: "mm", hidden: [], pins: [], names: {} }; +} diff --git a/src/env.d.ts b/src/env.d.ts new file mode 100644 index 0000000..7a36973 --- /dev/null +++ b/src/env.d.ts @@ -0,0 +1,2 @@ +/** The package.json version, filled in by Vite (see vite.config.ts). */ +declare const __APP_VERSION__: string; diff --git a/src/freeform/bspline.ts b/src/freeform/bspline.ts new file mode 100644 index 0000000..bcdf9fa --- /dev/null +++ b/src/freeform/bspline.ts @@ -0,0 +1,98 @@ +// Uniform cubic B-spline interpolation of a point grid (pure math). +// +// Every freeform patch is an equal-sized grid with the same uniform +// parameters, so the knots and the interpolation matrix are shared — and two +// patches with the same border points get exactly the same border curve. + +import type { Vec3 } from "../doc/types"; + +export interface CubicKnots { + /** Distinct knot values and their multiplicities (clamped: ends ×4). */ + knots: number[]; + mults: number[]; + /** The full knot vector, for evaluation. */ + full: number[]; +} + +/** Knots for interpolating m+1 points at uniform parameters (de Boor averaging). */ +export function cubicKnots(count: number): CubicKnots { + const m = count - 1; + const t = Array.from({ length: count }, (_, k) => k / m); + const inner: number[] = []; + for (let j = 1; j <= m - 3; j++) inner.push((t[j] + t[j + 1] + t[j + 2]) / 3); + const full = [0, 0, 0, 0, ...inner, 1, 1, 1, 1]; + return { knots: [0, ...inner, 1], mults: [4, ...inner.map(() => 1), 4], full }; +} + +/** Cox–de Boor: value of basis function i (degree 3) at u. */ +function basis(full: number[], i: number, u: number): number { + const N = (j: number, p: number): number => { + if (p === 0) { + // The last span includes its right end. + const last = u === 1 && full[j + 1] === 1 && full[j] < 1; + return (full[j] <= u && u < full[j + 1]) || last ? 1 : 0; + } + const a = full[j + p] - full[j]; + const b = full[j + p + 1] - full[j + 1]; + return (a ? ((u - full[j]) / a) * N(j, p - 1) : 0) + (b ? ((full[j + p + 1] - u) / b) * N(j + 1, p - 1) : 0); + }; + return N(i, 3); +} + +/** Inverse of the interpolation matrix A[k][i] = N_i(t_k) for `count` uniform points. */ +const inverses = new Map(); +function interpolationInverse(count: number): number[][] { + let inv = inverses.get(count); + if (inv) return inv; + const { full } = cubicKnots(count); + const A = Array.from({ length: count }, (_, k) => Array.from({ length: count }, (_, i) => basis(full, i, k / (count - 1)))); + inv = invert(A); + inverses.set(count, inv); + return inv; +} + +function invert(A: number[][]): number[][] { + const n = A.length; + const M = A.map((row, i) => [...row, ...Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))]); + for (let c = 0; c < n; c++) { + let p = c; + for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r; + [M[c], M[p]] = [M[p], M[c]]; + const d = M[c][c]; + for (let k = 0; k < 2 * n; k++) M[c][k] /= d; + for (let r = 0; r < n; r++) { + if (r === c) continue; + const f = M[r][c]; + if (f) for (let k = 0; k < 2 * n; k++) M[r][k] -= f * M[c][k]; + } + } + return M.map((row) => row.slice(n)); +} + +/** Poles of the bicubic surface through grid[i][j] (both directions uniform). */ +export function interpolateGrid(grid: Vec3[][]): Vec3[][] { + const rows = grid.length; + const cols = grid[0].length; + const iu = interpolationInverse(rows); + const iv = interpolationInverse(cols); + // Rows first (along j), then columns (along i). + const R = grid.map((row) => iv.map((w) => w.reduce((s, x, k) => [s[0] + x * row[k][0], s[1] + x * row[k][1], s[2] + x * row[k][2]] as Vec3, [0, 0, 0] as Vec3))); + return iu.map((w) => Array.from({ length: cols }, (_, j) => w.reduce((s, x, k) => [s[0] + x * R[k][j][0], s[1] + x * R[k][j][1], s[2] + x * R[k][j][2]] as Vec3, [0, 0, 0] as Vec3))); +} + +/** Evaluate the interpolating surface (for tests): S(u, v). */ +export function evalSurface(poles: Vec3[][], u: number, v: number): Vec3 { + const ku = cubicKnots(poles.length).full; + const kv = cubicKnots(poles[0].length).full; + const out: Vec3 = [0, 0, 0]; + for (let i = 0; i < poles.length; i++) { + const bu = basis(ku, i, u); + if (!bu) continue; + for (let j = 0; j < poles[0].length; j++) { + const w = bu * basis(kv, j, v); + if (!w) continue; + for (let q = 0; q < 3; q++) out[q] += w * poles[i][j][q]; + } + } + return out; +} diff --git a/src/freeform/cage.ts b/src/freeform/cage.ts new file mode 100644 index 0000000..327d990 --- /dev/null +++ b/src/freeform/cage.ts @@ -0,0 +1,372 @@ +// Freeform control cages and Catmull–Clark subdivision (pure math, no OCCT). +// +// A cage is a quad mesh. The smooth shape is its subdivision surface; after a +// few levels every cage quad has become an n×n grid of points ("patch") that +// the kernel interpolates with one B-spline surface. Neighbouring patches share +// their boundary points exactly, so the surfaces sew into a clean shell/solid. + +import type { Vec3 } from "../doc/types"; + +export interface Cage { + verts: Vec3[]; + /** Quads, as vertex indices in order around the face. */ + faces: [number, number, number, number][]; +} + +export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere"; + +// ------------------------------------------------------------- primitives + +/** Box of w×d×h centred on the XY plane at `at` (bottom on z = at.z), n faces per side. */ +export function boxCage(size: Vec3 = [40, 40, 40], n = 2, at: Vec3 = [0, 0, 0]): Cage { + const pts = new Map(); + const verts: Vec3[] = []; + const faces: Cage["faces"] = []; + const vid = (p: Vec3) => { + const k = p.map((x) => Math.round(x * 1e6)).join(","); + let i = pts.get(k); + if (i === undefined) { + i = verts.push(p) - 1; + pts.set(k, i); + } + return i; + }; + // Unit cube [-1, 1]³; each side is an n×n grid, wound so normals point out. + const sides: { o: Vec3; u: Vec3; v: Vec3 }[] = [ + { o: [-1, -1, 1], u: [2, 0, 0], v: [0, 2, 0] }, // top + { o: [-1, 1, -1], u: [2, 0, 0], v: [0, -2, 0] }, // bottom + { o: [-1, -1, -1], u: [2, 0, 0], v: [0, 0, 2] }, // front (−y) + { o: [1, 1, -1], u: [-2, 0, 0], v: [0, 0, 2] }, // back (+y) + { o: [1, -1, -1], u: [0, 2, 0], v: [0, 0, 2] }, // right (+x) + { o: [-1, 1, -1], u: [0, -2, 0], v: [0, 0, 2] }, // left (−x) + ]; + const place = (q: Vec3): Vec3 => [at[0] + (q[0] * size[0]) / 2, at[1] + (q[1] * size[1]) / 2, at[2] + ((q[2] + 1) * size[2]) / 2]; + for (const { o, u, v } of sides) { + const P = (i: number, j: number): Vec3 => [o[0] + (u[0] * i + v[0] * j) / n, o[1] + (u[1] * i + v[1] * j) / n, o[2] + (u[2] * i + v[2] * j) / n]; + for (let i = 0; i < n; i++) + for (let j = 0; j < n; j++) faces.push([vid(P(i, j)), vid(P(i + 1, j)), vid(P(i + 1, j + 1)), vid(P(i, j + 1))]); + } + // Positions are placed after de-duplication (keys use the unit cube). + return { verts: verts.map(place), faces }; +} + +/** Sphere of diameter `d`: a box cage pushed onto a sphere. */ +export function sphereCage(d = 40, at: Vec3 = [0, 0, 0]): Cage { + const c = boxCage([2, 2, 2], 2, [0, 0, -1]); + // A cage a little bigger than the sphere: subdivision shrinks it. + const r = (d / 2) * 1.22; + return { faces: c.faces, verts: c.verts.map((p) => { + const l = Math.hypot(...p) || 1; + return [at[0] + (p[0] / l) * r, at[1] + (p[1] / l) * r, at[2] + d / 2 + (p[2] / l) * r]; + }) }; +} + +/** Flat n×n sheet of w×d on the XY plane at `at` (an open surface). */ +export function planeCage(size: [number, number] = [40, 40], n = 4, at: Vec3 = [0, 0, 0]): Cage { + const verts: Vec3[] = []; + for (let j = 0; j <= n; j++) for (let i = 0; i <= n; i++) verts.push([at[0] + (i / n - 0.5) * size[0], at[1] + (j / n - 0.5) * size[1], at[2]]); + const id = (i: number, j: number) => j * (n + 1) + i; + const faces: Cage["faces"] = []; + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]); + return { verts, faces }; +} + +/** Cylinder of diameter d and height h standing on `at`: 8 around, `rows` up, quad caps. */ +export function cylinderCage(d = 40, h = 40, rows = 2, at: Vec3 = [0, 0, 0]): Cage { + const N = 8; + const r = (d / 2) * 1.08; + const verts: Vec3[] = []; + const ring = (k: number) => k * N; + for (let k = 0; k <= rows; k++) + for (let i = 0; i < N; i++) { + const a = (i / N) * Math.PI * 2; + verts.push([at[0] + Math.cos(a) * r, at[1] + Math.sin(a) * r, at[2] + (k / rows) * h]); + } + const faces: Cage["faces"] = []; + for (let k = 0; k < rows; k++) + for (let i = 0; i < N; i++) { + const a = ring(k) + i; + const b = ring(k) + ((i + 1) % N); + faces.push([a, b, b + N, a + N]); + } + // Caps: a 2×2 grid of quads each, closing the bottom and top rings. + capGrid(verts, faces, ring(0), N, at[2], false, at); + capGrid(verts, faces, ring(rows), N, at[2] + h, true, at); + return { verts, faces }; +} + +/** + * Close an 8-point rim with a 2×2 grid of quads: its corners are rim points + * 1, 3, 5, 7, its edge midpoints rim 0, 2, 4, 6, and a new centre point. + */ +function capGrid(verts: Vec3[], faces: Cage["faces"], R: number, N: number, z: number, up: boolean, at: Vec3): void { + const c = verts.push([at[0], at[1], z]) - 1; + // 2×2 grid: corner points = rim 1, 3, 5, 7; edge mid points = rim 0, 2, 4, 6; centre = c. + for (let q = 0; q < 4; q++) { + const mid0 = R + ((2 * q) % N); + const corner = R + ((2 * q + 1) % N); + const mid1 = R + ((2 * q + 2) % N); + const quad: [number, number, number, number] = [c, mid0, corner, mid1]; + faces.push(up ? quad : [quad[0], quad[3], quad[2], quad[1]]); + } +} + +export function primitiveCage(kind: CagePrimitive, at: Vec3 = [0, 0, 0]): Cage { + switch (kind) { + case "box": + return boxCage([40, 40, 40], 2, at); + case "plane": + return planeCage([60, 60], 4, at); + case "cylinder": + return cylinderCage(40, 40, 2, at); + case "sphere": + return sphereCage(40, at); + } +} + +// ------------------------------------------------------------ subdivision + +/** The subdivided surface: points, and per cage face the (n+1)×(n+1) grid of point indices. */ +export interface Subdivided { + points: Vec3[]; + /** grids[f][i][j]: point index; i runs from the face's corner 0 towards 1, j towards 3. */ + grids: number[][][]; + /** Size of each grid side in cells (2^levels). */ + n: number; +} + +const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; +const mul3 = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k]; + +/** Catmull–Clark, `levels` times. Boundary edges (open sheets) stay sharp B-spline curves. */ +export function subdivide(cage: Cage, levels = 3): Subdivided { + let points = cage.verts.map((p) => [...p] as Vec3); + let grids = cage.faces.map((f) => [ + [f[0], f[3]], + [f[1], f[2]], + ]); + let n = 1; + for (let lvl = 0; lvl < levels; lvl++) { + // Every current cell (quad) and the edges between grid points. + const quads: number[][] = []; + for (const g of grids) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]); + const ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`); + const edgeFaces = new Map(); + quads.forEach((q, qi) => { + for (let k = 0; k < 4; k++) { + const key = ekey(q[k], q[(k + 1) % 4]); + const l = edgeFaces.get(key); + if (l) l.push(qi); + else edgeFaces.set(key, [qi]); + } + }); + const facePt = quads.map((q) => mul3(q.reduce((s, i) => add3(s, points[i]), [0, 0, 0] as Vec3), 0.25)); + // New point list: old vertices (moved), then edge points, then face points. + const next: Vec3[] = []; + const edgeIdx = new Map(); + const faceIdx: number[] = []; + // Edge points. + const edgePos = new Map(); + for (const [key, fs] of edgeFaces) { + const [a, b] = key.split(",").map(Number); + const mid = mul3(add3(points[a], points[b]), 0.5); + edgePos.set(key, fs.length === 2 ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid); + } + // Vertex points. + const vFaces = new Map(); + const vEdges = new Map(); + quads.forEach((q, qi) => q.forEach((v) => vFaces.set(v, [...(vFaces.get(v) ?? []), qi]))); + for (const key of edgeFaces.keys()) for (const v of key.split(",").map(Number)) vEdges.set(v, [...(vEdges.get(v) ?? []), key]); + const moved = points.map((p, v) => { + const es = vEdges.get(v); + const fs = vFaces.get(v); + if (!es || !fs) return p; + const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1); + if (boundary.length >= 2) { + // Boundary: a cubic B-spline along the border; a corner (two faces meet at an angle) stays put. + if (fs.length === 1) return p; + const others = boundary.slice(0, 2).map((k) => { + const [a, b] = k.split(",").map(Number); + return points[a === v ? b : a]; + }); + return add3(mul3(p, 0.75), mul3(add3(others[0], others[1]), 0.125)); + } + const m = es.length; + const F = mul3(fs.reduce((s, f) => add3(s, facePt[f]), [0, 0, 0] as Vec3), 1 / fs.length); + const R = mul3(es.reduce((s, k) => { + const [a, b] = k.split(",").map(Number); + return add3(s, mul3(add3(points[a], points[b]), 0.5)); + }, [0, 0, 0] as Vec3), 1 / m); + return mul3(add3(add3(F, mul3(R, 2)), mul3(p, m - 3)), 1 / m); + }); + next.push(...moved); + for (const [key, pos] of edgePos) edgeIdx.set(key, next.push(pos) - 1); + for (const fp of facePt) faceIdx.push(next.push(fp) - 1); + // New grids, twice as fine. + let qi = 0; + const N = 2 * n; + grids = grids.map((g) => { + const ng: number[][] = Array.from({ length: N + 1 }, () => new Array(N + 1)); + for (let i = 0; i <= n; i++) for (let j = 0; j <= n; j++) ng[2 * i][2 * j] = g[i][j]; + for (let i = 0; i <= n; i++) for (let j = 0; j < n; j++) ng[2 * i][2 * j + 1] = edgeIdx.get(ekey(g[i][j], g[i][j + 1]))!; + for (let i = 0; i < n; i++) for (let j = 0; j <= n; j++) ng[2 * i + 1][2 * j] = edgeIdx.get(ekey(g[i][j], g[i + 1][j]))!; + for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) ng[2 * i + 1][2 * j + 1] = faceIdx[qi++]; + return ng; + }); + points = next; + n = N; + } + return { points, grids, n }; +} + +/** Triangles of the subdivided surface (for the live preview). */ +export function previewMesh(s: Subdivided): { positions: Float32Array; normals: Float32Array; indices: Uint32Array } { + const positions = new Float32Array(s.points.flat()); + const idx: number[] = []; + for (const g of s.grids) + for (let i = 0; i < s.n; i++) + for (let j = 0; j < s.n; j++) { + const a = g[i][j]; + const b = g[i + 1][j]; + const c = g[i + 1][j + 1]; + const d = g[i][j + 1]; + idx.push(a, b, c, a, c, d); + } + // Smooth normals: area-weighted average of the triangles around each point. + const nrm = new Float32Array(positions.length); + for (let t = 0; t < idx.length; t += 3) { + const [a, b, c] = [idx[t], idx[t + 1], idx[t + 2]].map((k) => s.points[k]); + const u: Vec3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + const v: Vec3 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + const n: Vec3 = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + for (const k of [idx[t], idx[t + 1], idx[t + 2]]) for (let q = 0; q < 3; q++) nrm[k * 3 + q] += n[q]; + } + for (let k = 0; k < nrm.length; k += 3) { + const l = Math.hypot(nrm[k], nrm[k + 1], nrm[k + 2]) || 1; + nrm[k] /= l; + nrm[k + 1] /= l; + nrm[k + 2] /= l; + } + return { positions, normals: nrm, indices: new Uint32Array(idx) }; +} + +/** Cage edges (each once), for drawing and picking. */ +export function cageEdges(cage: Cage): [number, number][] { + const seen = new Set(); + const out: [number, number][] = []; + for (const f of cage.faces) + for (let k = 0; k < 4; k++) { + const a = f[k]; + const b = f[(k + 1) % 4]; + const key = a < b ? `${a},${b}` : `${b},${a}`; + if (!seen.has(key)) (seen.add(key), out.push([a, b])); + } + return out; +} + +/** Does every cage edge have two faces (a closed shape → a solid)? */ +export function isClosed(cage: Cage): boolean { + const count = new Map(); + for (const f of cage.faces) + for (let k = 0; k < 4; k++) { + const a = f[k]; + const b = f[(k + 1) % 4]; + const key = a < b ? `${a},${b}` : `${b},${a}`; + count.set(key, (count.get(key) ?? 0) + 1); + } + return [...count.values()].every((c) => c === 2); +} + +// ------------------------------------------------------------ cage editing + +/** Remove faces; points no face uses any more go too (indices are renumbered). */ +export function deleteFaces(cage: Cage, faces: number[]): Cage { + const drop = new Set(faces); + return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)) }); +} + +function compact(cage: Cage): Cage { + const used = [...new Set(cage.faces.flat())].sort((a, b) => a - b); + const map = new Map(used.map((v, i) => [v, i])); + return { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) }; +} + +const ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`); + +/** Edges used by only one face (the rim of a sheet or of a hole), as that face winds them. */ +export function boundaryEdges(cage: Cage): [number, number][] { + const count = new Map(); + for (const f of cage.faces) + for (let k = 0; k < 4; k++) { + const a = f[k]; + const b = f[(k + 1) % 4]; + const e = count.get(ekey(a, b)); + if (e) e.n++; + else count.set(ekey(a, b), { n: 1, dir: [a, b] }); + } + return [...count.values()].filter((e) => e.n === 1).map((e) => e.dir); +} + +/** + * Closed loops among the chosen boundary edges, each walked the opposite way + * to the face it borders — the winding a new face filling it needs. + */ +export function holeLoops(cage: Cage, chosen: Set): number[][] { + const edges = boundaryEdges(cage).filter(([a, b]) => chosen.has(ekey(a, b))); + // Reverse each: from b to a. + const next = new Map(); + for (const [a, b] of edges) next.set(b, a); + const loops: number[][] = []; + const seen = new Set(); + for (const start of next.keys()) { + if (seen.has(start)) continue; + const loop: number[] = []; + let v: number | undefined = start; + while (v !== undefined && !seen.has(v)) { + seen.add(v); + loop.push(v); + v = next.get(v); + } + if (v === start && loop.length >= 3) loops.push(loop); + } + return loops; +} + +/** Fill a hole: 4 edges → one quad; an even number above 4 → quads around a new centre point. */ +export function fillLoop(cage: Cage, loop: number[]): Cage | null { + const n = loop.length; + if (n === 4) return { verts: cage.verts, faces: [...cage.faces, [loop[0], loop[1], loop[2], loop[3]]] }; + if (n < 4 || n % 2) return null; + const c = loop.reduce((s, v) => [s[0] + cage.verts[v][0] / n, s[1] + cage.verts[v][1] / n, s[2] + cage.verts[v][2] / n] as Vec3, [0, 0, 0] as Vec3); + const ci = cage.verts.length; + const faces = [...cage.faces]; + for (let k = 0; k < n; k += 2) faces.push([ci, loop[k], loop[(k + 1) % n], loop[(k + 2) % n]]); + return { verts: [...cage.verts, c], faces }; +} + +/** + * Bridge two holes with the same number of edges by a ring of quads (e.g. a + * tunnel between a front and a back opening). The second loop is turned and + * rotated to line up with the first so the quads don't twist. + */ +export function bridgeLoops(cage: Cage, a: number[], b: number[]): Cage | null { + const n = a.length; + if (b.length !== n) return null; + // Facing holes run opposite ways round: walk b backwards, then pick the start that lines up best. + const rb = [...b].reverse(); + const d = (p: number, q: number) => Math.hypot(...[0, 1, 2].map((k) => cage.verts[p][k] - cage.verts[q][k])); + let best = 0; + let bestCost = Infinity; + for (let s = 0; s < n; s++) { + let cost = 0; + for (let i = 0; i < n; i++) cost += d(a[i], rb[(i + s) % n]); + if (cost < bestCost) (bestCost = cost), (best = s); + } + const B = (i: number) => rb[(i + best) % n]; + const faces = [...cage.faces]; + // Each a-edge (a_i → a_i+1) already runs as the new face needs it; the b side runs back. + for (let i = 0; i < n; i++) faces.push([a[i], a[(i + 1) % n], B(i + 1), B(i)]); + return { verts: cage.verts, faces }; +} + +export { ekey as cageEdgeKey }; diff --git a/src/geom.ts b/src/geom.ts new file mode 100644 index 0000000..228eff2 --- /dev/null +++ b/src/geom.ts @@ -0,0 +1,54 @@ +// Small vector / plane helpers shared by the UI and the kernel worker. + +import type { PlaneDef, Vec2, Vec3 } from "./doc/types"; + +export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; +export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +export const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s]; +export const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +export const cross = (a: Vec3, b: Vec3): Vec3 => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +export const len = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); +export const norm = (a: Vec3): Vec3 => { + const l = len(a) || 1; + return [a[0] / l, a[1] / l, a[2] / l]; +}; +export const dist = (a: Vec3, b: Vec3): number => len(sub(a, b)); + +export const GROUND: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +export const FRONT: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] }; +export const RIGHT: PlaneDef = { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] }; + +export function planeY(p: PlaneDef): Vec3 { + return cross(p.normal, p.xDir); +} + +export function toWorld(p: PlaneDef, uv: Vec2): Vec3 { + const y = planeY(p); + return add(p.origin, add(scale(p.xDir, uv[0]), scale(y, uv[1]))); +} + +export function toPlane(p: PlaneDef, w: Vec3): Vec2 { + const d = sub(w, p.origin); + return [dot(d, p.xDir), dot(d, planeY(p))]; +} + +/** Pick a stable in-plane x direction for a face normal (world X if possible). */ +export function xDirFor(normal: Vec3): Vec3 { + const ref: Vec3 = Math.abs(normal[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1]; + // Project ref onto the plane; for vertical faces this gives a horizontal x axis. + const x = Math.abs(normal[2]) > 0.9 ? ref : cross(ref, normal); + const proj = sub(x, scale(normal, dot(x, normal))); + return norm(proj); +} + + +/** Round to a "nice" step (0.1, 0.5, 1, 5, 10, …) close to `raw`. */ +export function niceStep(raw: number): number { + const p = Math.pow(10, Math.floor(Math.log10(raw))); + const m = raw / p; + return (m < 2 ? 1 : m < 7 ? 5 : 10) * p; +} diff --git a/src/io/insert.ts b/src/io/insert.ts new file mode 100644 index 0000000..09138a7 --- /dev/null +++ b/src/io/insert.ts @@ -0,0 +1,250 @@ +// Insert menu: files (STEP/STL/OBJ/DXF/projects), images, variables. + +import { migrate, newId } from "../doc/store"; +import type { Feature, ImageFeature, PlaneDef, SketchEntity, SketchFeature } from "../doc/types"; +import { GROUND } from "../geom"; +import { uid } from "../sketch/edit"; +import type { AppContext } from "../tools/tool"; +import { evaluate, fmtLen, setVariables } from "../units"; +import { parseSVG } from "./svg"; + +export function pickFile(accept: string): Promise { + return new Promise((resolve) => { + const input = document.createElement("input"); + input.type = "file"; + input.accept = accept; + input.onchange = () => resolve(input.files?.[0] ?? null); + input.click(); + }); +} + +export async function insertFile(app: AppContext): Promise { + const file = await pickFile(".step,.stp,.stl,.obj,.dxf,.svg,.dwg,.super,.tessel"); + if (!file) return; + const ext = file.name.split(".").pop()!.toLowerCase(); + try { + if (ext === "dwg") { + app.ui.toast("DWG is a closed format. Save it as DXF (e.g. with LibreCAD or ODA File Converter, both free) and insert that.", "error"); + return; + } + if (ext === "dxf") { + const entities = parseDXF(await file.text()); + if (!entities.length) throw new Error("No lines, arcs, circles, polylines or splines found"); + const sk: SketchFeature = { ...app.store.newIdentity("sketch", file.name.replace(/\.dxf$/i, "")), type: "sketch", plane: GROUND, entities }; + app.store.add(sk); + app.ui.toast(`Inserted ${entities.length} curves as a sketch on the ground plane`); + return; + } + if (ext === "svg") { + // Outlines (logos, laser/vinyl cut files…) as a sketch, centred on the origin. + const { entities, size } = parseSVG(await file.text()); + const sk: SketchFeature = { ...app.store.newIdentity("sketch", file.name.replace(/\.svg$/i, "")), type: "sketch", plane: GROUND, entities }; + app.store.add(sk); + app.ui.toast(`Inserted ${entities.length} curves (${fmtLen(size[0])} × ${fmtLen(size[1])}) as a sketch on the ground plane`); + return; + } + if (ext === "super" || ext === "tessel") { + insertProject(app, migrate(JSON.parse(await file.text())).features, file.name); + return; + } + let bytes: Uint8Array = new Uint8Array(await file.arrayBuffer()); + let format: "step" | "stl" = ext === "stl" ? "stl" : "step"; + if (ext === "obj") { + bytes = objToStl(new TextDecoder().decode(bytes)); + format = "stl"; + } + app.ui.setStatus(`Importing ${file.name}…`); + app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes) }); + app.ui.setStatus(null); + } catch (err) { + app.ui.setStatus(null); + app.ui.toast(`Could not insert ${file.name}: ${(err as Error).message}`, "error"); + } +} + +/** Append another project's history (ids are renamed so nothing collides). */ +function insertProject(app: AppContext, features: Feature[], name: string): void { + const map = new Map(features.map((f) => [f.id, newId(f.type)])); + let json = JSON.stringify(features); + for (const [from, to] of map) json = json.split(`"${from}"`).join(`"${to}"`); + const renamed = JSON.parse(json) as Feature[]; + app.store.commit((d) => d.features.push(...renamed)); + app.ui.toast(`Inserted ${renamed.length} steps from ${name}`); +} + +export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Promise { + const file = await pickFile("image/*"); + if (!file) return; + const src = await new Promise((resolve) => { + const r = new FileReader(); + r.onload = () => resolve(r.result as string); + r.readAsDataURL(file); + }); + const img = new Image(); + img.src = src; + await img.decode(); + const width = 100; + const f: ImageFeature = { ...app.store.newIdentity("image"), type: "image", plane, src, width, height: (width * img.height) / img.width, opacity: 0.8 }; + app.store.add(f); + app.ui.toast("Image placed on the ground plane (100 mm wide). Edit it from History."); +} + +/** Create a named variable (optionally from a field's current value); returns its name. */ +export async function createVariable(app: AppContext, value = ""): Promise { + const list = app.store.doc.variables; + const note = list.length ? `Existing: ${list.map((v) => `${v.name} = ${v.expr}`).join(", ")}` : "Use variables in any field, e.g. width*2 or wall + 1mm."; + const v = await app.ui.dialog("Create Variable", [ + { key: "name", label: "Name", value: "", placeholder: "width" }, + { key: "expr", label: "Value", value, placeholder: "40 or 1.5in or depth/2" }, + ], note); + if (!v) return null; + const name = v.name.trim(); + if (!/^[a-z_][a-z0-9_]*$/i.test(name) || /^(mm|cm|m|in|ft)$/i.test(name)) { + app.ui.toast("Names use letters, digits and _ (not starting with a digit, not a unit)", "error"); + return null; + } + const next = [...list.filter((x) => x.name !== name), { name, expr: v.expr.trim() || "0" }]; + setVariables(next); + if (evaluate(v.expr || "0") === null) { + setVariables(list); + app.ui.toast(`"${v.expr}" isn't a valid value`, "error"); + return null; + } + app.store.commit((d) => (d.variables = next)); + app.ui.toast(`${name} = ${v.expr}`); + return name; +} + +/** Edit every variable at once; changing one rebuilds everything that uses it. */ +export async function editVariables(app: AppContext): Promise { + const list = app.store.doc.variables; + if (!list.length) return void createVariable(app); + const v = await app.ui.dialog( + "Variables", + list.map((x) => ({ key: x.name, label: x.name, value: x.expr })), + "Change a value to update every feature that uses it. Clear a value to delete the variable.", + ); + if (!v) return; + const next = list.filter((x) => v[x.name]?.trim()).map((x) => ({ name: x.name, expr: v[x.name].trim() })); + setVariables(next); + const bad = next.find((x) => evaluate(x.expr) === null); + if (bad) { + setVariables(list); + return app.ui.toast(`"${bad.expr}" isn't a valid value for ${bad.name}`, "error"); + } + app.store.commit((d) => (d.variables = next)); +} + +export async function editImage(app: AppContext, f: ImageFeature): Promise { + const v = await app.ui.dialog("Image", [ + { key: "width", label: "Width (mm)", value: String(f.width) }, + { key: "opacity", label: "Opacity (0–1)", value: String(f.opacity) }, + ]); + if (!v) return; + const width = Number(v.width) || f.width; + app.store.update(f.id, { width, height: (f.height * width) / f.width, opacity: Math.min(1, Math.max(0.05, Number(v.opacity) || f.opacity)) }); +} + +// -------------------------------------------------------------------- DXF + +/** Minimal ASCII DXF reader: LINE, CIRCLE, ARC, LWPOLYLINE, POLYLINE, SPLINE, ELLIPSE. */ +export function parseDXF(text: string): SketchEntity[] { + const lines = text.split(/\r?\n/); + const pairs: [number, string][] = []; + for (let i = 0; i + 1 < lines.length; i += 2) pairs.push([parseInt(lines[i].trim(), 10), lines[i + 1].trim()]); + const start = pairs.findIndex((p, i) => p[0] === 2 && p[1] === "ENTITIES" && pairs[i - 1]?.[1] === "SECTION"); + if (start < 0) return []; + const out: SketchEntity[] = []; + let i = start + 1; + const num = (codes: [number, string][], c: number, d = 0) => Number(codes.find((x) => x[0] === c)?.[1] ?? d); + while (i < pairs.length && !(pairs[i][0] === 0 && pairs[i][1] === "ENDSEC")) { + if (pairs[i][0] !== 0) { + i++; + continue; + } + const type = pairs[i][1]; + const codes: [number, string][] = []; + i++; + while (i < pairs.length && pairs[i][0] !== 0) codes.push(pairs[i++]); + if (type === "LINE") out.push({ id: uid(), kind: "line", a: [num(codes, 10), num(codes, 20)], b: [num(codes, 11), num(codes, 21)] }); + else if (type === "CIRCLE") out.push({ id: uid(), kind: "circle", center: [num(codes, 10), num(codes, 20)], radius: num(codes, 40) }); + else if (type === "ARC") { + const c: [number, number] = [num(codes, 10), num(codes, 20)]; + const r = num(codes, 40); + const a0 = (num(codes, 50) * Math.PI) / 180; + let a1 = (num(codes, 51) * Math.PI) / 180; + if (a1 <= a0) a1 += Math.PI * 2; + const at = (t: number): [number, number] => [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)]; + out.push({ id: uid(), kind: "arc", a: at(a0), m: at((a0 + a1) / 2), b: at(a1) }); + } else if (type === "ELLIPSE") { + const mx = num(codes, 11); + const my = num(codes, 21); + const rx = Math.hypot(mx, my); + out.push({ id: uid(), kind: "ellipse", center: [num(codes, 10), num(codes, 20)], rx, ry: rx * num(codes, 40, 1), rotation: Math.atan2(my, mx) }); + } else if (type === "LWPOLYLINE") { + const xs = codes.filter((c) => c[0] === 10).map((c) => Number(c[1])); + const ys = codes.filter((c) => c[0] === 20).map((c) => Number(c[1])); + const closed = (num(codes, 70) & 1) === 1; + const pts = xs.map((x, k) => [x, ys[k]] as [number, number]); + if (pts.length >= 2) out.push({ id: uid(), kind: "polyline", points: pts, closed }); + } else if (type === "SPLINE") { + const fx = codes.filter((c) => c[0] === 11).map((c) => Number(c[1])); + const fy = codes.filter((c) => c[0] === 21).map((c) => Number(c[1])); + const cx = codes.filter((c) => c[0] === 10).map((c) => Number(c[1])); + const cy = codes.filter((c) => c[0] === 20).map((c) => Number(c[1])); + const closed = (num(codes, 70) & 1) === 1; + if (fx.length >= 2) out.push({ id: uid(), kind: "spline", points: fx.map((x, k) => [x, fy[k]]), closed, mode: "fit" }); + else if (cx.length >= 2) out.push({ id: uid(), kind: "spline", points: cx.map((x, k) => [x, cy[k]]), closed, mode: "control" }); + } else if (type === "POLYLINE") { + const closed = (num(codes, 70) & 1) === 1; + const pts: [number, number][] = []; + while (i < pairs.length && pairs[i][1] === "VERTEX") { + i++; + const v: [number, string][] = []; + while (i < pairs.length && pairs[i][0] !== 0) v.push(pairs[i++]); + pts.push([num(v, 10), num(v, 20)]); + } + if (pts.length >= 2) out.push({ id: uid(), kind: "polyline", points: pts, closed }); + } + } + return out; +} + +// -------------------------------------------------------------------- OBJ + +/** OBJ (triangles/polygons) → binary STL, so the kernel can import it. */ +export function objToStl(text: string): Uint8Array { + const v: number[][] = []; + const tris: number[][] = []; + for (const line of text.split(/\r?\n/)) { + const p = line.trim().split(/\s+/); + if (p[0] === "v") v.push([Number(p[1]), Number(p[2]), Number(p[3])]); + else if (p[0] === "f") { + const idx = p.slice(1).map((s) => { + const n = parseInt(s.split("/")[0], 10); + return n < 0 ? v.length + n : n - 1; + }); + for (let k = 1; k + 1 < idx.length; k++) tris.push([idx[0], idx[k], idx[k + 1]]); + } + } + if (!tris.length) throw new Error("No faces in the OBJ file"); + const buf = new ArrayBuffer(84 + tris.length * 50); + const dv = new DataView(buf); + dv.setUint32(80, tris.length, true); + let o = 84; + for (const t of tris) { + o += 12; // normal left as zero; readers recompute it + for (const k of t) { + for (let c = 0; c < 3; c++) dv.setFloat32(o + c * 4, v[k][c], true); + o += 12; + } + o += 2; + } + return new Uint8Array(buf); +} + +function toBase64(bytes: Uint8Array): string { + let s = ""; + for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(s); +} diff --git a/src/io/svg.ts b/src/io/svg.ts new file mode 100644 index 0000000..93bbc95 --- /dev/null +++ b/src/io/svg.ts @@ -0,0 +1,408 @@ +// SVG → sketch curves. Lines stay lines, circular arcs become arcs, circles / +// ellipses / rectangles become those shapes (when not skewed), and Bézier or +// elliptical curves become splines through points on them. Units follow the +// SVG's width/viewBox (mm, cm, in, pt, px); y is flipped so up stays up, and +// the drawing is centred on the sketch origin. +// +// Self-contained (no DOM), so it works in tests and workers alike. + +import type { SketchEntity, Vec2 } from "../doc/types"; +import { uid } from "../sketch/edit"; + +/** 2D affine map [a b c d e f]: x' = a x + c y + e, y' = b x + d y + f (SVG's matrix order). */ +type M = [number, number, number, number, number, number]; +const I: M = [1, 0, 0, 1, 0, 0]; +const mul = (p: M, q: M): M => [p[0] * q[0] + p[2] * q[1], p[1] * q[0] + p[3] * q[1], p[0] * q[2] + p[2] * q[3], p[1] * q[2] + p[3] * q[3], p[0] * q[4] + p[2] * q[5] + p[4], p[1] * q[4] + p[3] * q[5] + p[5]]; +const ap = (m: M, [x, y]: Vec2): Vec2 => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]; + +/** Rotation + uniform scale (+ mirror) only: circles stay circles. */ +function similarity(m: M): { k: number; rot: number } | null { + const k1 = Math.hypot(m[0], m[1]); + const k2 = Math.hypot(m[2], m[3]); + const dotp = m[0] * m[2] + m[1] * m[3]; + if (Math.abs(k1 - k2) > 1e-9 * Math.max(k1, k2) || Math.abs(dotp) > 1e-9 * k1 * k2) return null; + return { k: k1, rot: Math.atan2(m[1], m[0]) }; +} + +function parseTransform(s: string | undefined): M { + let m = I; + if (!s) return m; + for (const [, fn, args] of s.matchAll(/(\w+)\s*\(([^)]*)\)/g)) { + const v = nums(args); + let t: M = I; + switch (fn) { + case "matrix": + if (v.length === 6) t = v as M; + break; + case "translate": + t = [1, 0, 0, 1, v[0] ?? 0, v[1] ?? 0]; + break; + case "scale": + t = [v[0] ?? 1, 0, 0, v[1] ?? v[0] ?? 1, 0, 0]; + break; + case "rotate": { + const a = ((v[0] ?? 0) * Math.PI) / 180; + const r: M = [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]; + t = v.length >= 3 ? mul(mul([1, 0, 0, 1, v[1], v[2]], r), [1, 0, 0, 1, -v[1], -v[2]]) : r; + break; + } + case "skewX": + t = [1, 0, Math.tan(((v[0] ?? 0) * Math.PI) / 180), 1, 0, 0]; + break; + case "skewY": + t = [1, Math.tan(((v[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0]; + break; + } + m = mul(m, t); + } + return m; +} + +function nums(s: string): number[] { + return (s.match(/[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? []).map(Number); +} + +// ---------------------------------------------------------------- XML + +interface El { + name: string; + attrs: Record; + children: El[]; +} + +/** Tiny XML reader: elements and attributes only (enough for SVG geometry). */ +function parseXml(text: string): El { + const root: El = { name: "#root", attrs: {}, children: [] }; + const stack = [root]; + const src = text.replace(//g, "").replace(//g, "").replace(/<\?[\s\S]*?\?>/g, "").replace(//gi, ""); + for (const [, close, name, rest, selfClose] of src.matchAll(/<(\/?)([\w:.-]+)([^>]*?)(\/?)>/g)) { + if (close) { + if (stack.length > 1) stack.pop(); + continue; + } + const attrs: Record = {}; + for (const [, k, , v1, v2] of rest.matchAll(/([\w:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g)) attrs[k] = v1 ?? v2 ?? ""; + // style="stroke:…; transform:…" isn't geometry, except display:none. + const el: El = { name: name.replace(/^svg:/, ""), attrs, children: [] }; + stack[stack.length - 1].children.push(el); + if (!selfClose) stack.push(el); + } + return root; +} + +// ---------------------------------------------------------------- units + +const UNIT_MM: Record = { mm: 1, cm: 10, in: 25.4, pt: 25.4 / 72, pc: 25.4 / 6, px: 25.4 / 96, "": 25.4 / 96 }; + +function lengthMM(s: string | undefined): number | null { + const m = s?.trim().match(/^([-+]?[\d.]+(?:e[-+]?\d+)?)\s*(mm|cm|in|pt|pc|px)?$/i); + return m ? Number(m[1]) * UNIT_MM[(m[2] ?? "").toLowerCase()] : null; +} + +// ---------------------------------------------------------------- import + +export interface SvgImport { + entities: SketchEntity[]; + /** Size of the drawing in mm. */ + size: Vec2; +} + +export function parseSVG(text: string): SvgImport { + const doc = parseXml(text); + const svg = findFirst(doc, "svg"); + if (!svg) throw new Error("Not an SVG file"); + // User units → mm, from width + viewBox (no width: 96 px per inch). + const vb = svg.attrs.viewBox ? nums(svg.attrs.viewBox) : null; + const w = lengthMM(svg.attrs.width); + const h = lengthMM(svg.attrs.height); + // Without a viewBox one user unit is one CSS pixel; with one, width (or height) sets the scale. + let k = UNIT_MM.px; + if (vb && vb.length === 4 && vb[2] > 0 && vb[3] > 0) k = w !== null ? w / vb[2] : h !== null ? h / vb[3] : UNIT_MM.px; + const [kx, ky] = [k, k]; + const ox = vb?.[0] ?? 0; + const oy = vb?.[1] ?? 0; + // SVG y points down; the sketch's y points up. + const base: M = mul([kx, 0, 0, -ky, 0, 0], [1, 0, 0, 1, -ox, -oy]); + const out: SketchEntity[] = []; + walk(svg, base, out); + if (!out.length) throw new Error("No shapes found (text has to be converted to paths first)"); + // Centre on the origin. + const pts = out.flatMap(samplePoints); + const lo: Vec2 = [Math.min(...pts.map((p) => p[0])), Math.min(...pts.map((p) => p[1]))]; + const hi: Vec2 = [Math.max(...pts.map((p) => p[0])), Math.max(...pts.map((p) => p[1]))]; + const c: Vec2 = [(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2]; + return { entities: out.map((e) => shift(e, -c[0], -c[1])), size: [hi[0] - lo[0], hi[1] - lo[1]] }; +} + +function findFirst(el: El, name: string): El | null { + if (el.name === name) return el; + for (const c of el.children) { + const f = findFirst(c, name); + if (f) return f; + } + return null; +} + +const SKIP = new Set(["defs", "clipPath", "mask", "symbol", "marker", "pattern", "style", "title", "desc", "metadata", "text", "linearGradient", "radialGradient", "filter", "image"]); + +function walk(el: El, parent: M, out: SketchEntity[]): void { + for (const c of el.children) { + if (SKIP.has(c.name) || /display\s*:\s*none/.test(c.attrs.style ?? "") || c.attrs.display === "none") continue; + const m = mul(parent, parseTransform(c.attrs.transform)); + const n = (k: string, d = 0) => (c.attrs[k] !== undefined ? Number(nums(c.attrs[k])[0] ?? d) : d); + switch (c.name) { + case "g": + case "svg": + case "a": + case "switch": + walk(c, c.name === "svg" ? mul(m, [1, 0, 0, 1, n("x"), n("y")]) : m, out); + break; + case "path": + out.push(...pathEntities(c.attrs.d ?? "", m)); + break; + case "line": + out.push(line(ap(m, [n("x1"), n("y1")]), ap(m, [n("x2"), n("y2")]))); + break; + case "polyline": + case "polygon": { + const v = nums(c.attrs.points ?? ""); + const p: Vec2[] = []; + for (let i = 0; i + 1 < v.length; i += 2) p.push(ap(m, [v[i], v[i + 1]])); + for (let i = 0; i + 1 < p.length; i++) out.push(line(p[i], p[i + 1])); + if (c.name === "polygon" && p.length > 2) out.push(line(p[p.length - 1], p[0])); + break; + } + case "rect": { + const [x, y, w, h] = [n("x"), n("y"), n("width"), n("height")]; + if (w <= 0 || h <= 0) break; + const rx = Math.min(n("rx", n("ry")), w / 2); + const ry = Math.min(n("ry", rx), h / 2); + const sim = similarity(m); + if (!rx && !ry && sim) { + const ctr = ap(m, [x + w / 2, y + h / 2]); + out.push({ id: uid(), kind: "rect", center: ctr, w: w * sim.k, h: h * sim.k, rotation: Math.atan2(m[1], m[0]) }); + } else { + // Rounded (or skewed): as a path. + const d = rx || ry + ? `M${x + rx},${y}H${x + w - rx}A${rx},${ry} 0 0 1 ${x + w},${y + ry}V${y + h - ry}A${rx},${ry} 0 0 1 ${x + w - rx},${y + h}H${x + rx}A${rx},${ry} 0 0 1 ${x},${y + h - ry}V${y + ry}A${rx},${ry} 0 0 1 ${x + rx},${y}Z` + : `M${x},${y}H${x + w}V${y + h}H${x}Z`; + out.push(...pathEntities(d, m)); + } + break; + } + case "circle": + case "ellipse": { + const cx = n("cx"); + const cy = n("cy"); + const rx = c.name === "circle" ? n("r") : n("rx"); + const ry = c.name === "circle" ? n("r") : n("ry", rx); + if (rx <= 0 || ry <= 0) break; + const sim = similarity(m); + const ctr = ap(m, [cx, cy]); + if (sim && Math.abs(rx - ry) < 1e-12) out.push({ id: uid(), kind: "circle", center: ctr, radius: rx * sim.k }); + else if (sim) out.push({ id: uid(), kind: "ellipse", center: ctr, rx: rx * sim.k, ry: ry * sim.k, rotation: sim.rot }); + else out.push(closedSpline(Array.from({ length: 24 }, (_, i) => ap(m, [cx + rx * Math.cos((i / 24) * Math.PI * 2), cy + ry * Math.sin((i / 24) * Math.PI * 2)])))); + break; + } + } + } +} + +// ---------------------------------------------------------------- paths + +/** One SVG path's curves. */ +export function pathEntities(d: string, m: M = I): SketchEntity[] { + const out: SketchEntity[] = []; + const toks = d.match(/[a-df-z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? []; + let i = 0; + let cmd = ""; + let cur: Vec2 = [0, 0]; + let start: Vec2 = [0, 0]; + let lastCtrl: Vec2 | null = null; + let lastQ: Vec2 | null = null; + const num = () => Number(toks[i++]); + const more = () => i < toks.length && !/^[a-z]$/i.test(toks[i]); + const P = (p: Vec2) => ap(m, p); + const sim = similarity(m); + while (i < toks.length) { + if (/^[a-z]$/i.test(toks[i])) cmd = toks[i++]; + const rel = cmd === cmd.toLowerCase(); + const R = (p: Vec2): Vec2 => (rel ? [cur[0] + p[0], cur[1] + p[1]] : p); + const C = cmd.toUpperCase(); + if (C === "Z") { + if (Math.hypot(cur[0] - start[0], cur[1] - start[1]) > 1e-12) out.push(line(P(cur), P(start))); + cur = start; + lastCtrl = lastQ = null; + if (!more()) continue; + cmd = rel ? "l" : "L"; + continue; + } + if (!more()) break; + switch (C) { + case "M": { + cur = R([num(), num()]); + start = cur; + cmd = rel ? "l" : "L"; + lastCtrl = lastQ = null; + continue; + } + case "L": + case "H": + case "V": { + const p: Vec2 = C === "L" ? R([num(), num()]) : C === "H" ? [rel ? cur[0] + num() : num(), cur[1]] : [cur[0], rel ? cur[1] + num() : num()]; + if (Math.hypot(p[0] - cur[0], p[1] - cur[1]) > 1e-12) out.push(line(P(cur), P(p))); + cur = p; + lastCtrl = lastQ = null; + break; + } + case "C": + case "S": { + const c1: Vec2 = C === "C" ? R([num(), num()]) : lastCtrl ? [2 * cur[0] - lastCtrl[0], 2 * cur[1] - lastCtrl[1]] : cur; + const c2 = R([num(), num()]); + const p = R([num(), num()]); + out.push(bezierSpline([cur, c1, c2, p].map(P))); + lastCtrl = c2; + lastQ = null; + cur = p; + break; + } + case "Q": + case "T": { + const q: Vec2 = C === "Q" ? R([num(), num()]) : lastQ ? [2 * cur[0] - lastQ[0], 2 * cur[1] - lastQ[1]] : cur; + const p = R([num(), num()]); + // Quadratic → cubic. + const c1: Vec2 = [cur[0] + (2 / 3) * (q[0] - cur[0]), cur[1] + (2 / 3) * (q[1] - cur[1])]; + const c2: Vec2 = [p[0] + (2 / 3) * (q[0] - p[0]), p[1] + (2 / 3) * (q[1] - p[1])]; + out.push(bezierSpline([cur, c1, c2, p].map(P))); + lastQ = q; + lastCtrl = null; + cur = p; + break; + } + case "A": { + const rx0 = Math.abs(num()); + const ry0 = Math.abs(num()); + const phi = (num() * Math.PI) / 180; + const large = num() !== 0; + const sweep = num() !== 0; + const p = R([num(), num()]); + out.push(...arcEntities(cur, p, rx0, ry0, phi, large, sweep, m, sim)); + cur = p; + lastCtrl = lastQ = null; + break; + } + default: + i++; + } + } + return out; +} + +/** SVG endpoint arc → one arc (circular, under a similarity) or a spline through it. */ +function arcEntities(a: Vec2, b: Vec2, rx: number, ry: number, phi: number, large: boolean, sweep: boolean, m: M, sim: { k: number } | null): SketchEntity[] { + if (Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-12) return []; + if (!rx || !ry) return [line(ap(m, a), ap(m, b))]; + // Endpoint → centre parameterisation (SVG spec, F.6.5). + const cs = Math.cos(phi); + const sn = Math.sin(phi); + const dx = (a[0] - b[0]) / 2; + const dy = (a[1] - b[1]) / 2; + const x1 = cs * dx + sn * dy; + const y1 = -sn * dx + cs * dy; + const lam = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); + if (lam > 1) { + rx *= Math.sqrt(lam); + ry *= Math.sqrt(lam); + } + const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; + const den = rx * rx * y1 * y1 + ry * ry * x1 * x1; + const co = (large !== sweep ? 1 : -1) * Math.sqrt(Math.max(0, num / den)); + const cx1 = (co * rx * y1) / ry; + const cy1 = (-co * ry * x1) / rx; + const cx = cs * cx1 - sn * cy1 + (a[0] + b[0]) / 2; + const cy = sn * cx1 + cs * cy1 + (a[1] + b[1]) / 2; + const ang = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); + const t1 = ang(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); + let dt = ang((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry); + if (!sweep && dt > 0) dt -= 2 * Math.PI; + if (sweep && dt < 0) dt += 2 * Math.PI; + const at = (t: number): Vec2 => ap(m, [cx + rx * Math.cos(t) * cs - ry * Math.sin(t) * sn, cy + rx * Math.cos(t) * sn + ry * Math.sin(t) * cs]); + if (sim && Math.abs(rx - ry) < 1e-9 * rx) { + // A full-ish circle is split in two so each arc's three points stay well apart. + if (Math.abs(dt) > Math.PI * 1.5) { + const h = dt / 2; + return [arc3(at(t1), at(t1 + h / 2), at(t1 + h)), arc3(at(t1 + h), at(t1 + h * 1.5), at(t1 + dt))]; + } + return [arc3(at(t1), at(t1 + dt / 2), at(t1 + dt))]; + } + const n = Math.max(4, Math.ceil((Math.abs(dt) / (Math.PI / 2)) * 4)); + return [{ id: uid(), kind: "spline", mode: "fit", closed: false, points: Array.from({ length: n + 1 }, (_, k) => at(t1 + (dt * k) / n)) }]; +} + +/** A cubic Bézier as a fit spline through points on it (ends exact). */ +function bezierSpline([p0, p1, p2, p3]: Vec2[]): SketchEntity { + // Straight "curves" stay lines. + const off = (p: Vec2) => { + const dx = p3[0] - p0[0]; + const dy = p3[1] - p0[1]; + const l = Math.hypot(dx, dy) || 1; + return Math.abs((p[0] - p0[0]) * dy - (p[1] - p0[1]) * dx) / l; + }; + if (off(p1) < 1e-9 && off(p2) < 1e-9) return line(p0, p3); + const N = 8; + const pts = Array.from({ length: N + 1 }, (_, k): Vec2 => { + const t = k / N; + const u = 1 - t; + return [u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]]; + }); + return { id: uid(), kind: "spline", mode: "fit", closed: false, points: pts }; +} + +const line = (a: Vec2, b: Vec2): SketchEntity => ({ id: uid(), kind: "line", a, b }); +const arc3 = (a: Vec2, m: Vec2, b: Vec2): SketchEntity => ({ id: uid(), kind: "arc", a, m, b }); +const closedSpline = (points: Vec2[]): SketchEntity => ({ id: uid(), kind: "spline", mode: "fit", closed: true, points }); + +function samplePoints(e: SketchEntity): Vec2[] { + switch (e.kind) { + case "line": + return [e.a, e.b]; + case "arc": + return [e.a, e.m, e.b]; + case "circle": + return [[e.center[0] - e.radius, e.center[1] - e.radius], [e.center[0] + e.radius, e.center[1] + e.radius]]; + case "ellipse": { + const r = Math.max(e.rx, e.ry); + return [[e.center[0] - r, e.center[1] - r], [e.center[0] + r, e.center[1] + r]]; + } + case "rect": { + const c = Math.cos(e.rotation); + const s = Math.sin(e.rotation); + return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([u, v]): Vec2 => [e.center[0] + (u * e.w * c - v * e.h * s) / 2, e.center[1] + (u * e.w * s + v * e.h * c) / 2]); + } + case "spline": + case "polyline": + return e.points; + default: + return []; + } +} + +function shift(e: SketchEntity, dx: number, dy: number): SketchEntity { + const s = (p: Vec2): Vec2 => [p[0] + dx, p[1] + dy]; + switch (e.kind) { + case "line": + return { ...e, a: s(e.a), b: s(e.b) }; + case "arc": + return { ...e, a: s(e.a), m: s(e.m), b: s(e.b) }; + case "circle": + case "ellipse": + case "rect": + case "polygon": + return { ...e, center: s(e.center) }; + case "spline": + case "polyline": + return { ...e, points: e.points.map(s) }; + default: + return e; + } +} diff --git a/src/kernel/client.ts b/src/kernel/client.ts new file mode 100644 index 0000000..042fc5a --- /dev/null +++ b/src/kernel/client.ts @@ -0,0 +1,75 @@ +import type { Feature } from "../doc/types"; +import type { Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol"; + +/** Promise-based wrapper around the kernel worker. */ +export class KernelClient { + private worker: Worker; + private nextId = 1; + private pending = new Map void>(); + readonly ready: Promise; + + // Coalesce regenerations: while one runs, only the most recent request waits. + private regenRunning = false; + private regenQueued: { features: Feature[]; resolve: (r: RegenResult | null) => void } | null = null; + + constructor() { + this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }); + this.worker.onmessage = (e: MessageEvent>) => { + const cb = this.pending.get(e.data.id); + this.pending.delete(e.data.id); + cb?.(e.data.msg); + }; + this.ready = this.call({ type: "init" }).then((r) => { + if (r.type === "error") throw new Error(r.message); + }); + } + + /** Told when the kernel starts and stops being busy (to show a busy indicator). */ + onBusy: ((busy: boolean) => void) | null = null; + + private call(msg: Request): Promise { + const id = this.nextId++; + if (this.pending.size === 0) this.onBusy?.(true); + return new Promise((resolve) => { + this.pending.set(id, (r) => { + resolve(r); + if (this.pending.size === 0 && !this.regenQueued) this.onBusy?.(false); + }); + this.worker.postMessage({ id, msg } satisfies Envelope); + }); + } + + /** + * Rebuild geometry. If calls arrive faster than the kernel can answer, the + * intermediate ones resolve with null (they were superseded). + */ + regenerate(features: Feature[]): Promise { + return new Promise((resolve) => { + if (this.regenRunning) { + this.regenQueued?.resolve(null); + this.regenQueued = { features, resolve }; + return; + } + this.runRegen(features, resolve); + }); + } + + private async runRegen(features: Feature[], resolve: (r: RegenResult | null) => void) { + this.regenRunning = true; + await this.ready; + const r = await this.call({ type: "regenerate", features }); + resolve(r.type === "regenerated" ? r.result : null); + if (r.type === "error") console.error(r.message); + this.regenRunning = false; + const q = this.regenQueued; + this.regenQueued = null; + if (q) this.runRegen(q.features, q.resolve); + } + + async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise { + await this.ready; + const r = await this.call({ type: "export", features, format, bodies }); + if (r.type === "exported") return r.blob; + throw new Error(r.type === "error" ? r.message : "Export failed"); + } +} diff --git a/src/kernel/engine.ts b/src/kernel/engine.ts new file mode 100644 index 0000000..ccf59f3 --- /dev/null +++ b/src/kernel/engine.ts @@ -0,0 +1,1154 @@ +// The geometry kernel. This (with sketchGeom.ts) is the ONLY code that knows +// about OpenCascade / replicad; worker.ts exposes it to the UI via protocol.ts. +// +// replicad gotchas, learned the hard way: +// - makeCompound(), translate(), rotate(), mirror(), scale() DELETE their input. +// Shapes here live on in the feature cache, so always clone first. + +import { + basicFaceExtrusion, + exportSTEP, + getOC, + genericSweep, + importSTEP, + importSTL, + loft, + makeCompound, + makeBSplineApproximation, + isShape3D, + makeFace, + cast, + makePolygon, + makeSolid, + measureArea, + measureVolume, + revolution, + Vector, + assembleWire, + type AnyShape, + type Edge, + type Face, + type Shape3D, + type Wire, +} from "replicad"; +import type { + AxisRef, + EdgeRef, + ExtrudeSource, + FaceRef, + Feature, + PathRef, + PlaneDef, + SketchEntity, + SketchFeature, + Vec3, +} from "../doc/types"; +import { add, cross, dist, dot, len, norm, scale, sub, toWorld, xDirFor } from "../geom"; +import { projectPolyline } from "../sketch/edit"; +import { cageToShape } from "./freeform"; +import { deleteFaces, subdivide } from "../freeform/cage"; +import { deleteFace, offsetFace, planeOf, replaceFacePlane, unify } from "./faceEdit"; +import { entitiesWire, regionFaces, regionWire } from "./sketchGeom"; +import type { BodyMesh, ConstructionInfo, EdgeInfo, ExportFormat, FaceInfo, FeatureError, RegenResult } from "./protocol"; + +type Bodies = Map; +type SketchState = SketchFeature & { boundary: SketchEntity[] }; + +const allCurves = (s: SketchState): SketchEntity[] => [...s.entities, ...s.boundary]; + +interface Ctx { + bodies: Bodies; + sketches: Map; + planes: Map; + axes: Map; + /** + * Bodies that are still a freeform cage moved/scaled by an affine map: they can + * be rebuilt exactly (e.g. stretched along X/Y/Z, which other bodies can't be). + */ + freeforms: Map; m: Affine }>; +} + +interface CacheEntry { + key: string; + ctx: Ctx; + error?: string; +} + +const meshCache = new WeakMap(); +const importCache = new Map(); +let cache: CacheEntry[] = []; + +// ------------------------------------------------------------------ public API + +export async function exportBodies(features: Feature[], format: ExportFormat, only?: string[]): Promise { + const { ctx } = await run(features); + const shapes = [...ctx.bodies.entries()].filter(([id]) => !only || only.includes(id)); + if (shapes.length === 0) throw new Error("Nothing to export"); + return format === "step" + ? exportSTEP(shapes.map(([id, shape]) => ({ shape, name: nameOf(features, id) }))) + : await makeCompound(shapes.map(([, s]) => s.clone())).blobSTL({ binary: true, tolerance: 0.02, angularTolerance: 0.1 }); +} + +export async function regenerate(features: Feature[]): Promise { + const t0 = performance.now(); + const { ctx, errors } = await run(features); + const meshes: BodyMesh[] = []; + for (const [id, shape] of ctx.bodies) { + try { + meshes.push(meshBody(id, nameOf(features, id), shape)); + } catch (err) { + errors.push({ featureId: baseId(id), message: `Could not display body: ${errorText(err)}` }); + } + } + const sketchPlanes: Record = {}; + const sketchBoundaries: Record = {}; + for (const [id, s] of ctx.sketches) { + sketchPlanes[id] = s.plane; + if (s.boundary.length) sketchBoundaries[id] = s.boundary; + } + return { bodies: meshes, errors, sketchPlanes, sketchBoundaries, planes: [...ctx.planes.values()], axes: [...ctx.axes.values()], ms: performance.now() - t0 }; +} + +/** + * Replay features in order. Results are cached per feature, keyed by the JSON + * of every feature up to it, so editing feature k only rebuilds k onwards. + */ +async function run(features: Feature[]) { + const errors: FeatureError[] = []; + let ctx: Ctx = { bodies: new Map(), sketches: new Map(), planes: new Map(), axes: new Map(), freeforms: new Map() }; + let key = ""; + const next: CacheEntry[] = []; + let hit = true; + + for (let i = 0; i < features.length; i++) { + const f = features[i]; + key += JSON.stringify(f); + const cached: CacheEntry | undefined = hit && cache[i]?.key === key ? cache[i] : undefined; + hit = !!cached; + let entry: CacheEntry; + if (cached) { + entry = cached; + } else { + const out: Ctx = { bodies: new Map(ctx.bodies), sketches: new Map(ctx.sketches), planes: new Map(ctx.planes), axes: new Map(ctx.axes), freeforms: new Map(ctx.freeforms) }; + entry = { key, ctx: out }; + if (!f.suppressed) { + try { + await apply(f, out); + // Anything but a move/scale changing a freeform body makes it an ordinary body. + if (f.type !== "freeform" && f.type !== "transform") for (const id of [...out.freeforms.keys()]) if (out.bodies.get(id) !== ctx.bodies.get(id)) out.freeforms.delete(id); + } catch (err) { + entry.error = errorText(err); + entry.ctx = { ...ctx, sketches: f.type === "sketch" ? new Map(ctx.sketches).set(f.id, { ...f, boundary: [] }) : ctx.sketches }; + } + } + } + if (entry.error) errors.push({ featureId: f.id, message: entry.error }); + ctx = entry.ctx; + next.push(entry); + } + cache = next; + return { ctx, errors }; +} + +async function apply(f: Feature, ctx: Ctx): Promise { + const { bodies } = ctx; + switch (f.type) { + case "sketch": { + const plane = f.attachedTo ? followFace(f, bodies) : f.plane; + // On a face, the face outline takes part in regions: a line across the face splits it. + const boundary = f.attachedTo ? faceBoundary(f.attachedTo, plane, bodies) : []; + ctx.sketches.set(f.id, { ...f, plane, boundary }); + return; + } + + case "extrude": { + if (Math.abs(f.distance) < 1e-6) throw new Error("Distance is zero"); + // Pushing/pulling a face of its own body offsets it: the neighbouring faces + // extend along their own surfaces (a round side stays round). + if (f.source.kind === "face" && f.mode !== "new" && f.target === f.source.face.body) { + const body = need(bodies, f.target); + const face = resolveFace(body, f.source.face); + const d = f.mode === "cut" ? -Math.abs(f.distance) : f.mode === "join" ? Math.abs(f.distance) : f.distance; + try { + bodies.set(f.target, offsetFace(body, face, d)); + return; + } catch (err) { + // Faces whose neighbours don't enclose them still get a straight push. + if (face.geomType !== "PLANE") throw err; + } + } + const parts = sourceFaces(f.source, ctx).map(({ face, normal }) => basicFaceExtrusion(face, new Vector(normal).multiply(f.distance))); + const solid = fuseAll(parts); + // Auto: other bodies the extrusion runs into get cut through. Drawn on + // its own (no body it belongs to), it then only cuts — no new body. + if (f.mode === "auto") { + const hit = overlapping(solid, ctx, f.target); + for (const id of hit) { + const cut = need(bodies, id).cut(solid); + if (isEmpty(cut)) bodies.delete(id); + else bodies.set(id, cut); + ctx.freeforms.delete(id); + } + if (hit.length && !f.target) return; + } + combine(f.id, f.mode, f.target, solid, f.distance < 0, ctx); + return; + } + + case "revolve": { + if (Math.abs(f.angle) < 1e-6) throw new Error("Angle is zero"); + const axis = resolveAxis(f.axis, ctx); + if (f.travel && Math.abs(f.travel) > 1e-9) { + // Moving along the axis while turning: a helical sweep (threads, springs). + const parts = sourceWires(f.source, ctx).map((w) => helicalSweep(w, axis.origin, norm(axis.dir), f.angle, f.travel!)); + combine(f.id, f.mode, f.target, fuseAll(parts), false, ctx); + return; + } + if (Math.abs(f.angle) > 360 + 1e-6) throw new Error("More than one turn needs a Travel along the axis (or it overlaps itself)"); + const parts = sourceFaces(f.source, ctx).map(({ face }) => revolution(face, axis.origin, axis.dir, f.angle)); + combine(f.id, f.mode, f.target, fuseAll(parts), false, ctx); + return; + } + + case "sweep": { + const spine = pathWire(f.path, ctx); + const parts = sourceWires(f.source, ctx).map((w) => genericSweep(w, spine, { frenet: true, transitionMode: "round" }) as Shape3D); + combine(f.id, f.mode, f.target, fuseAll(parts), false, ctx); + return; + } + + case "loft": { + if (f.sections.length < 2) throw new Error("Pick at least two profiles"); + // Each section's own plane (a profile's sketch, or the face). + const frames = f.sections.map((s) => sectionFrame(s, ctx)); + let order = f.sections.map((_, i) => i); + const n0 = frames[0].normal; + // Parallel sections go in their order along the normal, whatever order they were picked in + // (a loft that doubles back on itself isn't a solid). + if (frames.every((fr) => Math.abs(dot(fr.normal, n0)) > 0.999)) { + const h = (i: number) => dot(sub(frames[i].origin, frames[0].origin), n0); + order.sort((a, b) => h(a) - h(b)); + for (let k = 1; k < order.length; k++) if (Math.abs(h(order[k]) - h(order[k - 1])) < 1e-6) throw new Error("Two profiles lie on the same plane: loft needs them one above another"); + } + // The same profile picked twice counts once. + order = order.filter((i, k) => k === 0 || JSON.stringify(f.sections[i]) !== JSON.stringify(f.sections[order[k - 1]])); + if (order.length < 2) throw new Error("Pick at least two different profiles"); + const wires = order.map((i) => sourceWires(f.sections[i], ctx)[0]); + let shape: Shape3D; + try { + shape = loft(wires, { ruled: f.ruled }); + } catch { + throw new Error("These profiles can't be lofted together"); + } + combine(f.id, f.mode, f.target, shape, false, ctx); + return; + } + + case "fillet": + case "chamfer": { + const byBody = new Map(); + for (const e of f.edges) byBody.set(e.body, [...(byBody.get(e.body) ?? []), e]); + for (const [bodyId, refs] of byBody) { + const body = need(bodies, bodyId); + const edges = refs.map((r) => resolveEdge(body, r)); + const result = + f.type === "fillet" + ? body.fillet(f.radius, (finder) => finder.inList(edges)) + : body.chamfer(f.radius, (finder) => finder.inList(edges)); + bodies.set(bodyId, result); + } + return; + } + + case "shell": { + const body = need(bodies, f.body); + const faces = f.faces.map((r) => resolveFace(body, r)); + // A freeform: drop the picked cage faces and thicken the rest inward — + // exact, where shelling its smooth surfaces is unreliable. + const ff = ctx.freeforms.get(f.body); + if (ff && faces.length) { + bodies.set(f.body, shellFreeform(ff, faces, Math.abs(f.thickness))); + ctx.freeforms.delete(f.body); + return; + } + // Positive thickness shells inward (negative grows outward with rounded corners). + const v0 = Math.abs(measureVolume(body)); + const hollowed = (s: Shape3D | null) => !!s && Math.abs(Math.abs(measureVolume(s)) - v0) > 1e-6 * v0; + let out: Shape3D | null = null; + try { + out = body.shell(Math.abs(f.thickness), (finder) => finder.inList(faces)); + } catch { + out = null; + } + // Many-faced shapes trip the one-step shell: hollow with an offset copy + // of the body instead, then cut the openings through. + if (!hollowed(out)) out = shellByOffset(body, faces, Math.abs(f.thickness)); + // OpenCascade can "succeed" without hollowing anything: say so. + if (!hollowed(out)) throw new Error("Shell didn't work on this shape (try a smaller thickness)"); + bodies.set(f.body, out!); + return; + } + + case "boolean": { + let target = need(bodies, f.target); + for (const t of f.tools) { + const tool = need(bodies, t); + target = f.op === "union" ? target.fuse(tool) : f.op === "subtract" ? target.cut(tool) : target.intersect(tool); + bodies.delete(t); + } + if (isEmpty(target)) throw new Error("The result is empty"); + bodies.set(f.target, target); + return; + } + + case "transform": + transform(f, ctx); + return; + + case "split": { + const body = need(bodies, f.body); + const half = halfSpace(f.plane, body); + const a = body.intersect(half); + const b = body.cut(half); + if (isEmpty(a) || isEmpty(b)) throw new Error("The plane doesn't cut through the body"); + bodies.set(f.body, b); + bodies.set(f.id, a); + return; + } + + case "plane": { + let plane = f.plane; + if (f.face) { + const body = bodies.get(f.face.body); + if (body) { + const info = faceInfo(resolveFace(body, f.face)); + if (info.plane) plane = { ...info.plane, xDir: dot(info.plane.normal, f.plane.normal) > 0.999 ? f.plane.xDir : info.plane.xDir }; + } + } + plane = { ...plane, origin: add(plane.origin, scale(plane.normal, f.offset)) }; + ctx.planes.set(f.id, { id: f.id, name: f.name, plane }); + return; + } + + case "axis": + ctx.axes.set(f.id, { id: f.id, name: f.name, plane: { origin: f.origin, normal: norm(f.dir), xDir: xDirFor(norm(f.dir)) } }); + return; + + case "import": { + let shape = importCache.get(f.data); + if (!shape) { + const bytes = Uint8Array.from(atob(f.data), (c) => c.charCodeAt(0)); + const blob = new Blob([bytes]); + shape = (f.format === "step" ? await importSTEP(blob) : await importSTL(blob)) as Shape3D; + if (isEmpty(shape)) throw new Error("The file contains no solid geometry"); + importCache.set(f.data, shape); + } + bodies.set(f.id, shape); + return; + } + + case "delete": + for (const b of f.bodies) bodies.delete(b); + return; + + case "image": + return; // drawn by the UI only + + case "freeform": + bodies.set(f.id, freeformShape(f, AFFINE_ID)); + ctx.freeforms.set(f.id, { feature: f, m: AFFINE_ID }); + return; + + case "scaleFace": { + const body = need(bodies, f.face.body); + bodies.set(f.face.body, scaleFace(body, resolveFace(body, f.face), f.u, f.factors)); + return; + } + + case "replaceFace": { + const body = need(bodies, f.face.body); + const face = resolveFace(body, f.face); + // Follow the target face if it's still there; else the plane as saved. + let plane = f.plane; + if (f.target) { + const tb = bodies.get(f.target.body); + const tf = tb && (() => { + try { + return resolveFace(tb, f.target!); + } catch { + return null; + } + })(); + if (tf?.geomType === "PLANE") plane = planeOf(tf); + } + // Keep the face pointing the way it pointed (outward). + const n0 = planeOf(face).normal; + const n = dot(plane.normal, n0) < 0 ? scale(plane.normal, -1) : plane.normal; + bodies.set(f.face.body, replaceFacePlane(body, face, { origin: plane.origin, normal: n, xDir: xDirFor(n) })); + return; + } + + case "deleteGeom": { + let body = need(bodies, f.body); + for (const r of f.faces) body = deleteFace(body, resolveFace(body, r)); + for (const r of f.edges) body = deleteEdge(body, r); + for (const v of f.vertices) body = deleteVertex(body, v); + bodies.set(f.body, body); + return; + } + + case "moveFace": { + const r = f.rotate && Math.abs(f.rotate.angle) > 1e-9 ? f.rotate : undefined; + const move = (p: Vec3) => add(r ? rotateAbout(p, r.origin, r.axis, r.angle) : p, f.translate); + const turn = (n: Vec3) => (r ? norm(sub(rotateAbout(add(r.origin, n), r.origin, r.axis, r.angle), r.origin)) : n); + if (f.face) { + const body = need(bodies, f.face.body); + const face = resolveFace(body, f.face); + const { origin, normal } = planeOf(face); + const n = turn(normal); + bodies.set(f.face.body, replaceFacePlane(body, face, { origin: move(origin), normal: n, xDir: xDirFor(n) })); + return; + } + if (f.vertex) { + if (ctx.freeforms.has(f.vertex.body)) throw new Error("A freeform's shape comes from its cage: use Edit Freeform to move its points"); + bodies.set(f.vertex.body, moveVertex(need(bodies, f.vertex.body), f.vertex.at, move(f.vertex.at))); + return; + } + if (!f.edge) throw new Error("Nothing to move"); + bodies.set(f.edge.body, moveEdge(need(bodies, f.edge.body), f.edge, move)); + return; + } + } +} + +// ------------------------------------------------------------ affine maps + +/** x' = A x + t, as [a00 a01 a02 t0, a10 a11 a12 t1, a20 a21 a22 t2]. */ +type Affine = number[]; +const AFFINE_ID: Affine = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; +const applyAffine = (m: Affine, p: Vec3): Vec3 => [0, 1, 2].map((r) => m[r * 4] * p[0] + m[r * 4 + 1] * p[1] + m[r * 4 + 2] * p[2] + m[r * 4 + 3]) as Vec3; +/** First m, then n. */ +function affineThen(m: Affine, n: Affine): Affine { + const out: number[] = []; + for (let r = 0; r < 3; r++) { + for (let c = 0; c < 3; c++) out.push(n[r * 4] * m[c] + n[r * 4 + 1] * m[4 + c] + n[r * 4 + 2] * m[8 + c]); + out.push(n[r * 4] * m[3] + n[r * 4 + 1] * m[7] + n[r * 4 + 2] * m[11] + n[r * 4 + 3]); + } + return out; +} +const scaleAbout = (c: Vec3, k: Vec3): Affine => [k[0], 0, 0, c[0] * (1 - k[0]), 0, k[1], 0, c[1] * (1 - k[1]), 0, 0, k[2], c[2] * (1 - k[2])]; + +/** The affine map of a move/scale/mirror step (null for patterns). */ +function opAffine(op: Extract["op"]): Affine | null { + const fromPoints = (f: (p: Vec3) => Vec3): Affine => { + const o = f([0, 0, 0]); + const cols = [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map((e) => sub(f(e as Vec3), o)); + return [0, 1, 2].flatMap((r) => [cols[0][r], cols[1][r], cols[2][r], o[r]]); + }; + switch (op.kind) { + case "move": { + const r = op.rotate && Math.abs(op.rotate.angle) > 1e-9 ? op.rotate : null; + return fromPoints((p) => add(r ? rotateAbout(p, r.origin, r.axis, r.angle) : p, op.translate)); + } + case "scale": + return scaleAbout(op.center, [op.factor, op.factor, op.factor]); + case "scaleXYZ": + return scaleAbout(op.center, op.factors); + case "mirror": { + const k = norm(op.plane.normal); + return fromPoints((p) => sub(p, scale(k, 2 * dot(sub(p, op.plane.origin), k)))); + } + default: + return null; + } +} + +/** Shell a freeform: remove the cage quads under the picked faces, thicken the sheet inward. */ +function shellFreeform(ff: { feature: Extract; m: Affine }, faces: Face[], t: number): Shape3D { + const cage = { faces: ff.feature.cage.faces, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) }; + // Each body face is one cage quad's patch: match by the patch's middle point. + const sub3 = subdivide(cage, 3); + const mid = sub3.n / 2; + const centres = sub3.grids.map((g) => sub3.points[g[mid][mid]]); + const drop = new Set(); + for (const face of faces) { + const c = face.center.toTuple() as Vec3; + let best = 0; + centres.forEach((q, i) => { + if (dist(q, c) < dist(centres[best], c)) best = i; + }); + drop.add(best); + } + if (drop.size >= cage.faces.length) throw new Error("Shell needs at least one face to stay"); + const open = deleteFaces(cage, [...drop]); + // Closed cages face outward, so "down" (against the normals) is inward. + return cageToShape(open, 3, { thickness: t, side: "down" }); +} + +/** A freeform's shape with its cage mapped by m (thickness grows with the overall scale). */ +function freeformShape(f: Extract, m: Affine): Shape3D { + const cage = { faces: f.cage.faces, verts: f.cage.verts.map((v) => applyAffine(m, v)) }; + const det = Math.abs(m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8]) + m[2] * (m[4] * m[9] - m[5] * m[8])); + const thicken = f.thickness ? { thickness: f.thickness * Math.cbrt(det || 1), side: f.thickSide ?? "up" } : undefined; + return cageToShape(cage, 3, thicken); +} + +/** + * Scale a flat face within its plane: each flat neighbour turns about its far + * side so it passes through the face's moved edge (like a taper). + */ +function scaleFace(body: Shape3D, face: Face, u0: Vec3, [su, sv]: [number, number]): Shape3D { + if (face.geomType !== "PLANE") throw new Error("Scale Face works on flat faces"); + if (su <= 0 || sv <= 0) throw new Error("Scale factors must be positive"); + const { origin: c0, normal: n } = planeOf(face); + const c = face.center.toTuple() as Vec3; + const u = norm(sub(u0, scale(n, dot(u0, n)))); + const v = cross(n, u); + void c0; + const map = (p: Vec3): Vec3 => { + const d = sub(p, c); + return add(c, add(add(scale(u, su * dot(d, u)), scale(v, sv * dot(d, v))), scale(n, dot(d, n)))); + }; + const targets = face.edges.map((edge) => { + if (edge.geomType !== "LINE") throw new Error("Scale Face needs straight edges (round edges can't taper yet)"); + const g = body.faces.find((x) => !x.isSame(face) && x.edges.some((e) => e.isSame(edge))); + if (!g) throw new Error("A neighbouring face is missing"); + if (g.geomType !== "PLANE") throw new Error("Scale Face works when the faces around it are flat"); + const a = edge.startPoint.toTuple() as Vec3; + const b = edge.endPoint.toTuple() as Vec3; + const a2 = map(a); + const b2 = map(b); + const d = norm(sub(b, a)); + const off = (p: Vec3) => len(sub(sub(p, a), scale(d, dot(sub(p, a), d)))); + const pts = g.edges.flatMap((e) => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3]); + const far = pts.reduce((m, p) => (off(p) > off(m) ? p : m), pts[0]); + const old = planeOf(g); + let nn = norm(cross(sub(b2, a2), sub(far, a2))); + if (dot(nn, old.normal) < 0) nn = scale(nn, -1); + return { sig: faceInfo(g), plane: { origin: a2, normal: nn, xDir: xDirFor(nn) } }; + }); + let out = body; + for (const t of targets) out = replaceFacePlane(out, resolveFace(out, { body: "", center: t.sig.center, normal: t.sig.normal, area: t.sig.area }), t.plane); + return out; +} + +/** Rotate point p about the axis through o along a (degrees). */ +function rotateAbout(p: Vec3, o: Vec3, a: Vec3, deg: number): Vec3 { + const k = norm(a); + const v = sub(p, o); + const t = (deg * Math.PI) / 180; + const c = Math.cos(t); + const s = Math.sin(t); + // Rodrigues' rotation formula. + const r = add(add(scale(v, c), scale(cross(k, v), s)), scale(k, dot(k, v) * (1 - c))); + return add(o, r); +} + +/** + * Move a straight edge: each flat face on it turns about its far side so it + * passes through the edge's new position. + */ +function moveEdge(body: Shape3D, ref: EdgeRef, move: (p: Vec3) => Vec3): Shape3D { + const edge = resolveEdge(body, ref); + if (edge.geomType !== "LINE") throw new Error("Only straight edges can be moved"); + const a = edge.startPoint.toTuple() as Vec3; + const b = edge.endPoint.toTuple() as Vec3; + const a2 = move(a); + const b2 = move(b); + const d2 = norm(sub(b2, a2)); + const faces = body.faces.filter((g) => g.edges.some((e) => e.isSame(edge))); + if (faces.some((g) => g.geomType !== "PLANE")) throw new Error("Only edges between flat faces can be moved"); + const targets = faces.map((g) => { + const old = planeOf(g); + // The face's point farthest from the edge stays put. + const pts = g.edges.flatMap((e) => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3]); + const d = norm(sub(b, a)); + const off = (p: Vec3) => len(sub(sub(p, a), scale(d, dot(sub(p, a), d)))); + const far = pts.reduce((m, p) => (off(p) > off(m) ? p : m), pts[0]); + let n = norm(cross(d2, sub(far, a2))); + if (dot(n, old.normal) < 0) n = scale(n, -1); + return { sig: faceInfo(g), plane: { origin: a2, normal: n, xDir: xDirFor(n) } }; + }); + let out = body; + for (const t of targets) out = replaceFacePlane(out, resolveFace(out, { body: ref.body, center: t.sig.center, normal: t.sig.normal, area: t.sig.area }), t.plane); + return out; +} + +/** + * Move one corner: every flat face meeting at it turns about its far edge (the + * one not touching the corner) so it passes through the corner's new place. + */ +function moveVertex(body: Shape3D, at: Vec3, to: Vec3): Shape3D { + // A body of flat faces moves just the point: faces that would bend are split + // into a triangle at the corner and the untouched rest. + const poly = movePolyhedronVertex(body, at, to); + if (poly) return poly; + return moveVertexByPlanes(body, at, to); +} + +/** Outer loop of a flat, straight-edged face as ordered corners (null if it isn't one). */ +function faceLoop(face: Face, tol: number): Vec3[] | null { + // (outerWire / innerWires use up the face they're called on: ask clones.) + if (face.geomType !== "PLANE" || face.clone().innerWires().length) return null; + const edges = face.clone().outerWire().edges; + if (edges.some((e) => e.geomType !== "LINE")) return null; + const segs = edges.map((e) => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3]); + const loop: Vec3[] = [segs[0][0], segs[0][1]]; + const used = new Set([0]); + while (used.size < segs.length) { + const last = loop[loop.length - 1]; + const k = segs.findIndex((sg, i) => !used.has(i) && (dist(sg[0], last) < tol || dist(sg[1], last) < tol)); + if (k < 0) return null; + used.add(k); + loop.push(dist(segs[k][0], last) < tol ? segs[k][1] : segs[k][0]); + } + if (dist(loop[0], loop[loop.length - 1]) > tol) return null; + loop.pop(); + // Wind it so its normal is the face's outward normal. + const n = face.normalAt().toTuple() as Vec3; + if (dot(polyNormal(loop), n) < 0) loop.reverse(); + return loop; +} + +function polyNormal(pts: Vec3[]): Vec3 { + let n: Vec3 = [0, 0, 0]; + for (let i = 0; i < pts.length; i++) n = add(n, cross(pts[i], pts[(i + 1) % pts.length])); + return n; +} + +function coplanar(pts: Vec3[], tol: number): boolean { + const n = norm(polyNormal(pts)); + if (!Number.isFinite(n[0]) || len(n) < 0.5) return false; + return pts.every((p) => Math.abs(dot(sub(p, pts[0]), n)) < tol); +} + +function movePolyhedronVertex(body: Shape3D, at: Vec3, to: Vec3): Shape3D | null { + const size = Math.hypot(body.boundingBox.width, body.boundingBox.height, body.boundingBox.depth) || 1; + const tol = size * 1e-6; + const loops = body.faces.map((f) => faceLoop(f, tol)); + if (loops.some((l) => !l)) return null; + const polys: Vec3[][] = []; + let touched = 0; + for (const loop of loops as Vec3[][]) { + const i = loop.findIndex((p) => dist(p, at) < tol); + if (i < 0) { + polys.push(loop); + continue; + } + touched++; + const moved = loop.map((p, k) => (k === i ? to : p)); + if (coplanar(moved, tol * 10)) { + polys.push(moved); + continue; + } + // Bent: a triangle at the corner, the rest stays where it was. + const prev = loop[(i - 1 + loop.length) % loop.length]; + const next = loop[(i + 1) % loop.length]; + polys.push([prev, to, next]); + const rest = loop.filter((_, k) => k !== i); + if (rest.length >= 3) polys.push(rest); + } + if (!touched) throw new Error("That corner is no longer there"); + try { + const build = (list: Vec3[][]) => unify(makeSolid(list.map((pl) => makePolygon(pl))) as unknown as Shape3D); + let solid = build(polys); + let v = measureVolume(solid); + // Inside out: wind every face the other way. + if (v < 0) { + solid = build(polys.map((pl) => [...pl].reverse())); + v = measureVolume(solid); + } + if (!Number.isFinite(v) || v < 1e-9 * size ** 3 || solid.faces.length < 4) return null; + return solid; + } catch { + return null; + } +} + +function moveVertexByPlanes(body: Shape3D, at: Vec3, to: Vec3): Shape3D { + const size = Math.hypot(body.boundingBox.width, body.boundingBox.height, body.boundingBox.depth) || 1; + const tol = size * 1e-6; + const ends = (e: Edge): Vec3[] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3]; + const faces = body.faces.filter((g) => g.edges.some((e) => ends(e).some((p) => dist(p, at) < tol))); + if (!faces.length) throw new Error("That corner is no longer there"); + if (faces.some((g) => g.geomType !== "PLANE")) throw new Error("Only corners where flat faces meet can be moved"); + const targets = faces.map((g) => { + const old = planeOf(g); + // The far edge: both ends away from the corner, the farthest such edge. + const far = g.edges + .filter((e) => e.geomType === "LINE" && ends(e).every((p) => dist(p, at) > tol)) + .sort((a, b) => dist(b.pointAt(0.5).toTuple() as Vec3, at) - dist(a.pointAt(0.5).toTuple() as Vec3, at))[0]; + if (!far) throw new Error("Moving this corner needs straight-edged faces around it"); + const [p1, p2] = ends(far); + let n = norm(cross(sub(p1, to), sub(p2, to))); + if (len(n) < 1e-9 || !Number.isFinite(n[0])) throw new Error("The corner can't go there (a face would fold flat)"); + if (dot(n, old.normal) < 0) n = scale(n, -1); + return { sig: faceInfo(g), plane: { origin: to, normal: n, xDir: xDirFor(n) } }; + }); + let out = body; + for (const t of targets) out = replaceFacePlane(out, resolveFace(out, { body: "", center: t.sig.center, normal: t.sig.normal, area: t.sig.area }), t.plane); + return out; +} + +/** + * Remove an edge: merge its faces when they lie on one surface, otherwise drop + * the blend face it bounds (fillet/chamfer) so its neighbours meet again. + */ +function deleteEdge(body: Shape3D, ref: EdgeRef): Shape3D { + const edge = resolveEdge(body, ref); + const merged = unify(body); + if (merged.edges.length < body.edges.length && !hasEdge(merged, ref)) return merged; + const adjacent = body.faces.filter((g) => g.edges.some((e) => e.isSame(edge))); + // Try the curved / smaller face first: that's the blend. + adjacent.sort((a, b) => (a.geomType === "PLANE" ? 1 : 0) - (b.geomType === "PLANE" ? 1 : 0) || measureArea(a) - measureArea(b)); + for (const g of adjacent) { + try { + return deleteFace(body, g); + } catch { + // try the other face + } + } + throw new Error("This edge can't be removed — the faces around it wouldn't close up"); +} + +function hasEdge(body: Shape3D, ref: EdgeRef): boolean { + try { + const e = edgeInfo(resolveEdge(body, ref)); + return dist(e.mid, ref.mid) < (ref.length || 1) * 1e-3 && Math.abs(e.length - ref.length) < (ref.length || 1) * 1e-3; + } catch { + return false; + } +} + +/** + * A profile turned `angle` degrees about an axis while moving `travel` along + * it: swept along a helix through the profile's centre, keeping its + * orientation to the axis (binormal mode), as threads are made. + */ +function helicalSweep(wire: Wire, origin: Vec3, dir: Vec3, angle: number, travel: number): Shape3D { + const bb = wire.boundingBox; + const c = bb.center as Vec3; + // The helix runs through the profile's centre (or, on the axis, its far side). + const radial = (p: Vec3) => { + const v = sub(p, origin); + return sub(v, scale(dir, dot(v, dir))); + }; + let start = c; + if (len(radial(c)) < 1e-6 * (1 + bb.width + bb.height + bb.depth)) { + const far = wire.edges.flatMap((e) => [0, 0.5, 1].map((t) => e.pointAt(t).toTuple() as Vec3)).sort((a, b) => len(radial(b)) - len(radial(a)))[0]; + start = far; + } + const turns = Math.abs(angle) / 360; + const n = Math.max(16, Math.ceil(turns * 48)); + const pts: Vec3[] = []; + const rel = sub(start, origin); + for (let i = 0; i <= n; i++) { + const t = i / n; + const th = (angle * Math.PI * t) / 180; + // Rodrigues' rotation about the axis, plus the travel so far. + const v = add(add(scale(rel, Math.cos(th)), scale(cross(dir, rel), Math.sin(th))), scale(dir, dot(dir, rel) * (1 - Math.cos(th)))); + pts.push(add(add(origin, v), scale(dir, travel * t))); + } + const spine = assembleWire([makeBSplineApproximation(pts, { tolerance: 1e-5 * (1 + len(rel)), degMax: 5, degMin: 3 })]); + const oc = getOC(); + const builder = new oc.BRepOffsetAPI_MakePipeShell(spine.wrapped); + const bi = new oc.gp_Dir(dir[0], dir[1], dir[2]); + try { + builder.SetMode(bi); + builder.Add(wire.wrapped, false, false); + builder.Build(); + if (!builder.IsDone()) throw new Error("The profile can't be swept round this axis"); + builder.MakeSolid(); + const shape = cast(builder.Shape()); + if (!isShape3D(shape)) throw new Error("The profile can't be swept round this axis"); + return shape; + } finally { + builder.delete(); + bi.delete(); + } +} + +/** + * Shell without BRepOffsetAPI_MakeThickSolid: body − (body offset inward by t) + * leaves a closed skin; each removed flat face then gets a hole cut through + * it (its outline shrunk by t, pushed through the skin). + */ +function shellByOffset(body: Shape3D, faces: Face[], t: number): Shape3D | null { + const oc = getOC(); + const off = new oc.BRepOffsetAPI_MakeOffsetShape(); + try { + const src = unify(body); + let inner: Shape3D | null = null; + for (const join of [oc.GeomAbs_JoinType.GeomAbs_Intersection, oc.GeomAbs_JoinType.GeomAbs_Arc]) { + try { + off.PerformByJoin(src.wrapped, -t, 1e-6, oc.BRepOffset_Mode.BRepOffset_Skin, true, false, join, false, new oc.Message_ProgressRange()); + if (off.IsDone()) { + let got = cast(off.Shape()); + // It can come back as a closed shell: make that a solid. + if (got.constructor.name === "Shell") got = makeSolid([got as never]); + inner = got as Shape3D; + } + if (inner && Math.abs(measureVolume(inner)) > 0) break; + } catch { + inner = null; + } + } + if (!inner) return null; + let skin = body.cut(inner); + for (const face of faces) { + if (face.geomType !== "PLANE") return null; + const n = norm(face.normalAt().toTuple() as Vec3); + // The opening: the face's outline brought in by the wall thickness. + const wire = face.clone().outerWire().offset2D(-t, "intersection"); + const start = new Vector(scale(n, t * 0.5)); + const hole = basicFaceExtrusion(makeFace(wire).translate(start), new Vector(scale(n, -t * 2))); + skin = skin.cut(hole); + } + return skin; + } catch { + return null; + } finally { + off.delete(); + } +} + +/** Remove a vertex that only splits an edge or face (merges what it separates). */ +function deleteVertex(body: Shape3D, at: Vec3): Shape3D { + const merged = unify(body); + const tol = 1e-6 * (Math.hypot(body.boundingBox.width, body.boundingBox.height, body.boundingBox.depth) || 1); + const still = merged.edges.some((e) => dist(e.startPoint.toTuple() as Vec3, at) < tol || dist(e.endPoint.toTuple() as Vec3, at) < tol); + if (still) throw new Error("This corner can't be removed — it's where faces meet"); + return merged; +} + +// ------------------------------------------------------------ feature helpers + +/** Faces (with their outward normal) for a profile or a body face. */ +function sourceFaces(src: ExtrudeSource, ctx: Ctx): { face: Face; normal: Vec3 }[] { + if (src.kind === "profile") { + const sketch = ctx.sketches.get(src.sketch); + if (!sketch) throw new Error("Its sketch was deleted"); + return regionFaces(allCurves(sketch), sketch.plane, src.regions).map((face) => ({ face, normal: sketch.plane.normal })); + } + const face = resolveFace(need(ctx.bodies, src.face.body), src.face); + if (face.geomType !== "PLANE") throw new Error("Only flat faces can be used here"); + return [{ face, normal: norm(face.normalAt().toTuple() as Vec3) }]; +} + +/** Plane of a loft section. */ +function sectionFrame(src: ExtrudeSource, ctx: Ctx): { origin: Vec3; normal: Vec3 } { + if (src.kind === "profile") { + const sketch = ctx.sketches.get(src.sketch); + if (!sketch) throw new Error("Its sketch was deleted"); + return { origin: sketch.plane.origin, normal: norm(sketch.plane.normal) }; + } + const face = resolveFace(need(ctx.bodies, src.face.body), src.face); + return { origin: face.center.toTuple() as Vec3, normal: norm(face.normalAt().toTuple() as Vec3) }; +} + +function sourceWires(src: ExtrudeSource, ctx: Ctx): Wire[] { + if (src.kind === "profile") { + const sketch = ctx.sketches.get(src.sketch); + if (!sketch) throw new Error("Its sketch was deleted"); + return src.regions.map((r) => regionWire(allCurves(sketch), sketch.plane, r)); + } + return [resolveFace(need(ctx.bodies, src.face.body), src.face).outerWire()]; +} + +function pathWire(path: PathRef, ctx: Ctx): Wire { + if (path.kind === "sketch") { + const sketch = ctx.sketches.get(path.sketch); + if (!sketch) throw new Error("The path sketch was deleted"); + return entitiesWire(sketch.entities, path.entities, sketch.plane); + } + const edges: Edge[] = path.edges.map((r) => resolveEdge(need(ctx.bodies, r.body), r)); + return assembleWire(edges); +} + +function resolveAxis(a: AxisRef, ctx: Ctx): { origin: Vec3; dir: Vec3 } { + if (a.ref?.kind === "sketchLine") { + const s = ctx.sketches.get(a.ref.sketch); + const e = s?.entities.find((x) => x.id === (a.ref as { entity: string }).entity); + if (s && e?.kind === "line") { + const p = toWorld(s.plane, e.a); + return { origin: p, dir: norm(sub(toWorld(s.plane, e.b), p)) }; + } + } + if (a.ref?.kind === "axis") { + const ax = ctx.axes.get(a.ref.feature); + if (ax) return { origin: ax.plane.origin, dir: ax.plane.normal }; + } + return { origin: a.origin, dir: norm(a.dir) }; +} + +/** Put a new solid into the model: new body, or join/cut a target. */ +function combine(id: string, mode: string, target: string | undefined, solid: Shape3D, negative: boolean, ctx: Ctx): void { + const m = mode === "auto" ? (target ? (negative ? "cut" : "join") : "new") : mode; + if (m === "new" || !target) { + ctx.bodies.set(id, solid); + return; + } + const t = need(ctx.bodies, target); + const result = m === "join" ? t.fuse(solid) : m === "cut" ? t.cut(solid) : t; + if (isEmpty(result)) ctx.bodies.delete(target); + else ctx.bodies.set(target, result); +} + +/** Bodies (other than `skip`) that `solid` really overlaps (not just touches). */ +function overlapping(solid: Shape3D, ctx: Ctx, skip?: string): string[] { + const sb = solid.boundingBox; + const vs = Math.abs(measureVolume(solid)); + const out: string[] = []; + for (const [id, body] of ctx.bodies) { + if (id === skip) continue; + const bb = body.boundingBox; + const apart = [0, 1, 2].some((k) => (bb.bounds[1] as number[])[k] < (sb.bounds[0] as number[])[k] || (bb.bounds[0] as number[])[k] > (sb.bounds[1] as number[])[k]); + if (apart) continue; + try { + const common = body.intersect(solid); + if (!isEmpty(common) && Math.abs(measureVolume(common)) > Math.max(1e-9, Math.min(vs, Math.abs(measureVolume(body))) * 1e-6)) out.push(id); + } catch { + // can't tell: leave it alone + } + } + return out; +} + +function fuseAll(parts: Shape3D[]): Shape3D { + if (!parts.length) throw new Error("Nothing to build"); + return parts.reduce((a, b) => a.fuse(b)); +} + +function transform(f: Extract, ctx: Ctx): void { + const op = f.op; + const copies: [string, Shape3D][] = []; + for (const id of f.bodies) { + const body = need(ctx.bodies, id); + const results: Shape3D[] = []; + switch (op.kind) { + case "move": { + let s = body.clone(); + if (op.rotate && Math.abs(op.rotate.angle) > 1e-9) s = s.rotate(op.rotate.angle, op.rotate.origin, op.rotate.axis); + if (len(op.translate) > 1e-9) s = s.translate(op.translate); + results.push(s); + break; + } + case "scale": + if (op.factor <= 0) throw new Error("Scale must be positive"); + results.push(body.clone().scale(op.factor, op.center)); + break; + case "scaleXYZ": { + if (op.factors.some((k) => k <= 0)) throw new Error("Scale factors must be positive"); + const ff = ctx.freeforms.get(id); + if (!ff) throw new Error("Stretching along X/Y/Z works on freeform bodies only — the geometry engine can't stretch other bodies (use uniform Scale)"); + results.push(freeformShape(ff.feature, affineThen(ff.m, scaleAbout(op.center, op.factors)))); + break; + } + case "mirror": + results.push(body.clone().mirror(op.plane.normal, op.plane.origin)); + break; + case "linear": + for (let k = 1; k < op.count; k++) results.push(body.clone().translate(scale(norm(op.dir), op.spacing * k))); + break; + case "circular": { + const ax = resolveAxis(op.axis, ctx); + const full = Math.abs(Math.abs(op.angle) - 360) < 1e-6; + const step = op.angle / (full ? op.count : Math.max(1, op.count - 1)); + for (let k = 1; k < op.count; k++) results.push(body.clone().rotate(step * k, ax.origin, ax.dir)); + break; + } + } + const isPattern = op.kind === "linear" || op.kind === "circular"; + // A freeform stays rebuildable through moves, scales and mirrors (copies too). + const ff = ctx.freeforms.get(id); + const step = ff && !isPattern ? opAffine(op) : null; + if (isPattern || f.copy) { + results.forEach((s, k) => copies.push([`${f.id}:${id}:${k}`, s])); + if (ff && step) ctx.freeforms.set(`${f.id}:${id}:0`, { feature: ff.feature, m: affineThen(ff.m, step) }); + } else { + ctx.bodies.set(id, results[0]); + if (ff && step) ctx.freeforms.set(id, { feature: ff.feature, m: affineThen(ff.m, step) }); + else ctx.freeforms.delete(id); + } + } + for (const [id, s] of copies) ctx.bodies.set(id, s); +} + +/** Solid filling the positive side of a plane, big enough to contain `body`. */ +function halfSpace(plane: PlaneDef, body: Shape3D): Shape3D { + const bb = body.boundingBox; + const L = (Math.hypot(bb.width, bb.height, bb.depth) + dist(bb.center as Vec3, plane.origin)) * 2 + 10; + const x = plane.xDir; + const y = cross(plane.normal, x); + const o = plane.origin; + const corner = (u: number, v: number): Vec3 => add(o, add(scale(x, u * L), scale(y, v * L))); + const face = makePolygon([corner(-1, -1), corner(1, -1), corner(1, 1), corner(-1, 1)]); + return basicFaceExtrusion(face, new Vector(plane.normal).multiply(L)); +} + +/** The outline of the face a sketch sits on, as sketch curves (ids "bnd-…"). */ +function faceBoundary(ref: FaceRef, plane: PlaneDef, bodies: Bodies): SketchEntity[] { + const body = bodies.get(ref.body); + if (!body) return []; + let face: Face; + try { + face = resolveFace(body, ref); + } catch { + return []; + } + if (face.geomType !== "PLANE") return []; + return face.edges.flatMap((e, i) => { + const pts = Array.from({ length: 25 }, (_, k) => e.pointAt(k / 24).toTuple() as Vec3); + const ent = projectPolyline(pts, plane, e.geomType); + return ent ? [{ ...ent, id: `bnd-${i}` }] : []; + }); +} + +/** A sketch drawn on a face moves with that face when earlier features change. */ +function followFace(f: SketchFeature, bodies: Bodies): PlaneDef { + const ref = f.attachedTo!; + const body = bodies.get(ref.body); + if (!body) return f.plane; + const face = resolveFace(body, ref); + const n = norm(face.normalAt().toTuple() as Vec3); + const c = face.center.toTuple() as Vec3; + const offset = dot(n, sub(c, f.plane.origin)); + const origin = add(f.plane.origin, scale(n, offset)); + return dot(n, f.plane.normal) > 0.999 ? { ...f.plane, origin } : { origin, normal: n, xDir: xDirFor(n) }; +} + +// ----------------------------------------------------- geometric references + +function faceInfo(face: Face): FaceInfo { + const center = face.center.toTuple() as Vec3; + const normal = norm(face.normalAt().toTuple() as Vec3); + const info: FaceInfo = { center, normal, area: measureArea(face), type: face.geomType }; + if (face.geomType === "PLANE") info.plane = { origin: center, normal, xDir: xDirFor(normal) }; + return info; +} + +function edgeInfo(edge: Edge): EdgeInfo { + const info: EdgeInfo = { + mid: edge.pointAt(0.5).toTuple() as Vec3, + dir: norm(edge.tangentAt(0.5).toTuple() as Vec3), + length: edge.length, + start: edge.startPoint.toTuple() as Vec3, + end: edge.endPoint.toTuple() as Vec3, + type: edge.geomType, + }; + return info; +} + +/** Best-matching face for a stored signature (survives upstream edits). */ +function resolveFace(body: Shape3D, ref: FaceRef): Face { + const size = Math.sqrt(ref.area) || 1; + let best: { face: Face; score: number } | null = null; + for (const face of body.faces) { + const fi = faceInfo(face); + const align = dot(fi.normal, ref.normal); + if (align < 0.5) continue; + const score = dist(fi.center, ref.center) / size + (1 - align) * 4 + Math.abs(Math.log((fi.area + 1e-9) / (ref.area + 1e-9))); + if (!best || score < best.score) best = { face, score }; + } + if (!best) throw new Error("The face it was built on no longer exists"); + return best.face; +} + +function resolveEdge(body: Shape3D, ref: EdgeRef): Edge { + const size = ref.length || 1; + let best: { edge: Edge; score: number } | null = null; + for (const edge of body.edges) { + const ei = edgeInfo(edge); + const align = Math.abs(dot(ei.dir, ref.dir)); + const score = dist(ei.mid, ref.mid) / size + (1 - align) * 2 + Math.abs(Math.log((ei.length + 1e-9) / (ref.length + 1e-9))); + if (!best || score < best.score) best = { edge, score }; + } + if (!best || best.score > 3) throw new Error("An edge it was built on no longer exists"); + return best.edge; +} + +// ------------------------------------------------------------------- meshing + +function meshBody(id: string, name: string, shape: Shape3D): BodyMesh { + const cached = meshCache.get(shape); + if (cached) return { ...cached, id, name }; + const bb = shape.boundingBox; + const diag = Math.hypot(bb.width, bb.height, bb.depth) || 1; + const tolerance = Math.min(0.1, Math.max(0.001, diag * 0.0008)); + const angularTolerance = 0.25; + const m = shape.mesh({ tolerance, angularTolerance }); + const e = shape.meshEdges({ tolerance, angularTolerance }); + // Group order matches shape.faces / shape.edges order (verified); ids are hashes. + const mesh: BodyMesh = { + id, + name, + positions: new Float32Array(m.vertices), + normals: new Float32Array(m.normals), + indices: new Uint32Array(m.triangles), + faceGroups: m.faceGroups.map((g, i) => ({ start: g.start, count: g.count, face: i })), + edgePositions: new Float32Array(e.lines), + edgeGroups: e.edgeGroups.map((g, i) => ({ start: g.start, count: g.count, edge: i })), + faces: shape.faces.map(faceInfo), + edges: shape.edges.map(edgeInfo), + openEdges: openEdges(shape), + }; + meshCache.set(shape, mesh); + return mesh; +} + +/** + * Edges used by fewer than two faces: the body is not closed (watertight) + * there. Imported meshes and failed operations are the usual cause. + */ +function openEdges(shape: Shape3D): number[] { + const edges = shape.edges; + const buckets = new Map(); + edges.forEach((e, i) => { + const h = e.hashCode; + buckets.set(h, [...(buckets.get(h) ?? []), { e, i, n: 0 }]); + }); + const oc = getOC(); + for (const f of shape.faces) { + for (const fe of f.edges) { + const m = buckets.get(fe.hashCode)?.find((x) => x.e.isSame(fe)); + // A seam (cylinder/torus) belongs to its face twice but is listed once. + if (m) m.n += oc.BRep_Tool.IsClosed(fe.wrapped, f.wrapped) ? 2 : 1; + } + } + return [...buckets.values()].flat().filter((x) => x.n < 2).map((x) => x.i); +} + +// ------------------------------------------------------------------- helpers + +function need(bodies: Bodies, id: string): Shape3D { + const b = bodies.get(id); + if (!b) throw new Error("A body it uses no longer exists"); + return b; +} + +function isEmpty(shape: AnyShape): boolean { + try { + return (shape as Shape3D).faces.length === 0; + } catch { + return true; + } +} + +/** Pattern copies are named `${featureId}:${body}:${k}`. */ +function baseId(bodyId: string): string { + return bodyId.split(":")[0]; +} + +function nameOf(features: Feature[], bodyId: string): string { + const f = features.find((x) => x.id === baseId(bodyId)); + if (!f) return "Body"; + if (f.type === "import") return f.fileName; + const k = bodyId.split(":")[2]; + return k ? `Body (${f.name} #${Number(k) + 2})` : `Body (${f.name})`; +} + +export function errorText(err: unknown): string { + if (err instanceof Error) return err.message; + if (typeof err === "number") return "The geometry kernel could not compute this (try other values)"; + return String(err); +} diff --git a/src/kernel/faceEdit.ts b/src/kernel/faceEdit.ts new file mode 100644 index 0000000..b1e2007 --- /dev/null +++ b/src/kernel/faceEdit.ts @@ -0,0 +1,472 @@ +// Direct face editing with booleans: offset a face (neighbours extend along their +// own surfaces), move/tilt a flat face, delete a face (neighbours close the gap). +// +// The trick: near face F the body equals E ∩ "behind F", where E is the +// intersection of the *extended* neighbouring surfaces — each taken on the side +// the body is on (planes → half-spaces, cylinders → infinite cylinders). Changing +// F then only means adding/removing the right slab of E. + +import { assembleWire, basicFaceExtrusion, getOC, loft, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, measureArea, measureVolume, cast, Vector, type Face, type Shape3D } from "replicad"; +import type { PlaneDef, Vec3 } from "../doc/types"; +import { add, cross, dist, dot, len, norm, scale, sub, xDirFor } from "../geom"; + +interface Cyl { + c: Vec3; + a: Vec3; + r: number; + /** +1: material inside (boss), −1: material outside (hole). */ + s: number; +} + +const tup = (v: { toTuple(): number[] }) => v.toTuple() as Vec3; + +function sizeOf(body: Shape3D): number { + const bb = body.boundingBox; + return Math.hypot(bb.width, bb.height, bb.depth) || 1; +} + +// Each helper solid gets a slightly different size: when two of them end on the +// same far-away plane, the booleans split surfaces and they no longer re-merge. +let jitter = 0; +const vary = (L: number) => L * (1 + 0.0137 * (jitter = (jitter + 1) % 37)); + +/** Solid on the positive side of a plane, big enough for `L`. */ +export function halfSpace(plane: PlaneDef, L0: number): Shape3D { + const L = vary(L0); + const x = norm(plane.xDir); + const y = cross(plane.normal, x); + const o = plane.origin; + const corner = (u: number, v: number): Vec3 => add(o, add(scale(x, u * L), scale(y, v * L))); + // Off-centre on purpose (see `vary`). + const face = makePolygon([corner(-1.09, -0.93), corner(0.97, -0.93), corner(0.97, 1.05), corner(-1.09, 1.05)]); + return basicFaceExtrusion(face, new Vector(plane.normal).multiply(L)); +} + +/** Axis, radius and orientation of a cylindrical face (from surface samples). */ +export function cylinderOf(f: Face): Cyl | null { + if (f.geomType !== "CYLINDRE") return null; + // pointOnSurface takes UV normalised to the face's bounds. + const at = (u: number, v: number) => { + const p = tup(f.pointOnSurface(u, v)); + return { p, n: norm(tup(f.normalAt(p))) }; + }; + // Two points at the same height, apart around the axis. + const s1 = at(0.25, 0.5); + const s2 = at(0.6, 0.5); + const ax = cross(s1.n, s2.n); + if (len(ax) < 1e-9) return null; + const a = norm(ax); + const dn = len(sub(s1.n, s2.n)); + const r = len(sub(s1.p, s2.p)) / (dn || 1); + // Normals point away from the axis on a boss, towards it in a hole. + const cOut = sub(s1.p, scale(s1.n, r)); + const cIn = add(s1.p, scale(s1.n, r)); + const out2 = sub(s2.p, scale(s2.n, r)); + const s = dist(cOut, out2) < dist(cIn, add(s2.p, scale(s2.n, r))) ? 1 : -1; + const c = s > 0 ? cOut : cIn; + return { c, a, r, s }; +} + +/** + * A point that lies on face F itself (its center may be off the face — e.g. on + * a cylinder's axis or inside a ring) and the outward normal there. + */ +export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } { + // Curved faces: the middle of the face's own parameter range sits well inside + // it (a fillet's mid-arc), away from the edges where its neighbours start. + if (F.geomType !== "PLANE") { + const p = tup(F.pointOnSurface(0.5, 0.5)); + return { p, n: norm(tup(F.normalAt(p))) }; + } + let t = F.triangulation(); + if (!t || !t.trianglesIndexes.length) { + body.mesh({ tolerance: sizeOf(body) * 1e-3, angularTolerance: 0.3 }); + t = F.triangulation(); + } + if (t && t.trianglesIndexes.length) { + // Centroid of the biggest triangle: well inside the face. + const v = (i: number): Vec3 => [t!.vertices[3 * i], t!.vertices[3 * i + 1], t!.vertices[3 * i + 2]]; + let best: Vec3 = v(0); + let area = -1; + for (let k = 0; k < t.trianglesIndexes.length; k += 3) { + const [a, b, c] = [0, 1, 2].map((j) => v(t!.trianglesIndexes[k + j])); + const ar = len(cross(sub(b, a), sub(c, a))); + if (ar > area) { + area = ar; + best = scale(add(add(a, b), c), 1 / 3); + } + } + return { p: best, n: norm(tup(F.normalAt(best))) }; + } + const p = tup(F.pointOnSurface(0.5, 0.5)); + return { p, n: norm(tup(F.normalAt(p))) }; +} + +/** The exact plane of a flat face (a surface point, not a mesh point). */ +export function planeOf(F: Face): PlaneDef { + const origin = tup(F.pointOnSurface(0.5, 0.5)); + const normal = norm(tup(F.normalAt(origin))); + return { origin, normal, xDir: xDirFor(normal) }; +} + +function infiniteCylinder(cy: Cyl, r: number, L0: number): Shape3D { + const L = vary(L0); + return makeCylinder(r, 2 * L, sub(cy.c, scale(cy.a, L)), cy.a) as Shape3D; +} + +/** Faces sharing an edge with F. */ +function neighbours(body: Shape3D, F: Face): Face[] { + const edges = F.edges; + return body.faces.filter((g) => !g.isSame(F) && g.edges.some((e) => edges.some((fe) => fe.isSame(e)))); +} + +/** + * E: the region bounded by F's neighbours' extended surfaces, each on the side + * that contains `q` (a point just inside the body under F). Bounded by a box. + */ +export function extendedRegion(body: Shape3D, F: Face, q: Vec3, L: number): Shape3D { + const c = body.boundingBox.center as Vec3; + // Bounding box, bigger than the other tools so no faces coincide with theirs. + const big = () => halfSpace({ origin: sub(c, [0, 0, 1.5 * L]), xDir: [1, 0, 0], normal: [0, 0, 1] }, 3 * L); + const keep: Shape3D[] = []; + const remove: Shape3D[] = []; + for (const g of neighbours(body, F)) { + if (g.geomType === "PLANE") { + const { origin: p, normal: n } = planeOf(g); + // Keep the side of g's plane that contains q. + const side = dot(sub(q, p), n) < 0 ? scale(n, -1) : n; + keep.push(halfSpace({ origin: p, normal: side, xDir: xDirFor(side) }, L)); + } else if (g.geomType === "CYLINDRE") { + const cy = cylinderOf(g); + if (!cy) continue; + const rel = sub(q, cy.c); + const radial = len(sub(rel, scale(cy.a, dot(rel, cy.a)))); + (radial < cy.r ? keep : remove).push(infiniteCylinder(cy, cy.r, L)); + } + // Other surface types are left unbounded (rare next to a face being edited). + } + let E = keep.length ? keep[0] : big(); + for (const k of keep.slice(1)) E = E.intersect(k); + for (const r of remove) E = E.cut(r); + return E; +} + +/** + * Replace flat face F's plane with `to` (move/tilt); neighbours extend or trim. + * Round blends (fillets) on F are taken off first and put back at the same + * radius afterwards — extending a fillet's cylinder through the body would + * carve a tunnel into it. + */ +export function replaceFacePlane(body: Shape3D, F: Face, to: PlaneDef): Shape3D { + if (F.geomType !== "PLANE") throw new Error("Only flat faces can be moved or tilted"); + const blends = blendsOf(body, F); + if (blends.length) { + try { + return aroundBlends(body, F, blends, to); + } catch { + // Couldn't rebuild the fillets: fall back to editing straight through them. + } + } + return replacePlaneDirect(body, F, to); +} + +interface Blend { + r: number; + /** The two flat faces the fillet runs between; `null` stands for the face being moved. */ + sides: [PlaneDef | null, PlaneDef]; + /** The blend's own signature, to find it again after earlier edits. */ + sig: { center: Vec3; area: number }; +} + +/** Is cylinder `cy` tangent to plane `pl` (a fillet's support face)? */ +function tangentTo(cy: Cyl, pl: PlaneDef, tol: number): boolean { + return Math.abs(dot(cy.a, pl.normal)) < 1e-6 && Math.abs(Math.abs(dot(sub(cy.c, pl.origin), pl.normal)) - cy.r) < cy.r * 1e-4 + tol; +} + +/** + * Fillets touching F: round faces next to it that run between two flat faces + * (F itself may be one of them). They get taken off and put back around an edit. + */ +function blendsOf(body: Shape3D, F: Face): Blend[] { + const tol = sizeOf(body) * 1e-7; + const out: Blend[] = []; + for (const g of neighbours(body, F)) { + if (g.geomType !== "CYLINDRE") continue; + const cy = cylinderOf(g); + if (!cy) continue; + const supports = neighbours(body, g).filter((h) => h.geomType === "PLANE" && tangentTo(cy, planeOf(h), tol)); + if (supports.length !== 2) continue; + const planes = supports.map((h) => (h.isSame(F) ? null : planeOf(h))); + // Keep F (if it is one) first. + const sides = (planes[1] === null ? [planes[1], planes[0]] : planes) as [PlaneDef | null, PlaneDef]; + if (sides[1] === null) continue; + out.push({ r: cy.r, sides, sig: { center: tup(g.center), area: measureArea(g) } }); + } + return out; +} + +function aroundBlends(body: Shape3D, F: Face, blends: Blend[], to: PlaneDef): Shape3D { + const fp = planeOf(F); + let b = body; + // 1. Take the fillets off (their faces meet in sharp edges again). + for (const bl of blends) { + const g = findFace(b, (h) => h.geomType === "CYLINDRE", bl.sig.center, bl.sig.area); + if (!g) throw new Error("blend lost"); + b = deleteFace(b, g); + } + // 2. Move the face, now bounded by flat neighbours only. + const F1 = findFace(b, (h) => h.geomType === "PLANE" && Math.abs(dot(planeOf(h).normal, fp.normal)) > 1 - 1e-9 && Math.abs(dot(sub(planeOf(h).origin, fp.origin), fp.normal)) < sizeOf(b) * 1e-7, tup(F.center), measureArea(F)); + if (!F1) throw new Error("face lost"); + b = replacePlaneDirect(b, F1, to); + // 3. Round the edges between each fillet's two faces again, same radius. + const moved: PlaneDef = { ...to, normal: norm(to.normal) }; + const tol = sizeOf(b) * 1e-6; + const on = (m: Vec3, pl: PlaneDef) => Math.abs(dot(sub(m, pl.origin), norm(pl.normal))) < tol; + for (const bl of blends) { + const p1 = bl.sides[0] ?? moved; + const p2 = bl.sides[1]; + const edges = b.edges.filter((e) => { + const m = tup(e.pointAt(0.5)); + return on(m, p1) && on(m, p2); + }); + if (!edges.length) throw new Error("edge lost"); + b = b.fillet(bl.r, (finder) => finder.inList(edges)) as Shape3D; + } + return sanity(body, b); +} + +/** The face that passes `ok`, nearest a remembered centre (and area). */ +function findFace(body: Shape3D, ok: (f: Face) => boolean, center: Vec3, area: number): Face | null { + let best: { f: Face; s: number } | null = null; + const size = Math.sqrt(area) || 1; + for (const f of body.faces) { + if (!ok(f)) continue; + const s = dist(tup(f.center), center) / size + Math.abs(Math.log((measureArea(f) + 1e-12) / (area + 1e-12))); + if (!best || s < best.s) best = { f, s }; + } + return best?.f ?? null; +} + +function replacePlaneDirect(body: Shape3D, F: Face, to: PlaneDef): Shape3D { + const L = sizeOf(body) * 4; + const { p, n } = onFace(body, F); + const q = sub(p, scale(n, sizeOf(body) * 1e-3)); + const E = extendedRegion(body, F, q, L); + const behind = (pl: PlaneDef) => halfSpace({ ...pl, normal: scale(pl.normal, -1), xDir: xDirFor(scale(pl.normal, -1)) }, L); + const front = (pl: PlaneDef) => halfSpace(pl, L); + const old = planeOf(F); + const neu: PlaneDef = { ...to, normal: norm(to.normal), xDir: xDirFor(norm(to.normal)) }; + let out = body; + const grow = E.intersect(front(old)).intersect(behind(neu)); + if (!isEmpty(grow)) out = out.fuse(grow); + const shrink = E.intersect(behind(old)).intersect(front(neu)); + if (!isEmpty(shrink)) out = out.cut(shrink); + return sanity(body, out); +} + +/** + * Neighbours that the half-space trick can't extend: curved surfaces other + * than cylinders standing straight on F (cones, lofted and revolved sides…). + */ +function needsContinuation(body: Shape3D, F: Face): boolean { + const n = planeOf(F).normal; + return neighbours(body, F).some((g) => { + if (g.geomType === "PLANE") return false; + if (g.geomType === "CYLINDRE") { + const cy = cylinderOf(g); + // Upright walls, or fillets running along F (taken off and put back). + return !cy || (Math.abs(Math.abs(dot(cy.a, n)) - 1) > 1e-6 && Math.abs(dot(cy.a, n)) > 1e-6); + } + return true; + }); +} + +/** + * Offset flat face F by d when its neighbours are curved: each point of F's + * outline carries on along its neighbour surface (the way that surface is + * heading there) until it is d further out; the slab between the old and the + * new outline is added (d > 0) or taken away (d < 0). + */ +function offsetByContinuation(body: Shape3D, F: Face, d: number): Shape3D { + const fp = planeOf(F); + const n = fp.normal; + const size = sizeOf(body); + const tol = size * 1e-6; + const nbrs = neighbours(body, F); + // F's outline as a loop of edges, end to end. + const edges = F.clone().outerWire().edges; + const ends = (e: { startPoint: { toTuple(): number[] }; endPoint: { toTuple(): number[] } }): [Vec3, Vec3] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3]; + const order: { k: number; rev: boolean }[] = [{ k: 0, rev: false }]; + const used = new Set([0]); + let at = ends(edges[0])[1]; + while (used.size < edges.length) { + const k = edges.findIndex((e, i) => !used.has(i) && ends(e).some((q) => dist(q, at) < tol * 10)); + if (k < 0) throw new Error("outline not closed"); + used.add(k); + const [a, b] = ends(edges[k]); + const rev = dist(b, at) < dist(a, at); + order.push({ k, rev }); + at = rev ? a : b; + } + // Where a point on edge k goes: along its neighbour, across the edge, out of F's plane. + // Cutting: the cutter reaches a hair past the walls and above F, so no sliver stays on the coincident surfaces. + const eps = d < 0 ? size * 1e-4 : 0; + const outward = (k: number, t: number): Vec3 => { + const e = edges[k]; + const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)))!; + const ng = norm(tup(g.normalAt(tup(e.pointAt(t))))); + const flat = sub(ng, scale(n, dot(ng, n))); + return len(flat) < 1e-9 ? [0, 0, 0] : scale(norm(flat), eps); + }; + const movedAt = (k: number, t: number): Vec3 => { + const e = edges[k]; + const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e))); + if (!g) throw new Error("no neighbour"); + const p = tup(e.pointAt(t)); + const dt = 1e-3; + const tangent = norm(sub(tup(e.pointAt(Math.min(1, t + dt))), tup(e.pointAt(Math.max(0, t - dt))))); + // Just inside the edge on g: its normal there (exactly on the edge it can be the other face's). + const ng = norm(tup(g.normalAt(p))); + let dir = norm(cross(ng, tangent)); + if (dot(dir, n) < 0) dir = scale(dir, -1); + const rise = dot(dir, n); + if (rise < 0.15) throw new Error("neighbour runs along the face"); + return add(add(p, scale(dir, d / rise)), outward(k, t)); + }; + const liftedAt = (k: number, t: number): Vec3 => add(add(tup(edges[k].pointAt(t)), scale(n, eps)), outward(k, t)); + // Corners: shared by two edges, moved the same way for both (halfway between their two estimates). + const m = order.length; + const corner: Vec3[] = order.map(({ k, rev }, i) => { + const prev = order[(i - 1 + m) % m]; + const a = movedAt(k, rev ? 1 : 0); + const b = movedAt(prev.k, prev.rev ? 0 : 1); + return scale(add(a, b), 0.5); + }); + const lowerCorner: Vec3[] = order.map(({ k, rev }) => liftedAt(k, rev ? 1 : 0)); + const lowerEdges = eps + ? order.map(({ k, rev }, i) => { + // Cutting: F's outline nudged up and out (see eps). + const c0 = lowerCorner[i]; + const c1 = lowerCorner[(i + 1) % m]; + if (edges[k].geomType === "LINE") return makeLine(c0, c1); + const pts: Vec3[] = []; + for (let j = 0; j <= 24; j++) pts.push(liftedAt(k, rev ? 1 - j / 24 : j / 24)); + pts[0] = c0; + pts[24] = c1; + return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 }); + }) + : order.map(({ k }) => edges[k].clone()); + const upperEdges = order.map(({ k, rev }, i) => { + const e = edges[k]; + const c0 = corner[i]; + const c1 = corner[(i + 1) % m]; + if (e.geomType === "LINE") return makeLine(c0, c1); + // A curved edge: a smooth curve through its moved points. + const pts: Vec3[] = []; + for (let j = 0; j <= 24; j++) pts.push(movedAt(k, rev ? 1 - j / 24 : j / 24)); + pts[0] = c0; + pts[24] = c1; + return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 }); + }); + const a = assembleWire(lowerEdges); + const b = assembleWire(upperEdges); + const slab = loft(d > 0 ? [a, b] : [b, a], { ruled: true }); + const out = d > 0 ? body.fuse(slab) : body.cut(slab); + return sanity(body, out); +} + +/** Offset a face along its normal: flat faces move, cylinders change radius. */ +export function offsetFace(body: Shape3D, F: Face, d: number): Shape3D { + if (F.geomType === "PLANE" && needsContinuation(body, F)) { + try { + return offsetByContinuation(body, F, d); + } catch { + // fall through to the plane trick + } + } + if (F.geomType === "PLANE") { + const { origin, normal } = planeOf(F); + return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) }); + } + const cy = cylinderOf(F); + if (!cy) throw new Error("Offset works on flat and cylindrical faces"); + const r2 = cy.r + cy.s * d; + if (r2 <= 1e-6) throw new Error("That offset would remove the whole round face"); + const L = sizeOf(body) * 4; + // q: just inside the material next to the face. + const { p, n } = onFace(body, F); + const q = sub(p, scale(n, sizeOf(body) * 1e-3)); + const E = extendedRegion(body, F, q, L); + const ring = infiniteCylinder(cy, Math.max(cy.r, r2), L).cut(infiniteCylinder(cy, Math.min(cy.r, r2), L)); + const slab = E.intersect(ring); + if (isEmpty(slab)) throw new Error("Nothing to offset"); + return sanity(body, d > 0 ? body.fuse(slab) : body.cut(slab)); +} + +/** Remove a face; its neighbours extend to close the gap (fillets, chamfers, holes). */ +export function deleteFace(body: Shape3D, F: Face): Shape3D { + const L = sizeOf(body) * 4; + const { p, n } = onFace(body, F); + const q = sub(p, scale(n, sizeOf(body) * 1e-3)); + // Only fill within the face's own box: the gap a face leaves lies inside it, and + // any slack either falls inside the material or is cut off by a neighbour. + const b = F.boundingBox; + const lo = b.bounds[0] as number[]; + const hi = b.bounds[1] as number[]; + const pad = sizeOf(body) * 1e-3; + const box = makePolygon([ + [lo[0] - pad, lo[1] - pad, lo[2] - pad], + [hi[0] + pad, lo[1] - pad, lo[2] - pad], + [hi[0] + pad, hi[1] + pad, lo[2] - pad], + [lo[0] - pad, hi[1] + pad, lo[2] - pad], + ]); + const local = basicFaceExtrusion(box, new Vector([0, 0, hi[2] - lo[2] + 2 * pad])); + const region = extendedRegion(body, F, q, L).intersect(local); + // Still has the face (or a copy of it a hair away): that way doesn't close the gap. + const fn = norm(tup(F.normalAt())); + const gone = (out: Shape3D) => + !out.faces.some((g) => g.geomType === F.geomType && dot(norm(tup(g.normalAt())), fn) > 0.999 && dist(tup(g.center), tup(F.center)) < sizeOf(body) * 0.02); + // A face on an outside corner (convex fillet, chamfer, hole wall) left material + // out: fill it back in. One in an inside corner (concave fillet) added material: + // take it away. Both are tried; the smallest change that removes the face wins. + const v0 = measureVolume(body); + const tries: { out: Shape3D; change: number }[] = []; + for (const make of [() => body.fuse(region), () => body.cut(region)]) { + try { + const out = unify(make()); + // Removing a face never needs new faces: one that adds some cut a new shape in. + if (!isEmpty(out) && gone(out) && out.faces.length < body.faces.length) tries.push({ out, change: Math.abs(measureVolume(out) - v0) }); + } catch { + // that way doesn't work here + } + } + if (!tries.length) throw new Error("This face can't be removed — its neighbours don't close the gap"); + tries.sort((a, b) => a.change - b.change); + return sanity(body, tries[0].out); +} + +/** Merge faces/edges that lie on the same surface (removes imprinted edges). */ +export function unify(body: Shape3D): Shape3D { + const oc = getOC(); + const u = new oc.ShapeUpgrade_UnifySameDomain(body.wrapped, true, true, false); + // Surfaces rebuilt from samples match the originals only to ~1e-9 relative. + u.SetLinearTolerance(sizeOf(body) * 1e-6); + u.SetAngularTolerance(1e-6); + u.Build(); + return cast(u.Shape()) as Shape3D; +} + +function isEmpty(s: Shape3D): boolean { + try { + return s.faces.length === 0; + } catch { + return true; + } +} + +/** Reject results that exploded (an unbounded region leaked out). */ +function sanity(before: Shape3D, after: Shape3D): Shape3D { + if (isEmpty(after)) throw new Error("The result would be empty"); + if (sizeOf(after) > sizeOf(before) * 3 + 1) throw new Error("This change can't be made cleanly here (the neighbouring faces don't enclose it)"); + return unify(after); +} diff --git a/src/kernel/freeform.ts b/src/kernel/freeform.ts new file mode 100644 index 0000000..15db581 --- /dev/null +++ b/src/kernel/freeform.ts @@ -0,0 +1,91 @@ +// Freeform cage → OpenCascade shape: each subdivided cage quad becomes one +// bicubic B-spline face interpolating its grid of points; faces are sewn and, +// when the cage is closed, made into a solid. + +import { cast, getOC, measureVolume, type Shape3D } from "replicad"; +import { cubicKnots, interpolateGrid } from "../freeform/bspline"; +import { isClosed, subdivide, type Cage } from "../freeform/cage"; + +export interface Thicken { + thickness: number; + side: "up" | "down" | "both"; +} + +export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken): Shape3D { + if (!cage.faces.length) throw new Error("The freeform has no faces"); + const oc = getOC(); + const s = subdivide(cage, levels); + const N = s.n + 1; + const tol = Math.max(1e-4, sizeOf(s.points) * 1e-5); + const sewing = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false); + const gc: { delete(): void }[] = [sewing]; + // Shared by every patch: same size, same uniform parameters. + const k = cubicKnots(N); + const uKnots = new oc.NCollection_Array1_double(1, k.knots.length); + const uMults = new oc.NCollection_Array1_int(1, k.mults.length); + k.knots.forEach((x, i) => uKnots.SetValue(i + 1, x)); + k.mults.forEach((x, i) => uMults.SetValue(i + 1, x)); + gc.push(uKnots, uMults); + for (const g of s.grids) { + // Our own uniform interpolation: patches with the same border points get + // identical border curves, so they sew exactly. + const poles = interpolateGrid(g.map((row) => row.map((i) => s.points[i]))); + const arr = new oc.NCollection_Array2_gp_Pnt(1, N, 1, N); + gc.push(arr); + for (let i = 0; i < N; i++) + for (let j = 0; j < N; j++) { + const p = poles[i][j]; + const pt = new oc.gp_Pnt(p[0], p[1], p[2]); + arr.SetValue(i + 1, j + 1, pt); + pt.delete(); + } + const surf = new oc.Geom_BSplineSurface(arr, uKnots, uKnots, uMults, uMults, 3, 3, false, false); + const mk = new oc.BRepBuilderAPI_MakeFace(surf, 1e-6); + gc.push(mk); + sewing.Add(mk.Face()); + } + sewing.Perform(); + const sewed = sewing.SewedShape(); + try { + if (isClosed(cage)) { + if (sewed.ShapeType() !== oc.TopAbs_ShapeEnum.TopAbs_SHELL) throw new Error("The freeform surfaces didn't close up into one piece"); + const fix = new oc.ShapeFix_Solid(); + gc.push(fix); + const solid = cast(fix.SolidFromShell(oc.TopoDS.Shell(sewed))); + return solid as Shape3D; + } + if (thicken && thicken.thickness > 0) return thickenSheet(sewed, thicken); + return cast(sewed) as Shape3D; + } finally { + for (const o of gc) o.delete(); + } +} + +/** An open sheet → a solid: grown along its normals (up), against them (down) or half each way. */ +function thickenSheet(sheet: unknown, { thickness: t, side }: Thicken): Shape3D { + const oc = getOC(); + const thick = (d: number): Shape3D => { + const mk = new oc.BRepOffsetAPI_MakeThickSolid(); + try { + mk.MakeThickSolidBySimple(sheet as never, d); + const solid = cast(mk.Shape()) as Shape3D; + // Growing along the normals comes out inside-out: turn it the right way. + return measureVolume(solid) < 0 ? (cast(solid.wrapped.Reversed()) as Shape3D) : solid; + } finally { + mk.delete(); + } + }; + if (side === "up") return thick(t); + if (side === "down") return thick(-t); + return thick(t / 2).fuse(thick(-t / 2)); +} + +function sizeOf(pts: number[][]): number { + let lo = [Infinity, Infinity, Infinity]; + let hi = [-Infinity, -Infinity, -Infinity]; + for (const p of pts) { + lo = lo.map((v, k) => Math.min(v, p[k])); + hi = hi.map((v, k) => Math.max(v, p[k])); + } + return Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1; +} diff --git a/src/kernel/protocol.ts b/src/kernel/protocol.ts new file mode 100644 index 0000000..483e484 --- /dev/null +++ b/src/kernel/protocol.ts @@ -0,0 +1,84 @@ +// Messages between the main thread and the kernel worker. This file is the +// whole contract: the UI never touches kernel objects directly. + +import type { Feature, PlaneDef, SketchEntity, Vec3 } from "../doc/types"; + +export interface FaceInfo { + center: Vec3; + normal: Vec3; + area: number; + /** OpenCascade surface type: PLANE, CYLINDRE (sic), CONE, SPHERE, BSPLINE_SURFACE… */ + type: string; + /** Set for flat faces: the plane a sketch on this face would use. */ + plane?: PlaneDef; +} + +export interface EdgeInfo { + mid: Vec3; + dir: Vec3; + length: number; + start: Vec3; + end: Vec3; + /** LINE, CIRCLE, ELLIPSE, BSPLINE_CURVE… */ + type: string; +} + +export interface BodyMesh { + id: string; + name: string; + positions: Float32Array; + normals: Float32Array; + indices: Uint32Array; + /** Triangle ranges (in index units) per face. */ + faceGroups: { start: number; count: number; face: number }[]; + /** Line-segment vertex pairs for all edges. */ + edgePositions: Float32Array; + /** Ranges (in vertex units of edgePositions) per edge. */ + edgeGroups: { start: number; count: number; edge: number }[]; + faces: FaceInfo[]; + edges: EdgeInfo[]; + /** Edges with fewer than two faces: the body isn't closed there (not watertight). */ + openEdges: number[]; +} + +/** A construction plane or axis (for an axis, plane.normal is its direction). */ +export interface ConstructionInfo { + id: string; + name: string; + plane: PlaneDef; +} + +export interface FeatureError { + featureId: string; + message: string; +} + +export interface RegenResult { + bodies: BodyMesh[]; + /** Current plane of every sketch (sketches on faces follow the face). */ + sketchPlanes: Record; + /** Outline of the face each face-attached sketch sits on (takes part in its regions). */ + sketchBoundaries: Record; + planes: ConstructionInfo[]; + axes: ConstructionInfo[]; + errors: FeatureError[]; + ms: number; +} + +export type ExportFormat = "stl" | "step"; + +export type Request = + | { type: "init" } + | { type: "regenerate"; features: Feature[] } + | { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] }; + +export type Response = + | { type: "ready" } + | { type: "regenerated"; result: RegenResult } + | { type: "exported"; blob: Blob } + | { type: "error"; message: string }; + +export interface Envelope { + id: number; + msg: T; +} diff --git a/src/kernel/sketchGeom.ts b/src/kernel/sketchGeom.ts new file mode 100644 index 0000000..1409ba0 --- /dev/null +++ b/src/kernel/sketchGeom.ts @@ -0,0 +1,167 @@ +// Sketch regions → exact OpenCascade geometry (worker only). + +import { + addHolesInFace, + assembleWire, + cast, + getOC, + makeBSplineApproximation, + makeCircle, + makeEllipse, + makeFace, + makeLine, + makeThreePointArc, + type Edge, + type Face, + type Wire, +} from "replicad"; +import type { PlaneDef, SketchEntity, Vec2 } from "../doc/types"; +import { toWorld } from "../geom"; +import { entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineSpanAt, splineSpans, type Prim } from "../sketch/curves"; +import { arrangement, resolveRegion, type Arrangement, type Loop, type Piece, type RegionRef } from "../sketch/regions"; + +/** Faces for the referenced regions of a sketch (one face per region, holes included). */ +export function regionFaces(entities: SketchEntity[], plane: PlaneDef, refs: RegionRef[]): Face[] { + const arr = arrangement(entities); + return refs.map((ref) => { + const r = resolveRegion(arr, ref); + if (!r) throw new Error("A profile it used no longer exists in its sketch"); + const face = makeFace(loopWire(arr, r.outer, plane)); + // addHolesInFace orients hole wires correctly (makeFace's holes arg does not). + return r.holes.length ? addHolesInFace(face, r.holes.map((h) => loopWire(arr, h, plane))) : face; + }); +} + +/** Outer wire of a region (for sweeps/lofts that need a wire). */ +export function regionWire(entities: SketchEntity[], plane: PlaneDef, ref: RegionRef): Wire { + const arr = arrangement(entities); + const r = resolveRegion(arr, ref); + if (!r) throw new Error("A profile it used no longer exists in its sketch"); + return loopWire(arr, r.outer, plane); +} + +/** A wire along sketch entities (open or closed), used as a sweep path. */ +export function entitiesWire(entities: SketchEntity[], ids: string[], plane: PlaneDef): Wire { + const edges: Edge[] = []; + for (const id of ids) { + const e = entities.find((x) => x.id === id); + if (!e) throw new Error("A path curve was deleted"); + for (const p of entityPrims(e)) { + if (p.t === "line") edges.push(makeLine(toWorld(plane, p.a), toWorld(plane, p.b))); + else if (p.t === "circle" && isClosedPrim(p)) edges.push(makeCircle(p.r, toWorld(plane, p.c), plane.normal)); + else if (p.t === "circle") edges.push(makeThreePointArc(w(plane, evalPrim(p, 0)), w(plane, evalPrim(p, 0.5)), w(plane, evalPrim(p, 1)))); + else edges.push(exactSpline(p, 0, 1, plane) ?? bspline(Array.from({ length: 65 }, (_, i) => evalPrim(p, i / 64)), plane)); + } + } + return assembleWire(edges); +} + +function loopWire(arr: Arrangement, loop: Loop, plane: PlaneDef): Wire { + // A loop that is a whole circle/ellipse on its own: use the exact closed curve. + const prims = new Set(loop.pieces.map((r) => arr.pieces[r.piece].prim)); + if (prims.size === 1) { + const p = arr.prims[[...prims][0]]; + if (p.t === "circle" && isClosedPrim(p)) return assembleWire([makeCircle(p.r, toWorld(plane, p.c), plane.normal)]); + if (p.t === "ellipse" && isClosedPrim(p)) { + const major = p.rx >= p.ry; + const rot = p.rot + (major ? 0 : Math.PI / 2); + const xDir = toWorld({ ...plane, origin: [0, 0, 0] }, [Math.cos(rot), Math.sin(rot)]); + return assembleWire([makeEllipse(Math.max(p.rx, p.ry), Math.min(p.rx, p.ry), toWorld(plane, p.c), plane.normal, xDir)]); + } + } + return assembleWire(loop.pieces.map((r) => pieceEdge(arr, arr.pieces[r.piece], plane))); +} + +function pieceEdge(arr: Arrangement, pc: Piece, plane: PlaneDef): Edge { + const p = arr.prims[pc.prim]; + const a = pc.poly[0]; + const b = pc.poly[pc.poly.length - 1]; + switch (p.t) { + case "line": + return makeLine(w(plane, a), w(plane, b)); + case "circle": + // Through the (shared) end nodes, so neighbouring pieces meet exactly. + return makeThreePointArc(w(plane, a), w(plane, evalPrim(p, (pc.t0 + pc.t1) / 2)), w(plane, b)); + default: + return exactSpline(p, pc.t0, pc.t1, plane, a, b) ?? bspline(pc.poly, plane); + } +} + +/** + * The spline exactly as drawn, from parameter t0 to t1: each span of the + * sketch spline is a cubic, so it becomes one Bezier piece of a C1 B-spline — + * no fitting, so no ripples (in revolves and lofts especially). + * `a`/`b` pin the ends onto the arrangement's nodes so neighbours meet. + */ +function exactSpline(p: Prim, t0: number, t1: number, plane: PlaneDef, a?: Vec2, b?: Vec2): Edge | null { + if (p.t !== "spline" || !p.ctrl) return null; + const spans = splineSpans(p.ctrl); + const n = p.pts.length - 1; + if (n !== spans * SPLINE_PER_SPAN) return null; + // Closed pieces can run past the seam (t1 > 1). + const f0 = t0 * spans; + const f1 = t1 * spans; + if (f1 - f0 < 1e-9) return null; + // Span s (wrapping round a closed spline) at local parameter u. + const spanAt = (s: number, u: number): Vec2 => splineSpanAt(p.ctrl!, ((s % spans) + spans) % spans, u); + // Break at the span joints inside [f0, f1]. + const cuts = [f0]; + for (let k = Math.floor(f0) + 1; k < f1 - 1e-9; k++) if (k > f0 + 1e-9) cuts.push(k); + cuts.push(f1); + const poles: Vec2[] = []; + for (let i = 0; i < cuts.length - 1; i++) { + const [u0, u1] = [cuts[i], cuts[i + 1]]; + // A cubic through four of its own points is that cubic: solve for its Bezier. + // (Sampled inside the span, so a joint isn't read from the next span's formula.) + const s = Math.min(Math.floor(u0 + 1e-9), Math.ceil(u1 - 1e-9) - 1); + const q = [0, 1 / 3, 2 / 3, 1].map((x) => spanAt(s, u0 + (u1 - u0) * x - s)); + const P0 = q[0]; + const P3 = q[3]; + const A: Vec2 = [27 * q[1][0] - 8 * P0[0] - P3[0], 27 * q[1][1] - 8 * P0[1] - P3[1]]; + const B: Vec2 = [27 * q[2][0] - P0[0] - 8 * P3[0], 27 * q[2][1] - P0[1] - 8 * P3[1]]; + const P1: Vec2 = [(2 * A[0] - B[0]) / 18, (2 * A[1] - B[1]) / 18]; + const P2: Vec2 = [(2 * B[0] - A[0]) / 18, (2 * B[1] - A[1]) / 18]; + if (i === 0) poles.push(P0); + poles.push(P1, P2, P3); + } + if (a) poles[0] = a; + if (b) poles[poles.length - 1] = b; + const oc = getOC(); + const m = cuts.length - 1; + const arr = new oc.NCollection_Array1_gp_Pnt(1, poles.length); + const knots = new oc.NCollection_Array1_double(1, m + 1); + const mults = new oc.NCollection_Array1_int(1, m + 1); + try { + poles.forEach((q, i) => { + const w3 = w(plane, q); + const pt = new oc.gp_Pnt(w3[0], w3[1], w3[2]); + arr.SetValue(i + 1, pt); + pt.delete(); + }); + for (let i = 0; i <= m; i++) { + knots.SetValue(i + 1, i); + mults.SetValue(i + 1, i === 0 || i === m ? 4 : 3); + } + const curve = new oc.Geom_BSplineCurve(arr, knots, mults, 3, false); + const mk = new oc.BRepBuilderAPI_MakeEdge(curve); + const edge = cast(mk.Edge()) as Edge; + mk.delete(); + return edge; + } catch { + return null; + } finally { + arr.delete(); + knots.delete(); + mults.delete(); + } +} + +function bspline(pts: Vec2[], plane: PlaneDef): Edge { + // Thin out dense samples; the approximation is smooth anyway. + const step = Math.max(1, Math.floor(pts.length / 48)); + const kept = pts.filter((_, i) => i % step === 0 || i === pts.length - 1); + if (kept.length < 3) return makeLine(w(plane, kept[0]), w(plane, kept[kept.length - 1])); + return makeBSplineApproximation(kept.map((q) => w(plane, q)), { tolerance: 1e-4, degMax: 5, degMin: 2 }); +} + +const w = (plane: PlaneDef, q: Vec2) => toWorld(plane, q); diff --git a/src/kernel/worker.ts b/src/kernel/worker.ts new file mode 100644 index 0000000..e3135b7 --- /dev/null +++ b/src/kernel/worker.ts @@ -0,0 +1,30 @@ +/// +// Web Worker entry: loads OpenCascade and serves engine.ts over postMessage. + +import opencascade from "replicad-opencascadejs"; +import wasmUrl from "replicad-opencascadejs/wasm?url"; +import { setOC } from "replicad"; +import { errorText, exportBodies, regenerate } from "./engine"; +import type { Envelope, Request, Response } from "./protocol"; + +self.onmessage = async (e: MessageEvent>) => { + const { id, msg } = e.data; + const reply = (r: Response) => (self as DedicatedWorkerGlobalScope).postMessage({ id, msg: r } satisfies Envelope); + try { + switch (msg.type) { + case "init": + setOC(await opencascade({ locateFile: () => wasmUrl })); + reply({ type: "ready" }); + break; + case "regenerate": + reply({ type: "regenerated", result: await regenerate(msg.features) }); + break; + case "export": + reply({ type: "exported", blob: await exportBodies(msg.features, msg.format, msg.bodies) }); + break; + } + } catch (err) { + console.error(err); + reply({ type: "error", message: errorText(err) }); + } +}; diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..7cdbbb6 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,6 @@ +import "./style.css"; +import { App } from "./app"; + +const app = new App(document.getElementById("view") as HTMLCanvasElement); +// Handy for debugging from the console. +(window as unknown as { supergeometry: App }).supergeometry = app; diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..2859685 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,98 @@ +// Per-device preferences (not part of the project file). + +const KEY = "supergeometry.settings.v1"; +const OLD_KEY = "tessel.settings.v1"; + +export interface Settings { + snap: { + grid: boolean; + guidePoints: boolean; + guideLines: boolean; + points3d: boolean; + distantEdges: boolean; + }; + showGuidePoints: boolean; + showSnapHints: boolean; + gridLocked: boolean; + /** Grid step (mm) used when the grid is locked. */ + gridStep: number; + showGrid: boolean; + showAxes: boolean; + animateCamera: boolean; + ortho: boolean; + shader: "shaded" | "wireframe" | "xray"; + showEdges: boolean; + showHiddenEdges: boolean; + showPinned: boolean; + /** Sketch mode: show the constraint column. */ + showConstraints: boolean; + /** Sketch: add Horizontal/Vertical/Coincident automatically while drawing. */ + autoConstrain: boolean; + /** Sketch: draw the constraint badges (H, V, ∥, dimensions…) on the geometry. */ + showConstraintGlyphs: boolean; + /** Bumped when defaults change for everyone (see the constructor). */ + version: number; + /** Angle display: decimal degrees or degrees + minutes. */ + degrees: "decimal" | "fractional"; +} + +const DEFAULTS: Settings = { + snap: { grid: true, guidePoints: true, guideLines: true, points3d: true, distantEdges: false }, + showGuidePoints: true, + showSnapHints: true, + gridLocked: false, + gridStep: 1, + showGrid: true, + showAxes: true, + animateCamera: true, + ortho: true, + shader: "shaded", + showEdges: true, + showHiddenEdges: false, + showPinned: true, + degrees: "decimal", + showConstraints: true, + autoConstrain: true, + showConstraintGlyphs: true, + version: 2, +}; + +type Listener = (s: Settings) => void; + +class SettingsStore { + value: Settings; + private listeners = new Set(); + + constructor() { + let saved: Partial = {}; + try { + saved = JSON.parse(localStorage.getItem(KEY) ?? localStorage.getItem(OLD_KEY) ?? "{}"); + } catch { + // Unavailable storage just means defaults. + } + this.value = { ...DEFAULTS, ...saved, snap: { ...DEFAULTS.snap, ...(saved.snap ?? {}) } }; + // v2: orthographic view and the sketch constraint column are on by default — + // also for anyone whose saved preferences still hold the old defaults. + if ((saved.version ?? 1) < 2) this.value = { ...this.value, ortho: true, showConstraints: true, version: 2 }; + } + + set(key: K, v: Settings[K]): void { + this.value = { ...this.value, [key]: v }; + try { + localStorage.setItem(KEY, JSON.stringify(this.value)); + } catch { + // Ignore: preferences are a convenience. + } + this.listeners.forEach((fn) => fn(this.value)); + } + + onChange(fn: Listener): void { + this.listeners.add(fn); + } + + offChange(fn: Listener): void { + this.listeners.delete(fn); + } +} + +export const settings = new SettingsStore(); diff --git a/src/sketch/constraints.ts b/src/sketch/constraints.ts new file mode 100644 index 0000000..e4e99b6 --- /dev/null +++ b/src/sketch/constraints.ts @@ -0,0 +1,459 @@ +// Sketch constraint solver: every entity is a short parameter vector; each +// constraint is one or more residuals; Levenberg–Marquardt drives them to zero +// while a weak pull towards the current shape keeps under-constrained sketches +// from wandering (so the result is the smallest change that satisfies them). + +import type { ConstraintType, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types"; +import { arcFrom3, entityCorners } from "./curves"; + +// ------------------------------------------------------------- parameters + +/** Entity → flat parameter list (and back). */ +function params(e: SketchEntity): number[] { + switch (e.kind) { + case "line": + return [...e.a, ...e.b]; + case "arc": + return [...e.a, ...e.m, ...e.b]; + case "circle": + return [...e.center, e.radius]; + case "ellipse": + return [...e.center, e.rx, e.ry, e.rotation]; + case "rect": + return [...e.center, e.w, e.h, e.rotation]; + case "polygon": + return [...e.center, e.radius, e.angle]; + case "spline": + case "polyline": + return e.points.flat(); + } +} + +function withParams(e: SketchEntity, x: number[]): SketchEntity { + switch (e.kind) { + case "line": + return { ...e, a: [x[0], x[1]], b: [x[2], x[3]] }; + case "arc": + return { ...e, a: [x[0], x[1]], m: [x[2], x[3]], b: [x[4], x[5]] }; + case "circle": + return { ...e, center: [x[0], x[1]], radius: Math.abs(x[2]) }; + case "ellipse": + return { ...e, center: [x[0], x[1]], rx: Math.abs(x[2]), ry: Math.abs(x[3]), rotation: x[4] }; + case "rect": + return { ...e, center: [x[0], x[1]], w: Math.abs(x[2]), h: Math.abs(x[3]), rotation: x[4] }; + case "polygon": + return { ...e, center: [x[0], x[1]], radius: Math.abs(x[2]), angle: x[3] }; + case "spline": + case "polyline": { + const pts: Vec2[] = []; + for (let i = 0; i < x.length; i += 2) pts.push([x[i], x[i + 1]]); + return { ...e, points: pts }; + } + } +} + +/** Named points of an entity (what constraints can grab). */ +export function pointsOf(e: SketchEntity): { p: string; at: Vec2 }[] { + switch (e.kind) { + case "line": + return [{ p: "a", at: e.a }, { p: "b", at: e.b }]; + case "arc": { + const c = arcFrom3(e.a, e.m, e.b); + return [{ p: "a", at: e.a }, { p: "b", at: e.b }, ...(c ? [{ p: "c", at: c.c }] : [])]; + } + case "circle": + case "ellipse": + return [{ p: "c", at: e.center }]; + case "rect": + case "polygon": + return [{ p: "c", at: e.center }, ...entityCorners(e).map((at, i) => ({ p: `k${i}`, at }))]; + case "spline": + case "polyline": + return e.points.map((at, i) => ({ p: `k${i}`, at })); + } +} + +export function pointOf(e: SketchEntity, p: string): Vec2 | null { + return pointsOf(e).find((q) => q.p === p)?.at ?? null; +} + +/** Size of an entity by name, for dimension constraints and size fields. */ +export function sizeOf(e: SketchEntity, prop: string): number | null { + switch (prop) { + case "length": + if (e.kind === "line") return Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1]); + return null; + case "radius": + case "diameter": { + const r = e.kind === "circle" || e.kind === "polygon" ? e.radius : e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.r ?? null) : null; + return r === null ? null : prop === "diameter" ? 2 * r : r; + } + case "w": + return e.kind === "rect" ? e.w : null; + case "h": + return e.kind === "rect" ? e.h : null; + case "rx": + return e.kind === "ellipse" ? e.rx : null; + case "ry": + return e.kind === "ellipse" ? e.ry : null; + // Ellipse axis lengths (full widths, like a circle's diameter). + case "dx": + return e.kind === "ellipse" ? 2 * e.rx : null; + case "dy": + return e.kind === "ellipse" ? 2 * e.ry : null; + case "angle": + return e.kind === "line" ? (Math.atan2(e.b[1] - e.a[1], e.b[0] - e.a[0]) * 180) / Math.PI : null; + } + return null; +} + +/** Direction of a straight entity (line), or null. */ +function dirOf(e: SketchEntity): Vec2 | null { + if (e.kind !== "line") return null; + return [e.b[0] - e.a[0], e.b[1] - e.a[1]]; +} + +/** Centre and radius of round entities. */ +function roundOf(e: SketchEntity): { c: Vec2; r: number } | null { + if (e.kind === "circle") return { c: e.center, r: e.radius }; + if (e.kind === "arc") { + const a = arcFrom3(e.a, e.m, e.b); + return a ? { c: a.c, r: a.r } : null; + } + return null; +} + +// --------------------------------------------------------------- residuals + +type Lookup = (id: string) => SketchEntity | undefined; + +/** Residuals of one constraint (empty if it refers to something missing). */ +function residuals(c: SketchConstraint, get: Lookup): number[] { + const P = (r: PointRef) => { + const e = get(r.e); + return e ? pointOf(e, r.p) : null; + }; + const E = (i: number) => (c.curves?.[i] ? get(c.curves[i]) : undefined); + const unit = (v: Vec2) => { + const l = Math.hypot(v[0], v[1]) || 1; + return [v[0] / l, v[1] / l] as Vec2; + }; + switch (c.type) { + case "coincident": { + const [a, b] = (c.pts ?? []).map(P); + if (a && b) return [a[0] - b[0], a[1] - b[1]]; + // Point on a curve. + const e = E(0); + if (a && e) return [distToEntity(a, e)]; + return []; + } + case "horizontal": + case "vertical": { + const e = E(0); + const d = e && dirOf(e); + if (d) return [c.type === "horizontal" ? d[1] : d[0]]; + const [a, b] = (c.pts ?? []).map(P); + if (a && b) return [c.type === "horizontal" ? a[1] - b[1] : a[0] - b[0]]; + return []; + } + case "parallel": + case "perpendicular": { + const [d1, d2] = [E(0), E(1)].map((e) => (e ? dirOf(e) : null)); + if (!d1 || !d2) return []; + const u = unit(d1); + const v = unit(d2); + return [c.type === "parallel" ? u[0] * v[1] - u[1] * v[0] : u[0] * v[0] + u[1] * v[1]]; + } + case "equal": { + const [e1, e2] = [E(0), E(1)]; + if (!e1 || !e2) return []; + const s = (e: SketchEntity) => sizeOf(e, e.kind === "line" ? "length" : "radius"); + const a = s(e1); + const b = s(e2); + return a !== null && b !== null ? [a - b] : []; + } + case "tangent": { + const [e1, e2] = [E(0), E(1)]; + if (!e1 || !e2) return []; + const r1 = roundOf(e1); + const r2 = roundOf(e2); + const line = e1.kind === "line" ? e1 : e2.kind === "line" ? e2 : null; + const round = r1 ?? r2; + if (line && round) return [distPointLine(round.c, line.a, line.b) - round.r]; + if (r1 && r2) { + const d = Math.hypot(r1.c[0] - r2.c[0], r1.c[1] - r2.c[1]); + // External tangency unless one contains the other. + return [Math.min(Math.abs(d - (r1.r + r2.r)), Math.abs(d - Math.abs(r1.r - r2.r)))]; + } + return []; + } + case "concentric": { + const c1 = E(0) && centreOf(E(0)!); + const c2 = E(1) && centreOf(E(1)!); + return c1 && c2 ? [c1[0] - c2[0], c1[1] - c2[1]] : []; + } + case "midpoint": { + const a = c.pts?.[0] && P(c.pts[0]); + const e = E(0); + if (!a || e?.kind !== "line") return []; + return [a[0] - (e.a[0] + e.b[0]) / 2, a[1] - (e.a[1] + e.b[1]) / 2]; + } + case "symmetric": { + const [a, b] = (c.pts ?? []).map(P); + const e = E(0); + if (!a || !b || e?.kind !== "line") return []; + const m: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + const d = unit(dirOf(e)!); + // Midpoint on the line, and a–b perpendicular to it. + return [distPointLineSigned(m, e.a, e.b), (b[0] - a[0]) * d[0] + (b[1] - a[1]) * d[1]]; + } + case "fix": { + const a = c.pts?.[0] && P(c.pts[0]); + return a && c.at ? [a[0] - c.at[0], a[1] - c.at[1]] : []; + } + case "distance": { + if (c.value === undefined) return []; + // Point to line: perpendicular distance. + if (c.pts?.length === 1 && c.curves?.length === 1) { + const p = P(c.pts[0]); + const l = E(0); + return p && l?.kind === "line" ? [distPointLine(p, l.a, l.b) - c.value] : []; + } + const [a, b] = (c.pts ?? []).map(P); + return a && b ? [Math.hypot(a[0] - b[0], a[1] - b[1]) - c.value] : []; + } + case "dim": { + const e = E(0); + if (!e || !c.prop || c.value === undefined) return []; + if (c.prop === "angle" && c.curves?.length === 2) { + const d1 = dirOf(e); + const d2 = E(1) && dirOf(E(1)!); + if (!d1 || !d2) return []; + const ang = Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]); + return [wrap(Math.abs(ang) - (c.value * Math.PI) / 180)]; + } + const s = sizeOf(e, c.prop); + if (s === null) return []; + return c.prop === "angle" ? [wrap(((s - c.value) * Math.PI) / 180)] : [s - c.value]; + } + } +} + +function wrap(a: number): number { + while (a > Math.PI) a -= 2 * Math.PI; + while (a < -Math.PI) a += 2 * Math.PI; + return a; +} + +function centreOf(e: SketchEntity): Vec2 | null { + if (e.kind === "circle" || e.kind === "ellipse" || e.kind === "rect" || e.kind === "polygon") return e.center; + return roundOf(e)?.c ?? null; +} + +function distPointLine(p: Vec2, a: Vec2, b: Vec2): number { + return Math.abs(distPointLineSigned(p, a, b)); +} + +function distPointLineSigned(p: Vec2, a: Vec2, b: Vec2): number { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const l = Math.hypot(dx, dy) || 1; + return ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / l; +} + +function distToEntity(p: Vec2, e: SketchEntity): number { + if (e.kind === "line") return distPointLineSigned(p, e.a, e.b); + const r = roundOf(e); + if (r) return Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r; + return 0; +} + +// ------------------------------------------------------------------ solver + +export interface SolveOptions { + /** Points to pull towards a target (dragging), with a strong weight. */ + drag?: { ref: PointRef; to: Vec2 }[]; + /** Entities that must not move (e.g. the face outline). */ + fixed?: Set; +} + +export interface SolveResult { + entities: SketchEntity[]; + /** Largest remaining residual (≈0 when every constraint is met). */ + error: number; + ok: boolean; +} + +/** Solve constraints; returns updated entities (unchanged ones are kept). */ +export function solve(entities: SketchEntity[], constraints: SketchConstraint[], opts: SolveOptions = {}): SolveResult { + const live = constraints.filter((c) => refsOf(c).every((id) => entities.some((e) => e.id === id))); + if (!live.length && !opts.drag?.length) return { entities, error: 0, ok: true }; + // Only entities that take part move; everything else is left as is. + const involved = new Set(live.flatMap(refsOf)); + for (const d of opts.drag ?? []) involved.add(d.ref.e); + for (const id of opts.fixed ?? []) involved.delete(id); + const movers = entities.filter((e) => involved.has(e.id)); + const offsets: number[] = []; + const x0: number[] = []; + for (const e of movers) { + offsets.push(x0.length); + x0.push(...params(e)); + } + const byId = new Map(entities.map((e) => [e.id, e])); + const build = (x: number[]) => { + const m = new Map(byId); + movers.forEach((e, i) => m.set(e.id, withParams(e, x.slice(offsets[i], offsets[i] + params(e).length)))); + return m; + }; + const scale = Math.max(1, ...x0.map(Math.abs)); + // Two passes: a noticeable pull first (smallest change), then almost none (exact constraints). + let xs = x0; + for (const w of [1e-3, 1e-8]) xs = lm(xs, w); + const m = build(xs); + const get = (id: string) => m.get(id); + const error = Math.max(0, ...live.flatMap((c) => residuals(c, get).map(Math.abs))); + return { entities: entities.map((e) => m.get(e.id) ?? e), error, ok: error < 1e-6 * Math.max(1, scale) }; + + function lm(start: number[], weight: number): number[] { + const x0 = start; + const R = (x: number[]) => { + const m = build(x); + const get = (id: string) => m.get(id); + const out: number[] = []; + for (const c of live) out.push(...residuals(c, get)); + for (const d of opts.drag ?? []) { + const e = m.get(d.ref.e); + const p = e && pointOf(e, d.ref.p); + // The drag target is "soft but strong": constraints still win where they conflict. + if (p) out.push((p[0] - d.to[0]) * 0.3, (p[1] - d.to[1]) * 0.3); + } + // Weak pull towards the start: picks the smallest change for free directions. + for (let i = 0; i < x.length; i++) out.push((x[i] - x0[i]) * weight); + return out; + }; + let x = x0.slice(); + let r = R(x); + let cost = dot(r, r); + let lambda = 1e-3; + const n = x.length; + for (let it = 0; it < 60 && cost > 1e-20; it++) { + // Numeric Jacobian. + const J: number[][] = []; + for (let j = 0; j < n; j++) { + const h = 1e-6 * Math.max(1, Math.abs(x[j]), scale * 1e-3); + const xp = x.slice(); + xp[j] += h; + const rp = R(xp); + J.push(rp.map((v, i) => (v - r[i]) / h)); + } + // (JᵀJ + λ diag) dx = -Jᵀ r + const A: number[][] = Array.from({ length: n }, () => new Array(n).fill(0)); + const g = new Array(n).fill(0); + for (let a = 0; a < n; a++) { + for (let b = a; b < n; b++) { + let s = 0; + const Ja = J[a]; + const Jb = J[b]; + for (let i = 0; i < r.length; i++) s += Ja[i] * Jb[i]; + A[a][b] = A[b][a] = s; + } + let s = 0; + for (let i = 0; i < r.length; i++) s += J[a][i] * r[i]; + g[a] = -s; + } + let improved = false; + for (let tries = 0; tries < 8; tries++) { + const M = A.map((row, i) => row.map((v, j) => (i === j ? v * (1 + lambda) + 1e-12 : v))); + const dx = solveLinear(M, g); + if (!dx) { + lambda *= 10; + continue; + } + const xn = x.map((v, i) => v + dx[i]); + const rn = R(xn); + const cn = dot(rn, rn); + if (cn < cost) { + x = xn; + r = rn; + cost = cn; + lambda = Math.max(1e-9, lambda / 3); + improved = true; + break; + } + lambda *= 10; + } + if (!improved) break; + } + return x; + } +} + +/** Entity ids a constraint refers to. */ +export function refsOf(c: SketchConstraint): string[] { + return [...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])]; +} + +function dot(a: number[], b: number[]): number { + let s = 0; + for (let i = 0; i < a.length; i++) s += a[i] * b[i]; + return s; +} + +/** Gaussian elimination with partial pivoting. */ +function solveLinear(A: number[][], b: number[]): number[] | null { + const n = b.length; + const M = A.map((row, i) => [...row, b[i]]); + for (let c = 0; c < n; c++) { + let p = c; + for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r; + if (Math.abs(M[p][c]) < 1e-18) return null; + [M[c], M[p]] = [M[p], M[c]]; + for (let r = c + 1; r < n; r++) { + const f = M[r][c] / M[c][c]; + if (!f) continue; + for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k]; + } + } + const x = new Array(n).fill(0); + for (let r = n - 1; r >= 0; r--) { + let s = M[r][n]; + for (let k = r + 1; k < n; k++) s -= M[r][k] * x[k]; + x[r] = s / M[r][r]; + } + return x; +} + +// ------------------------------------------------------------- utilities + +/** Which constraints the current selection allows (for enabling buttons). */ +export function applicable(type: ConstraintType, pts: PointRef[], curves: SketchEntity[]): boolean { + const lines = curves.filter((e) => e.kind === "line"); + const rounds = curves.filter((e) => e.kind === "circle" || e.kind === "arc"); + switch (type) { + case "coincident": + return pts.length === 2 || (pts.length === 1 && curves.length === 1); + case "horizontal": + case "vertical": + return (lines.length === 1 && curves.length === 1 && !pts.length) || (pts.length === 2 && !curves.length); + case "parallel": + case "perpendicular": + return lines.length === 2 && curves.length === 2; + case "equal": + return curves.length === 2 && (lines.length === 2 || rounds.length === 2); + case "tangent": + return curves.length === 2 && rounds.length >= 1; + case "concentric": + return curves.length === 2 && curves.every((e) => e.kind !== "line" && e.kind !== "spline" && e.kind !== "polyline"); + case "midpoint": + return pts.length === 1 && lines.length === 1 && curves.length === 1; + case "symmetric": + return pts.length === 2 && lines.length === 1 && curves.length === 1; + case "distance": + return (pts.length === 2 && !curves.length) || (pts.length === 1 && lines.length === 1 && curves.length === 1); + case "fix": + // Points, or whole curves (all their points). + return pts.length >= 1 || curves.length >= 1; + default: + return false; + } +} diff --git a/src/sketch/curves.ts b/src/sketch/curves.ts new file mode 100644 index 0000000..9467064 --- /dev/null +++ b/src/sketch/curves.ts @@ -0,0 +1,284 @@ +// Sketch curve math, shared by the UI and the kernel worker. +// Every sketch entity is broken into primitives (line / circular arc / +// elliptical arc / spline) that can be evaluated at a parameter t ∈ [0, 1]. + +import type { SketchEntity, Vec2 } from "../doc/types"; + +export type Prim = + | { t: "line"; a: Vec2; b: Vec2; src: string } + | { t: "circle"; c: Vec2; r: number; a0: number; sweep: number; src: string } + | { t: "ellipse"; c: Vec2; rx: number; ry: number; rot: number; a0: number; sweep: number; src: string } + | { t: "spline"; pts: Vec2[]; closed: boolean; src: string; ctrl?: SplineDef }; + +/** The points a spline was drawn with (its samples are 16 per span of these). */ +export interface SplineDef { + points: Vec2[]; + closed: boolean; + mode: "fit" | "control"; +} + +export const SPLINE_PER_SPAN = 16; + +const TAU = Math.PI * 2; + +export function evalPrim(p: Prim, t: number): Vec2 { + switch (p.t) { + case "line": + return [p.a[0] + (p.b[0] - p.a[0]) * t, p.a[1] + (p.b[1] - p.a[1]) * t]; + case "circle": { + const ang = p.a0 + p.sweep * t; + return [p.c[0] + p.r * Math.cos(ang), p.c[1] + p.r * Math.sin(ang)]; + } + case "ellipse": { + const ang = p.a0 + p.sweep * t; + const x = p.rx * Math.cos(ang); + const y = p.ry * Math.sin(ang); + const c = Math.cos(p.rot); + const s = Math.sin(p.rot); + return [p.c[0] + x * c - y * s, p.c[1] + x * s + y * c]; + } + case "spline": { + const n = p.pts.length - 1; + const f = Math.min(Math.max(t, 0), 1) * n; + const i = Math.min(Math.floor(f), n - 1); + const u = f - i; + const a = p.pts[i]; + const b = p.pts[i + 1]; + return [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u]; + } + } +} + +export function isClosedPrim(p: Prim): boolean { + if (p.t === "circle" || p.t === "ellipse") return Math.abs(Math.abs(p.sweep) - TAU) < 1e-9; + if (p.t === "spline") return p.closed; + return false; +} + +/** Number of straight segments used to approximate a primitive. */ +export function primSegments(p: Prim): number { + switch (p.t) { + case "line": + return 1; + case "circle": + case "ellipse": + return Math.max(6, Math.ceil((Math.abs(p.sweep) / TAU) * 96)); + case "spline": + return p.pts.length - 1; + } +} + +/** Break an entity into primitives. Construction geometry still yields prims (for drawing). */ +export function entityPrims(e: SketchEntity): Prim[] { + const src = e.id; + switch (e.kind) { + case "line": + return [{ t: "line", a: e.a, b: e.b, src }]; + case "arc": { + const arc = arcFrom3(e.a, e.m, e.b); + if (!arc) return [{ t: "line", a: e.a, b: e.b, src }]; + return [{ t: "circle", c: arc.c, r: arc.r, a0: arc.a0, sweep: arc.sweep, src }]; + } + case "circle": + return [{ t: "circle", c: e.center, r: e.radius, a0: 0, sweep: TAU, src }]; + case "ellipse": + return [{ t: "ellipse", c: e.center, rx: e.rx, ry: e.ry, rot: e.rotation, a0: 0, sweep: TAU, src }]; + case "spline": + return [{ t: "spline", pts: splinePoints(e.points, e.closed, e.mode), closed: e.closed && e.points.length > 2, src, ...(e.points.length > 2 ? { ctrl: { points: e.points, closed: e.closed, mode: e.mode } } : {}) }]; + case "rect": + case "polygon": + case "polyline": { + const pts = entityCorners(e); + const closed = e.kind !== "polyline" || e.closed; + const out: Prim[] = []; + for (let i = 0; i < pts.length - (closed ? 0 : 1); i++) { + out.push({ t: "line", a: pts[i], b: pts[(i + 1) % pts.length], src }); + } + return out; + } + } +} + +/** Corner points of straight-sided entities. */ +export function entityCorners(e: Extract): Vec2[] { + if (e.kind === "polyline") return e.points; + if (e.kind === "polygon") { + return Array.from({ length: e.sides }, (_, i) => { + const t = e.angle + (i / e.sides) * TAU; + return [e.center[0] + e.radius * Math.cos(t), e.center[1] + e.radius * Math.sin(t)] as Vec2; + }); + } + const c = Math.cos(e.rotation); + const s = Math.sin(e.rotation); + const hw = e.w / 2; + const hh = e.h / 2; + return ([ + [-hw, -hh], + [hw, -hh], + [hw, hh], + [-hw, hh], + ] as Vec2[]).map(([x, y]) => [e.center[0] + x * c - y * s, e.center[1] + x * s + y * c] as Vec2); +} + +/** Dense polyline for drawing an entity. */ +export function entityPolylines(e: SketchEntity): Vec2[][] { + return entityPrims(e).map((p) => samplePrim(p, 0, 1)); +} + +export function samplePrim(p: Prim, t0: number, t1: number, segs?: number): Vec2[] { + const n = segs ?? Math.max(1, Math.ceil(primSegments(p) * Math.abs(t1 - t0))); + if (p.t === "spline") { + // Follow the stored samples exactly so pieces line up with the full curve. + const N = p.pts.length - 1; + const out: Vec2[] = [evalPrim(p, t0)]; + const lo = Math.min(t0, t1) * N; + const hi = Math.max(t0, t1) * N; + const inner: Vec2[] = []; + for (let i = Math.floor(lo) + 1; i < hi - 1e-9; i++) inner.push(p.pts[i]); + if (t1 < t0) inner.reverse(); + out.push(...inner, evalPrim(p, t1)); + return out; + } + return Array.from({ length: n + 1 }, (_, i) => evalPrim(p, t0 + ((t1 - t0) * i) / n)); +} + +/** Circle through three points, with the sweep that passes through the middle one. */ +export function arcFrom3(a: Vec2, m: Vec2, b: Vec2): { c: Vec2; r: number; a0: number; sweep: number } | null { + const ax = a[0]; + const ay = a[1]; + const bx = m[0]; + const by = m[1]; + const cx = b[0]; + const cy = b[1]; + const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); + if (Math.abs(d) < 1e-12) return null; + const ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d; + const uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d; + const r = Math.hypot(ax - ux, ay - uy); + const a0 = Math.atan2(ay - uy, ax - ux); + const am = Math.atan2(by - uy, bx - ux); + const a1 = Math.atan2(cy - uy, cx - ux); + const ccw = (x: number) => ((x % TAU) + TAU) % TAU; + const toM = ccw(am - a0); + const toB = ccw(a1 - a0); + const sweep = toM < toB ? toB : toB - TAU; + return { c: [ux, uy], r, a0, sweep }; +} + +/** + * Densely sampled spline. "fit" passes through the points (centripetal + * Catmull-Rom); "control" treats them as B-spline control points. + */ +export function splinePoints(pts: Vec2[], closed: boolean, mode: "fit" | "control", perSpan = 16): Vec2[] { + if (pts.length < 2) return pts.slice(); + if (pts.length === 2) return [pts[0], pts[1]]; + const n = pts.length; + const get = (i: number): Vec2 => (closed ? pts[((i % n) + n) % n] : pts[Math.max(0, Math.min(n - 1, i))]); + const spans = closed ? n : n - 1; + const out: Vec2[] = []; + for (let s = 0; s < spans; s++) { + for (let k = 0; k < perSpan; k++) { + const u = k / perSpan; + out.push(mode === "fit" ? catmull(get(s - 1), get(s), get(s + 1), get(s + 2), u) : bspline(get(s - 1), get(s), get(s + 1), get(s + 2), u)); + } + } + if (closed) out.push(out[0]); + else out.push(mode === "fit" ? pts[n - 1] : bspline(get(n - 3), get(n - 2), get(n - 1), get(n - 1), 1)); + if (!closed && mode === "control") out[0] = bspline(get(-1), get(0), get(1), get(2), 0); + return out; +} + +/** Exact point on span `s` of a spline (each span is one cubic), u in [0, 1]. */ +export function splineSpanAt(d: SplineDef, s: number, u: number): Vec2 { + const n = d.points.length; + const get = (i: number): Vec2 => (d.closed ? d.points[((i % n) + n) % n] : d.points[Math.max(0, Math.min(n - 1, i))]); + return d.mode === "fit" ? catmull(get(s - 1), get(s), get(s + 1), get(s + 2), u) : bspline(get(s - 1), get(s), get(s + 1), get(s + 2), u); +} + +/** Number of cubic spans of a spline. */ +export function splineSpans(d: SplineDef): number { + return d.closed ? d.points.length : d.points.length - 1; +} + +function catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, u: number): Vec2 { + // Centripetal parameterisation avoids cusps and self-intersections. + const d = (a: Vec2, b: Vec2) => Math.max(1e-9, Math.sqrt(Math.hypot(a[0] - b[0], a[1] - b[1]))); + const t0 = 0; + const t1 = t0 + d(p0, p1); + const t2 = t1 + d(p1, p2); + const t3 = t2 + d(p2, p3); + const t = t1 + (t2 - t1) * u; + const lerp = (a: Vec2, b: Vec2, ta: number, tb: number): Vec2 => { + const w = (t - ta) / (tb - ta || 1e-9); + return [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w]; + }; + const a1 = lerp(p0, p1, t0, t1); + const a2 = lerp(p1, p2, t1, t2); + const a3 = lerp(p2, p3, t2, t3); + const b1 = lerp(a1, a2, t0, t2); + const b2 = lerp(a2, a3, t1, t3); + return lerp(b1, b2, t1, t2); +} + +function bspline(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, u: number): Vec2 { + const u2 = u * u; + const u3 = u2 * u; + const b0 = (1 - 3 * u + 3 * u2 - u3) / 6; + const b1 = (4 - 6 * u2 + 3 * u3) / 6; + const b2 = (1 + 3 * u + 3 * u2 - 3 * u3) / 6; + const b3 = u3 / 6; + return [b0 * p0[0] + b1 * p1[0] + b2 * p2[0] + b3 * p3[0], b0 * p0[1] + b1 * p1[1] + b2 * p2[1] + b3 * p3[1]]; +} + +/** Closest parameter on a primitive to a point (coarse sample + refinement). */ +export function closestOnPrim(p: Prim, q: Vec2): { t: number; d: number; pt: Vec2 } { + const n = Math.max(16, primSegments(p) * 2); + let best = { t: 0, d: Infinity, pt: evalPrim(p, 0) }; + for (let i = 0; i <= n; i++) { + const t = i / n; + const pt = evalPrim(p, t); + const d = Math.hypot(pt[0] - q[0], pt[1] - q[1]); + if (d < best.d) best = { t, d, pt }; + } + let step = 1 / n; + for (let k = 0; k < 30; k++) { + step /= 2; + for (const t of [best.t - step, best.t + step]) { + if (t < 0 || t > 1) continue; + const pt = evalPrim(p, t); + const d = Math.hypot(pt[0] - q[0], pt[1] - q[1]); + if (d < best.d) best = { t, d, pt }; + } + } + return best; +} + +export function polyArea(poly: Vec2[]): number { + let a = 0; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) a += (poly[j][0] + poly[i][0]) * (poly[j][1] - poly[i][1]); + return -a / 2; +} + +export function polyCentroid(poly: Vec2[]): Vec2 { + let a = 0; + let cx = 0; + let cy = 0; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { + const f = poly[j][0] * poly[i][1] - poly[i][0] * poly[j][1]; + a += f; + cx += (poly[j][0] + poly[i][0]) * f; + cy += (poly[j][1] + poly[i][1]) * f; + } + if (Math.abs(a) < 1e-12) return poly[0] ?? [0, 0]; + return [cx / (3 * a), cy / (3 * a)]; +} + +export function pointInPoly(p: Vec2, poly: Vec2[]): boolean { + let inside = false; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { + const [xi, yi] = poly[i]; + const [xj, yj] = poly[j]; + if (yi > p[1] !== yj > p[1] && p[0] < ((xj - xi) * (p[1] - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} diff --git a/src/sketch/edit.ts b/src/sketch/edit.ts new file mode 100644 index 0000000..0b0f181 --- /dev/null +++ b/src/sketch/edit.ts @@ -0,0 +1,837 @@ +// Pure sketch-editing operations (no UI): trim, extend, offset, fillet, +// transforms, projection of 3D edges, and text outlines. + +import type { PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types"; +import { toPlane } from "../geom"; +import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves"; + +export function uid(): string { + return Math.random().toString(36).slice(2, 10); +} + +// ------------------------------------------------------------- transforms + +export type Xf = (p: Vec2) => Vec2; + +export const translateXf = (dx: number, dy: number): Xf => (p) => [p[0] + dx, p[1] + dy]; +export const rotateXf = (c: Vec2, ang: number): Xf => { + const cs = Math.cos(ang); + const sn = Math.sin(ang); + return (p) => [c[0] + (p[0] - c[0]) * cs - (p[1] - c[1]) * sn, c[1] + (p[0] - c[0]) * sn + (p[1] - c[1]) * cs]; +}; +export const scaleXf = (c: Vec2, k: number): Xf => (p) => [c[0] + (p[0] - c[0]) * k, c[1] + (p[1] - c[1]) * k]; +export const mirrorXf = (a: Vec2, b: Vec2): Xf => { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const l2 = dx * dx + dy * dy || 1; + return (p) => { + const t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2; + const fx = a[0] + dx * t; + const fy = a[1] + dy * t; + return [2 * fx - p[0], 2 * fy - p[1]]; + }; +}; + +/** Apply a point transform to an entity, keeping its kind where possible. */ +export function transformEntity(e: SketchEntity, xf: Xf, newId = false): SketchEntity { + const id = newId ? uid() : e.id; + const base = { id, construction: e.construction }; + const o = xf([0, 0]); + const ux = xf([1, 0]); + const k = Math.hypot(ux[0] - o[0], ux[1] - o[1]); // uniform scale factor + const rot = Math.atan2(ux[1] - o[1], ux[0] - o[0]); + const vy = xf([0, 1]); + const mirrored = (ux[0] - o[0]) * (vy[1] - o[1]) - (ux[1] - o[1]) * (vy[0] - o[0]) < 0; + switch (e.kind) { + case "line": + return { ...base, kind: "line", a: xf(e.a), b: xf(e.b) }; + case "arc": + return { ...base, kind: "arc", a: xf(e.a), m: xf(e.m), b: xf(e.b) }; + case "circle": + return { ...base, kind: "circle", center: xf(e.center), radius: e.radius * k }; + case "ellipse": + return { ...base, kind: "ellipse", center: xf(e.center), rx: e.rx * k, ry: e.ry * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot }; + case "spline": + return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode }; + case "rect": + return { ...base, kind: "rect", center: xf(e.center), w: e.w * k, h: e.h * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot }; + case "polygon": { + const corner = xf(entityCorners(e)[0]); + const c = xf(e.center); + return { ...base, kind: "polygon", center: c, radius: e.radius * k, sides: e.sides, angle: Math.atan2(corner[1] - c[1], corner[0] - c[0]) }; + } + case "polyline": + return { ...base, kind: "polyline", points: e.points.map(xf), closed: e.closed }; + } +} + +/** Characteristic points: endpoints, midpoints, centres (for snapping). */ +export function guidePoints(e: SketchEntity): { p: Vec2; kind: "end" | "mid" | "center" }[] { + const out: { p: Vec2; kind: "end" | "mid" | "center" }[] = []; + switch (e.kind) { + case "line": + out.push({ p: e.a, kind: "end" }, { p: e.b, kind: "end" }, { p: [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2], kind: "mid" }); + break; + case "arc": { + out.push({ p: e.a, kind: "end" }, { p: e.b, kind: "end" }); + const c = arcFrom3(e.a, e.m, e.b); + if (c) out.push({ p: c.c, kind: "center" }); + break; + } + case "circle": + case "ellipse": + out.push({ p: e.center, kind: "center" }); + for (const p of entityPrims(e)) for (const t of [0, 0.25, 0.5, 0.75]) out.push({ p: evalPrim(p, t), kind: "end" }); + break; + case "spline": + e.points.forEach((p) => out.push({ p, kind: "end" })); + break; + case "rect": + case "polygon": + case "polyline": { + const pts = entityCorners(e); + pts.forEach((p) => out.push({ p, kind: "end" })); + for (let i = 0; i < pts.length - (e.kind === "polyline" && !e.closed ? 1 : 0); i++) { + const a = pts[i]; + const b = pts[(i + 1) % pts.length]; + out.push({ p: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], kind: "mid" }); + } + if (e.kind !== "polyline") out.push({ p: e.center, kind: "center" }); + } + } + return out; +} + +// -------------------------------------------------------- trim & extend + +/** Turn rects/polygons/polylines into separate lines (needed before trimming one side). */ +export function explode(e: SketchEntity): SketchEntity[] { + if (e.kind !== "rect" && e.kind !== "polygon" && e.kind !== "polyline") return [e]; + return entityPrims(e).map((p) => ({ id: uid(), kind: "line", a: (p as { a: Vec2 }).a, b: (p as { b: Vec2 }).b, construction: e.construction })); +} + +/** Parameters where other entities cross primitive `p`. */ +function crossings(p: Prim, others: Prim[]): number[] { + const ts: number[] = []; + const n = Math.max(primSegments(p), 1) * 4; + const A = Array.from({ length: n + 1 }, (_, i) => evalPrim(p, i / n)); + for (const q of others) { + const m = Math.max(primSegments(q), 1) * 4; + const B = Array.from({ length: m + 1 }, (_, i) => evalPrim(q, i / m)); + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + const h = segHit(A[i], A[i + 1], B[j], B[j + 1]); + if (h) ts.push((i + h) / n); + } + } + } + return ts.sort((a, b) => a - b); +} + +function segHit(a: Vec2, b: Vec2, c: Vec2, d: Vec2): number | null { + const rx = b[0] - a[0]; + const ry = b[1] - a[1]; + const sx = d[0] - c[0]; + const sy = d[1] - c[1]; + const den = rx * sy - ry * sx; + if (Math.abs(den) < 1e-14) return null; + const qx = c[0] - a[0]; + const qy = c[1] - a[1]; + const u = (qx * sy - qy * sx) / den; + const v = (qx * ry - qy * rx) / den; + return u >= -1e-9 && u <= 1 + 1e-9 && v >= -1e-9 && v <= 1 + 1e-9 ? u : null; +} + +/** Remove the piece of `id` under `at` that lies between crossings. Returns the new entity list. */ +export function trim(entities: SketchEntity[], id: string, at: Vec2): SketchEntity[] { + let list = entities; + let target = list.find((e) => e.id === id); + if (!target) return entities; + // Straight-sided shapes: trim the one side that was tapped. + if (target.kind === "rect" || target.kind === "polygon" || target.kind === "polyline") { + const parts = explode(target); + list = list.flatMap((e) => (e.id === id ? parts : [e])); + target = parts.reduce((best, e) => (closestOnPrim(entityPrims(e)[0], at).d < closestOnPrim(entityPrims(best)[0], at).d ? e : best)); + } + const prim = entityPrims(target)[0]; + const others = list.filter((e) => e.id !== target!.id && !e.construction).flatMap(entityPrims); + const ts = crossings(prim, others).filter((t, i, a) => i === 0 || t - a[i - 1] > 1e-6); + const tap = closestOnPrim(prim, at).t; + const closed = isClosedPrim(prim); + const keep: [number, number][] = []; + if (closed) { + if (ts.length < 2) return list.filter((e) => e.id !== target!.id); + // The removed piece is between the crossings around the tap (cyclically). + let lo = ts[ts.length - 1] - 1; + let hi = ts[0]; + for (let i = 0; i < ts.length - 1; i++) if (tap >= ts[i] && tap <= ts[i + 1]) ((lo = ts[i]), (hi = ts[i + 1])); + if (tap > ts[ts.length - 1]) ((lo = ts[ts.length - 1]), (hi = ts[0] + 1)); + keep.push([hi, lo + 1]); + } else { + const cuts = [0, ...ts.filter((t) => t > 1e-6 && t < 1 - 1e-6), 1]; + for (let i = 0; i < cuts.length - 1; i++) if (!(tap >= cuts[i] && tap <= cuts[i + 1])) keep.push([cuts[i], cuts[i + 1]]); + } + const pieces = keep.map(([t0, t1]) => pieceEntity(prim, t0, t1, target!.construction)); + return list.flatMap((e) => (e.id === target!.id ? pieces : [e])); +} + +/** Entity for part [t0, t1] of a primitive (t may exceed 1 for closed curves). */ +function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity { + const at = (t: number) => evalPrim(p, isClosedPrim(p) && p.t !== "spline" ? t : Math.min(1, t > 1 ? t - 1 : t)); + if (p.t === "line") return { id: uid(), kind: "line", a: at(t0), b: at(t1), construction }; + if (p.t === "circle") return { id: uid(), kind: "arc", a: at(t0), m: at((t0 + t1) / 2), b: at(t1), construction }; + // Ellipses and splines: keep shape as a fit spline through samples. + const n = 12; + const pts = Array.from({ length: n + 1 }, (_, i) => at(t0 + ((t1 - t0) * i) / n)); + return { id: uid(), kind: "spline", points: pts, closed: false, mode: "fit", construction }; +} + +/** Extend the end of a line nearest `at` to the next curve it would hit. */ +export function extend(entities: SketchEntity[], id: string, at: Vec2): SketchEntity[] | null { + const e = entities.find((x) => x.id === id); + if (!e || e.kind !== "line") return null; + const endB = Math.hypot(at[0] - e.b[0], at[1] - e.b[1]) < Math.hypot(at[0] - e.a[0], at[1] - e.a[1]); + const from = endB ? e.b : e.a; + const other = endB ? e.a : e.b; + const dx = from[0] - other[0]; + const dy = from[1] - other[1]; + const L = Math.hypot(dx, dy) || 1; + const far: Vec2 = [from[0] + (dx / L) * 1e6, from[1] + (dy / L) * 1e6]; + let best = Infinity; + for (const q of entities.filter((x) => x.id !== id && !x.construction).flatMap(entityPrims)) { + const m = Math.max(primSegments(q), 1) * 4; + for (let j = 0; j < m; j++) { + const u = segHit(from, far, evalPrim(q, j / m), evalPrim(q, (j + 1) / m)); + if (u !== null && u * 1e6 > 1e-6) best = Math.min(best, u * 1e6); + } + } + if (!Number.isFinite(best)) return null; + const to: Vec2 = [from[0] + (dx / L) * best, from[1] + (dy / L) * best]; + return entities.map((x) => (x.id === id ? { ...e, ...(endB ? { b: to } : { a: to }) } : x)); +} + +/** Which end of an open curve the pick is nearer to ("a" or "b"); null for closed curves. */ +export function endNear(e: SketchEntity, at: Vec2): "a" | "b" | null { + const se = splineEnds(e); + if (se) return Math.hypot(at[0] - se[0][0], at[1] - se[0][1]) <= Math.hypot(at[0] - se[1][0], at[1] - se[1][1]) ? "a" : "b"; + if (e.kind !== "line" && e.kind !== "arc") return null; + return Math.hypot(at[0] - e.a[0], at[1] - e.a[1]) <= Math.hypot(at[0] - e.b[0], at[1] - e.b[1]) ? "a" : "b"; +} + +type Carrier = { kind: "line"; p: Vec2; d: Vec2 } | { kind: "circle"; c: Vec2; r: number }; + +type Piece = Extract; + +/** Where an open spline starts and ends (its real curve ends). */ +export function splineEnds(e: SketchEntity): [Vec2, Vec2] | null { + if (e.kind !== "spline" || e.closed || e.points.length < 2) return null; + const p = entityPrims(e)[0]; + return [evalPrim(p, 0), evalPrim(p, 1)]; +} + +/** The same curve run the other way. */ +function reverseIf(e: SketchEntity, rev: boolean): SketchEntity { + if (!rev) return e; + if (e.kind === "line" || e.kind === "arc") return { ...e, a: e.b, b: e.a } as SketchEntity; + if (e.kind === "spline") return { ...e, points: [...e.points].reverse() }; + return e; +} + +/** Point on a circle in the direction of q. */ +function towards(c: Vec2, q: Vec2, r: number): Vec2 { + const L = Math.hypot(q[0] - c[0], q[1] - c[1]) || 1; + return [c[0] + ((q[0] - c[0]) / L) * r, c[1] + ((q[1] - c[1]) / L) * r]; +} + +/** A spline end's tangent as a line carrier (to carry it on straight). */ +function splineEndCarrier(e: SketchEntity, end: "a" | "b"): Carrier | null { + if (e.kind !== "spline") return null; + const p = entityPrims(e)[0]; + const q = evalPrim(p, end === "a" ? 0 : 1); + const r = evalPrim(p, end === "a" ? 0.01 : 0.99); + return { kind: "line", p: q, d: [q[0] - r[0], q[1] - r[1]] }; +} + +function carrierOf(e: SketchEntity): Carrier | null { + if (e.kind === "line") return { kind: "line", p: e.a, d: [e.b[0] - e.a[0], e.b[1] - e.a[1]] }; + if (e.kind === "arc") { + const c = arcFrom3(e.a, e.m, e.b); + return c ? { kind: "circle", c: c.c, r: c.r } : null; + } + return null; +} + +/** Where two infinite lines / full circles cross. */ +function carrierCrossings(u: Carrier, v: Carrier): Vec2[] { + if (u.kind === "circle" && v.kind === "line") return carrierCrossings(v, u); + if (u.kind === "line" && v.kind === "line") { + const det = u.d[0] * v.d[1] - u.d[1] * v.d[0]; + if (Math.abs(det) < 1e-12 * (Math.hypot(...u.d) * Math.hypot(...v.d) || 1)) return []; + const t = ((v.p[0] - u.p[0]) * v.d[1] - (v.p[1] - u.p[1]) * v.d[0]) / det; + return [[u.p[0] + u.d[0] * t, u.p[1] + u.d[1] * t]]; + } + if (u.kind === "line" && v.kind === "circle") { + const L = Math.hypot(...u.d) || 1; + const d: Vec2 = [u.d[0] / L, u.d[1] / L]; + const f: Vec2 = [u.p[0] - v.c[0], u.p[1] - v.c[1]]; + const b = f[0] * d[0] + f[1] * d[1]; + const disc = b * b - (f[0] * f[0] + f[1] * f[1] - v.r * v.r); + if (disc < -1e-12) return []; + const s = Math.sqrt(Math.max(0, disc)); + return [-b - s, -b + s].map((t) => [u.p[0] + d[0] * t, u.p[1] + d[1] * t] as Vec2); + } + if (u.kind === "circle" && v.kind === "circle") { + const dx = v.c[0] - u.c[0]; + const dy = v.c[1] - u.c[1]; + const D = Math.hypot(dx, dy); + if (D < 1e-12 || D > u.r + v.r + 1e-9 || D < Math.abs(u.r - v.r) - 1e-9) return []; + const a = (u.r * u.r - v.r * v.r + D * D) / (2 * D); + const h = Math.sqrt(Math.max(0, u.r * u.r - a * a)); + const m: Vec2 = [u.c[0] + (dx * a) / D, u.c[1] + (dy * a) / D]; + return [ + [m[0] - (dy * h) / D, m[1] + (dx * h) / D], + [m[0] + (dy * h) / D, m[1] - (dx * h) / D], + ]; + } + return []; +} + +/** Move one end of a line/arc to `to` (an arc keeps its circle and its other end). */ +function moveEnd(e: SketchEntity, end: "a" | "b", to: Vec2): SketchEntity { + if (e.kind === "line") return { ...e, [end]: to }; + if (e.kind === "spline" && !e.closed) { + // The end fit point moves there. + const pts = [...e.points]; + pts[end === "a" ? 0 : pts.length - 1] = to; + return { ...e, points: pts }; + } + if (e.kind !== "arc") return e; + const c = arcFrom3(e.a, e.m, e.b); + if (!c) return e; + const ang = (q: Vec2) => Math.atan2(q[1] - c.c[1], q[0] - c.c[0]); + const a = end === "a" ? to : e.a; + const b = end === "b" ? to : e.b; + // Keep the arc's turning direction; the new mid point halves the new sweep. + const dir = Math.sign(c.sweep) || 1; + let sweep = ang(b) - ang(a); + while (dir > 0 && sweep <= 1e-9) sweep += 2 * Math.PI; + while (dir < 0 && sweep >= -1e-9) sweep -= 2 * Math.PI; + const t = ang(a) + sweep / 2; + return { ...e, a, b, m: [c.c[0] + c.r * Math.cos(t), c.c[1] + c.r * Math.sin(t)] }; +} + +/** + * Extend (or trim) two open curves so the picked ends meet: each pick says + * which end (the half that was tapped). Lines run along their direction, + * arcs along their circle. Picking both halves of one arc closes it into a circle. + */ +export function joinEnds(entities: SketchEntity[], first: { id: string; at: Vec2 }, second: { id: string; at: Vec2 }): SketchEntity[] | null { + const e1 = entities.find((x) => x.id === first.id); + const e2 = entities.find((x) => x.id === second.id); + if (!e1 || !e2) return null; + const end1 = endNear(e1, first.at); + const end2 = endNear(e2, second.at); + if (!end1 || !end2) return null; + if (e1.id === e2.id) { + if (e1.kind !== "arc" || end1 === end2) return null; + const c = arcFrom3(e1.a, e1.m, e1.b); + if (!c) return null; + const circle: SketchEntity = { id: e1.id, kind: "circle", center: c.c, radius: c.r, construction: e1.construction }; + return entities.map((x) => (x.id === e1.id ? circle : x)); + } + // A spline end carries on along its end tangent. + const k1 = carrierOf(e1) ?? splineEndCarrier(e1, end1); + const k2 = carrierOf(e2) ?? splineEndCarrier(e2, end2); + if (!k1 || !k2) return null; + const endPt = (e: SketchEntity, k: "a" | "b"): Vec2 => splineEnds(e)?.[k === "a" ? 0 : 1] ?? (e as Extract)[k]; + const p1 = endPt(e1, end1); + const p2 = endPt(e2, end2); + // A line running into a spline (as it is, or carried on): it stops on the spline itself. + if ((e1.kind === "spline") !== (e2.kind === "spline")) { + const [ln, lnEnd, sp] = e1.kind === "spline" ? [e2, end2, e1] : [e1, end1, e2]; + if (ln.kind === "line") { + const from = ln[lnEnd]; + const other = lnEnd === "a" ? ln.b : ln.a; + const L = Math.hypot(from[0] - other[0], from[1] - other[1]) || 1; + const dir: Vec2 = [(from[0] - other[0]) / L, (from[1] - other[1]) / L]; + const A: Vec2 = [other[0] - dir[0] * 1e6, other[1] - dir[1] * 1e6]; + const B: Vec2 = [from[0] + dir[0] * 1e6, from[1] + dir[1] * 1e6]; + const pts = samplePrim(entityPrims(sp)[0], 0, 1); + let best: Vec2 | null = null; + let bd = Infinity; + for (let i = 0; i < pts.length - 1; i++) { + const u = segHit(A, B, pts[i], pts[i + 1]); + if (u === null) continue; + const q: Vec2 = [A[0] + (B[0] - A[0]) * u, A[1] + (B[1] - A[1]) * u]; + const dd = Math.hypot(q[0] - from[0], q[1] - from[1]); + if (dd < bd) [bd, best] = [dd, q]; + } + if (best) return entities.map((x) => (x.id === ln.id ? moveEnd(ln, lnEnd, best!) : x)); + } + } + const cands = carrierCrossings(k1, k2); + if (!cands.length) return null; + // The meeting point nearest both picked ends. + const cost = (q: Vec2) => Math.hypot(q[0] - p1[0], q[1] - p1[1]) + Math.hypot(q[0] - p2[0], q[1] - p2[1]); + const to = cands.reduce((m, q) => (cost(q) < cost(m) ? q : m), cands[0]); + // A spline carries on to the meeting point (it becomes its new end point). + const reach = (e: SketchEntity, end: "a" | "b"): SketchEntity => { + if (e.kind !== "spline") return moveEnd(e, end, to); + return { ...e, points: end === "a" ? [to, ...e.points] : [...e.points, to] }; + }; + return entities.map((x) => (x.id === e1.id ? reach(e1, end1) : x.id === e2.id ? reach(e2, end2) : x)); +} + +/** + * Cut a line or arc in two: at its midpoint, or at the point nearest `at`. + * The second piece gets `newId`; returns null for other curves. + */ +export function splitEntity(entities: SketchEntity[], id: string, newId: string, at?: Vec2): SketchEntity[] | null { + const e = entities.find((x) => x.id === id); + if (!e) return null; + if (e.kind === "line") { + const d: Vec2 = [e.b[0] - e.a[0], e.b[1] - e.a[1]]; + const L2 = d[0] * d[0] + d[1] * d[1]; + let t = 0.5; + if (at && L2 > 0) t = ((at[0] - e.a[0]) * d[0] + (at[1] - e.a[1]) * d[1]) / L2; + if (!(t > 1e-6 && t < 1 - 1e-6)) return null; + const m: Vec2 = [e.a[0] + d[0] * t, e.a[1] + d[1] * t]; + return entities.flatMap((x) => (x.id === id ? [{ ...e, b: m }, { ...e, id: newId, a: m }] : [x])); + } + if (e.kind === "arc") { + const c = arcFrom3(e.a, e.m, e.b); + if (!c) return null; + let t = 0.5; + if (at) { + const ang = Math.atan2(at[1] - c.c[1], at[0] - c.c[0]); + let f = (ang - c.a0) / c.sweep; + // Bring the angle into the arc's own sweep. + const turn = (2 * Math.PI) / Math.abs(c.sweep); + while (f < 0) f += turn; + while (f > 1 && f - turn >= 0) f -= turn; + t = f; + } + if (!(t > 1e-6 && t < 1 - 1e-6)) return null; + const pt = (u: number): Vec2 => [c.c[0] + c.r * Math.cos(c.a0 + c.sweep * u), c.c[1] + c.r * Math.sin(c.a0 + c.sweep * u)]; + const m = pt(t); + return entities.flatMap((x) => (x.id === id ? [{ ...e, m: pt(t / 2), b: m }, { ...e, id: newId, a: m, m: pt((1 + t) / 2) }] : [x])); + } + return null; +} + +/** + * Fillet two lines picked by their halves: first they're extended/trimmed to + * meet (like `joinEnds`), then the corner is rounded with radius `r`. + */ +export function filletEnds(entities: SketchEntity[], first: { id: string; at: Vec2 }, second: { id: string; at: Vec2 }, r: number): SketchEntity[] | null { + const e1 = entities.find((x) => x.id === first.id); + const e2 = entities.find((x) => x.id === second.id); + if (e1?.kind !== "line" || e2?.kind !== "line" || e1.id === e2.id) return null; + const joined = joinEnds(entities, first, second); + if (!joined) return null; + const end = endNear(e1, first.at)!; + const corner = (joined.find((x) => x.id === e1.id) as Extract)[end]; + const size = Math.max(Math.hypot(e1.b[0] - e1.a[0], e1.b[1] - e1.a[1]), Math.hypot(e2.b[0] - e2.a[0], e2.b[1] - e2.a[1]), 1); + return filletCorner(joined, corner, r, size * 1e-7); +} + +/** + * Turn line `id2` so it makes `deg` degrees with line `id1`, about its end + * nearest to line 1. Both lines are re-oriented to point away from where they + * (would) meet, so their a→b directions span exactly that angle; `swapped` + * lists lines whose ends were exchanged (point refs a/b must follow). + */ +export function angleLines(entities: SketchEntity[], id1: string, id2: string, deg: number): { entities: SketchEntity[]; swapped: string[] } | null { + const l1 = entities.find((e) => e.id === id1); + const l2 = entities.find((e) => e.id === id2); + if (l1?.kind !== "line" || l2?.kind !== "line" || id1 === id2) return null; + const d1raw: Vec2 = [l1.b[0] - l1.a[0], l1.b[1] - l1.a[1]]; + const L1 = Math.hypot(...d1raw); + if (L1 < 1e-12) return null; + // Pivot: the end of line 2 closest to line 1 (its infinite line). + const off = (q: Vec2) => Math.abs((q[0] - l1.a[0]) * d1raw[1] - (q[1] - l1.a[1]) * d1raw[0]) / L1; + const pivotIsA = off(l2.a) <= off(l2.b); + const pivot = pivotIsA ? l2.a : l2.b; + const far = pivotIsA ? l2.b : l2.a; + const d2: Vec2 = [far[0] - pivot[0], far[1] - pivot[1]]; + const L2 = Math.hypot(...d2); + if (L2 < 1e-12) return null; + // Line 1 points away from the meeting point (its far end from line 2's pivot). + const da = Math.hypot(l1.a[0] - pivot[0], l1.a[1] - pivot[1]); + const db = Math.hypot(l1.b[0] - pivot[0], l1.b[1] - pivot[1]); + const flip1 = db < da; + const u: Vec2 = flip1 ? [-d1raw[0] / L1, -d1raw[1] / L1] : [d1raw[0] / L1, d1raw[1] / L1]; + // Keep the side line 2 is on now (counter-clockwise or clockwise from line 1). + const side = u[0] * d2[1] - u[1] * d2[0] >= 0 ? 1 : -1; + const t = Math.atan2(u[1], u[0]) + side * (deg * Math.PI) / 180; + const nf: Vec2 = [pivot[0] + Math.cos(t) * L2, pivot[1] + Math.sin(t) * L2]; + const swapped: string[] = []; + if (flip1) swapped.push(id1); + if (!pivotIsA) swapped.push(id2); + return { + entities: entities.map((e) => (e.id === id1 && flip1 ? { ...l1, a: l1.b, b: l1.a } : e.id === id2 ? { ...l2, a: pivot, b: nf } : e)), + swapped, + }; +} + +/** A curve with open ends (line/arc), walked in the chain's direction. */ +export interface ChainLink { + id: string; + /** Walked b→a rather than a→b. */ + reversed: boolean; +} + +/** + * Curves joined end to end with `id` (lines and arcs), in order. `closed` + * when the last one comes back to where the first started. + */ +export function connectedChain(entities: SketchEntity[], id: string): { links: ChainLink[]; closed: boolean } | null { + // Lines, arcs and open splines, by their two ends. + type Open = { id: string; a: Vec2; b: Vec2 }; + const open: Open[] = entities.flatMap((e) => { + if (e.construction) return []; + if (e.kind === "line" || e.kind === "arc") return [{ id: e.id, a: e.a, b: e.b }]; + const ends = splineEnds(e); + return ends ? [{ id: e.id, a: ends[0], b: ends[1] }] : []; + }); + const start = open.find((e) => e.id === id); + if (!start) return null; + const size = Math.max(1, ...open.flatMap((e) => [Math.abs(e.a[0]), Math.abs(e.a[1]), Math.abs(e.b[0]), Math.abs(e.b[1])])); + const tol = size * 1e-7; + const same = (p: Vec2, q: Vec2) => Math.hypot(p[0] - q[0], p[1] - q[1]) < tol; + const used = new Set([start.id]); + const walk = (from: Vec2): ChainLink[] => { + const out: ChainLink[] = []; + let at = from; + for (;;) { + const next = open.find((e) => !used.has(e.id) && (same(e.a, at) || same(e.b, at))); + if (!next) return out; + used.add(next.id); + const reversed = !same(next.a, at); + out.push({ id: next.id, reversed }); + at = reversed ? next.a : next.b; + } + }; + const forward = walk(start.b); + const last = forward.length ? open.find((e) => e.id === forward[forward.length - 1].id)! : start; + const lastEnd = forward.length ? (forward[forward.length - 1].reversed ? last.a : last.b) : start.b; + const closed = forward.length > 0 && same(lastEnd, start.a); + // Not closed: also walk backwards from the start, then flip that part. + const backward = closed ? [] : walk(start.a).reverse().map((l) => ({ ...l, reversed: !l.reversed })); + return { links: [...backward, { id: start.id, reversed: false }, ...forward], closed }; +} + +/** + * Offset a whole chain (e.g. a closed outline made of lines and arcs) by `d`: + * each piece moves sideways and neighbours are trimmed/extended to meet again, + * so a closed shape stays closed. Positive `d` grows a closed shape outward. + */ +export function offsetChain(entities: SketchEntity[], id: string, d: number): SketchEntity[] | null { + const chain = connectedChain(entities, id); + if (!chain) return null; + const byId = new Map(entities.map((e) => [e.id, e])); + // Walk direction: flip pieces walked backwards so every piece runs along the chain. + const pieces = chain.links.map((l) => reverseIf(byId.get(l.id)!, l.reversed) as Piece); + // Outward is to the right of a counter-clockwise loop (offsetEntity goes left). + let side = 1; + if (chain.closed) { + const poly = pieces.flatMap((e) => (e.kind === "arc" ? [e.a, e.m] : e.kind === "spline" ? samplePrim(entityPrims(e)[0], 0, 1).slice(0, -1) : [e.a])); + let area = 0; + for (let i = 0; i < poly.length; i++) { + const p = poly[i]; + const q = poly[(i + 1) % poly.length]; + area += p[0] * q[1] - q[0] * p[1]; + } + side = area > 0 ? -1 : 1; + } + // offsetEntity moves lines to their left but arcs always outward: an arc + // turning left (counter-clockwise) has its left side towards its centre. + const leftOf = (e: Piece) => (e.kind === "arc" && (arcFrom3(e.a, e.m, e.b)?.sweep ?? 0) > 0 ? -1 : 1); + const moved = pieces.map((e) => offsetEntity(e, leftOf(e) * side * d) as Piece | null); + if (moved.some((m) => !m)) return null; + const out = moved as Piece[]; + const endOf = (e: Piece, k: "a" | "b"): Vec2 => (e.kind === "spline" ? splineEnds(e)![k === "a" ? 0 : 1] : e[k]); + // Re-join neighbours where their offset carriers cross, nearest the original corner. + const n = out.length; + for (let i = 0; i < (chain.closed ? n : n - 1); i++) { + const j = (i + 1) % n; + const k1 = carrierOf(out[i]); + const k2 = carrierOf(out[j]); + const corner = endOf(pieces[i], "b"); + let meet: Vec2 | null = null; + if (k1 && k2) { + const cands = carrierCrossings(k1, k2); + if (cands.length) meet = cands.reduce((m, q) => (Math.hypot(q[0] - corner[0], q[1] - corner[1]) < Math.hypot(m[0] - corner[0], m[1] - corner[1]) ? q : m), cands[0]); + } else if (k1 || k2) { + // A spline next to a line/arc: the spline's offset end, brought onto the other's carrier. + const k = (k1 ?? k2)!; + const q = k1 ? endOf(out[j], "a") : endOf(out[i], "b"); + meet = k.kind === "line" ? projectOnLine(q, k.p, [k.p[0] + k.d[0], k.p[1] + k.d[1]]) : towards(k.c, q, k.r); + } else { + // Two splines: halfway between their offset ends. + const p = endOf(out[i], "b"); + const q = endOf(out[j], "a"); + meet = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2]; + } + // Tangent neighbours (e.g. line into a fillet) already meet: keep the offset end. + if (!meet) meet = endOf(out[i], "b"); + out[i] = moveEnd(out[i], "b", meet) as (typeof out)[number]; + out[j] = moveEnd(out[j], "a", meet) as (typeof out)[number]; + } + return [...entities, ...out.map((e) => ({ ...e, id: uid() }))]; +} + +// --------------------------------------------------------------- offset + +/** Offset copy of an entity (outward for closed shapes, to the left for open ones). */ +export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null { + const base = { id: uid(), construction: e.construction }; + switch (e.kind) { + case "circle": + return e.radius + d > 0 ? { ...base, kind: "circle", center: e.center, radius: e.radius + d } : null; + case "ellipse": + return e.rx + d > 0 && e.ry + d > 0 ? { ...base, kind: "ellipse", center: e.center, rx: e.rx + d, ry: e.ry + d, rotation: e.rotation } : null; + case "rect": + return e.w + 2 * d > 0 && e.h + 2 * d > 0 ? { ...base, kind: "rect", center: e.center, w: e.w + 2 * d, h: e.h + 2 * d, rotation: e.rotation } : null; + case "polygon": { + const r = e.radius + d / Math.cos(Math.PI / e.sides); + return r > 0 ? { ...base, kind: "polygon", center: e.center, radius: r, sides: e.sides, angle: e.angle } : null; + } + case "line": { + const dx = e.b[0] - e.a[0]; + const dy = e.b[1] - e.a[1]; + const L = Math.hypot(dx, dy) || 1; + const nx = (-dy / L) * d; + const ny = (dx / L) * d; + return { ...base, kind: "line", a: [e.a[0] + nx, e.a[1] + ny], b: [e.b[0] + nx, e.b[1] + ny] }; + } + case "arc": { + const c = arcFrom3(e.a, e.m, e.b); + if (!c) return null; + const k = (c.r + d) / c.r; + if (k <= 0) return null; + const s = scaleXf(c.c, k); + return { ...base, kind: "arc", a: s(e.a), m: s(e.m), b: s(e.b) }; + } + case "spline": + case "polyline": { + const pts = e.kind === "spline" ? samplePrim(entityPrims(e)[0], 0, 1) : e.points; + const closed = e.closed; + const sign = closed && signedArea(pts) < 0 ? -1 : 1; + const out = pts.map((p, i) => { + const prev = pts[i === 0 ? (closed ? pts.length - 2 : 0) : i - 1]; + const next = pts[i === pts.length - 1 ? (closed ? 1 : i) : i + 1]; + const tx = next[0] - prev[0]; + const ty = next[1] - prev[1]; + const L = Math.hypot(tx, ty) || 1; + // Outward for CCW closed curves = to the right of travel. + return [p[0] + (ty / L) * d * sign * (closed ? 1 : -1), p[1] - (tx / L) * d * sign * (closed ? 1 : -1)] as Vec2; + }); + // Enough fit points to follow the curve closely (four per original span). + const n = Math.max(24, (e.kind === "spline" ? e.points.length : 6) * 4 + 1); + return e.kind === "spline" ? { ...base, kind: "spline", points: thin(closed ? out.slice(0, -1) : out, n), closed, mode: "fit" } : { ...base, kind: "polyline", points: out, closed }; + } + } +} + +function signedArea(p: Vec2[]): number { + let a = 0; + for (let i = 0, j = p.length - 1; i < p.length; j = i++) a += (p[j][0] + p[i][0]) * (p[j][1] - p[i][1]); + return -a / 2; +} + +function thin(pts: Vec2[], n: number): Vec2[] { + if (pts.length <= n) return pts; + const step = (pts.length - 1) / (n - 1); + return Array.from({ length: n }, (_, i) => pts[Math.round(i * step)]); +} + +// --------------------------------------------------------------- fillet + +/** + * Round the corner nearest `at` where two lines meet. Rects/polygons are + * turned into lines first. Returns null if no corner is near. + */ +export function filletCorner(entities: SketchEntity[], at: Vec2, radius: number, tol: number): SketchEntity[] | null { + let list = entities.flatMap((e) => (e.kind === "rect" || e.kind === "polygon" || e.kind === "polyline" ? cornerNear(e, at, tol) ? explode(e) : [e] : [e])); + const lines = list.filter((e): e is Extract => e.kind === "line"); + const ends: { e: (typeof lines)[number]; end: "a" | "b" }[] = []; + for (const e of lines) for (const end of ["a", "b"] as const) if (Math.hypot(e[end][0] - at[0], e[end][1] - at[1]) < tol) ends.push({ e, end }); + if (ends.length < 2) return null; + const [p, q] = ends; + const corner = p.e[p.end]; + const farP = p.e[p.end === "a" ? "b" : "a"]; + const farQ = q.e[q.end === "a" ? "b" : "a"]; + const u = unit(sub2(farP, corner)); + const v = unit(sub2(farQ, corner)); + const cos = u[0] * v[0] + u[1] * v[1]; + const half = Math.acos(Math.max(-1, Math.min(1, cos))) / 2; + if (half < 1e-3 || Math.PI / 2 - half < 1e-3) return null; + const dist = radius / Math.tan(half); + if (dist > Math.hypot(...sub2(farP, corner)) || dist > Math.hypot(...sub2(farQ, corner))) return null; + const tp: Vec2 = [corner[0] + u[0] * dist, corner[1] + u[1] * dist]; + const tq: Vec2 = [corner[0] + v[0] * dist, corner[1] + v[1] * dist]; + const bis = unit([u[0] + v[0], u[1] + v[1]]); + const cdist = radius / Math.sin(half); + const c: Vec2 = [corner[0] + bis[0] * cdist, corner[1] + bis[1] * cdist]; + const mid: Vec2 = [c[0] - bis[0] * radius, c[1] - bis[1] * radius]; + list = list.map((e) => (e === p.e ? { ...p.e, [p.end]: tp } : e === q.e ? { ...q.e, [q.end]: tq } : e)); + list.push({ id: uid(), kind: "arc", a: tp, m: mid, b: tq, construction: p.e.construction }); + return list; +} + +function cornerNear(e: Extract, at: Vec2, tol: number): boolean { + return entityCorners(e).some((p) => Math.hypot(p[0] - at[0], p[1] - at[1]) < tol); +} + +const sub2 = (a: Vec2, b: Vec2): Vec2 => [a[0] - b[0], a[1] - b[1]]; +const unit = (a: Vec2): Vec2 => { + const l = Math.hypot(a[0], a[1]) || 1; + return [a[0] / l, a[1] / l]; +}; + +// --------------------------------------------------- projection of edges + +/** + * A 3D polyline (e.g. a body edge) flattened onto the sketch plane, as the + * simplest matching entity: line, circle, arc or spline. + */ +export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string): SketchEntity | null { + const pts = dedupe(pts3.map((p) => toPlane(plane, p))); + if (pts.length < 2) return null; + const a = pts[0]; + const b = pts[pts.length - 1]; + const closed = Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-6 * (1 + span(pts)); + if (type === "LINE" || pts.length === 2) return { id: uid(), kind: "line", a, b }; + if (type === "CIRCLE") { + const m = pts[Math.floor(pts.length / 2)]; + const q = pts[Math.floor(pts.length / 3)]; + const c = arcFrom3(pts[0], q, m); + if (c) { + // Only a true circle if the projection didn't squash it (plane parallel to the edge's circle). + const ok = pts.every((p) => Math.abs(Math.hypot(p[0] - c.c[0], p[1] - c.c[1]) - c.r) < c.r * 1e-3); + if (ok) return closed ? { id: uid(), kind: "circle", center: c.c, radius: c.r } : { id: uid(), kind: "arc", a, m, b }; + } + } + const fit = thin(closed ? pts.slice(0, -1) : pts, 24); + return { id: uid(), kind: "spline", points: fit, closed, mode: "fit" }; +} + +function dedupe(pts: Vec2[]): Vec2[] { + const out: Vec2[] = []; + for (const p of pts) { + const q = out[out.length - 1]; + if (!q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 1e-9) out.push(p); + } + return out; +} + +function span(pts: Vec2[]): number { + let m = 0; + for (const p of pts) m = Math.max(m, Math.abs(p[0]), Math.abs(p[1])); + return m; +} + +/** + * After a fillet: the lines no longer meet at the old corner, so the + * Coincident that joined them there would pull them back. Replace it with + * Coincident + Tangent between each line and the new arc. + */ +export function filletConstraints(entities: SketchEntity[], constraints: SketchConstraint[], before: Set): SketchConstraint[] { + const arcs = entities.filter((e): e is Extract => e.kind === "arc" && !before.has(e.id)); + let cs = constraints; + for (const arc of arcs) { + const touching: { e: string; p: "a" | "b"; arcEnd: "a" | "b" }[] = []; + for (const l of entities) + if (l.kind === "line") + for (const p of ["a", "b"] as const) + for (const arcEnd of ["a", "b"] as const) if (Math.hypot(l[p][0] - arc[arcEnd][0], l[p][1] - arc[arcEnd][1]) < 1e-9) touching.push({ e: l.id, p, arcEnd }); + if (touching.length < 2) continue; + const ends = new Set(touching.map((t) => `${t.e}:${t.p}`)); + // Drop constraints that tie these moved ends to each other. + cs = cs.filter((c) => !(c.type === "coincident" && c.pts?.length === 2 && c.pts.every((q) => ends.has(`${q.e}:${q.p}`)))); + for (const t of touching) { + cs = [...cs, { id: uid(), type: "coincident", pts: [{ e: t.e, p: t.p }, { e: arc.id, p: t.arcEnd }] }, { id: uid(), type: "tangent", curves: [t.e, arc.id] }]; + } + } + return cs; +} + +// ------------------------------------------------------------ align / join + +type LineE = Extract; + +const near2 = (p: Vec2, q: Vec2, tol: number) => Math.hypot(p[0] - q[0], p[1] - q[1]) < tol; + +/** Where the infinite line p + t·d meets the infinite line through a, b (null if parallel). */ +function meetLines(p: Vec2, d: Vec2, a: Vec2, b: Vec2): Vec2 | null { + const e: Vec2 = [b[0] - a[0], b[1] - a[1]]; + const den = d[0] * e[1] - d[1] * e[0]; + if (Math.abs(den) < 1e-12 * Math.hypot(...d) * Math.hypot(...e)) return null; + const t = ((a[0] - p[0]) * e[1] - (a[1] - p[1]) * e[0]) / den; + return [p[0] + d[0] * t, p[1] + d[1] * t]; +} + +function projectOnLine(p: Vec2, a: Vec2, b: Vec2): Vec2 { + const d: Vec2 = [b[0] - a[0], b[1] - a[1]]; + const l2 = d[0] * d[0] + d[1] * d[1] || 1; + const t = ((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / l2; + return [a[0] + d[0] * t, a[1] + d[1] * t]; +} + +/** + * Align: line `id` moves onto the infinite line of `target` (it ends up lying + * on it). Lines joined to its ends keep their direction and stretch to follow, + * like the neighbouring faces of a replaced face. + */ +export function alignLine(entities: SketchEntity[], id: string, target: SketchEntity): SketchEntity[] | null { + const ln = entities.find((e) => e.id === id); + if (ln?.kind !== "line" || target.kind !== "line" || target.id === id) return null; + const [ta, tb] = [target.a, target.b]; + const size = Math.hypot(ln.b[0] - ln.a[0], ln.b[1] - ln.a[1]) + Math.hypot(tb[0] - ta[0], tb[1] - ta[1]); + const tol = size * 1e-6 + 1e-9; + const moved = new Map(); + const ends: Record<"a" | "b", Vec2> = { a: ln.a, b: ln.b }; + for (const k of ["a", "b"] as const) { + const p = ln[k]; + // A line joined here (not the target itself) slides its end along its own direction. + const nb = entities.find((e): e is LineE => e.kind === "line" && e.id !== id && e.id !== target.id && !e.construction && (near2(e.a, p, tol) || near2(e.b, p, tol))); + let q: Vec2 | null = null; + if (nb) { + const end = near2(nb.a, p, tol) ? "a" : "b"; + const other = end === "a" ? nb.b : nb.a; + q = meetLines(other, [p[0] - other[0], p[1] - other[1]], ta, tb); + if (q) moved.set(nb.id, { ...(moved.get(nb.id) ?? nb), [end]: q }); + } + ends[k] = q ?? projectOnLine(p, ta, tb); + } + if (near2(ends.a, ends.b, tol)) return null; + return entities.map((e) => (e.id === id ? { ...ln, a: ends.a, b: ends.b } : moved.get(e.id) ?? e)); +} + +/** + * Join: line `id` and a line on the same axis that shares one of its ends + * become a single line. Returns the new entities and the id that was merged away. + */ +export function joinCollinear(entities: SketchEntity[], id: string, prefer?: Vec2): { entities: SketchEntity[]; removed: string } | null { + const ln = entities.find((e) => e.id === id); + if (ln?.kind !== "line") return null; + const len = Math.hypot(ln.b[0] - ln.a[0], ln.b[1] - ln.a[1]); + const tol = len * 1e-6 + 1e-9; + const d: Vec2 = [(ln.b[0] - ln.a[0]) / len, (ln.b[1] - ln.a[1]) / len]; + const onAxis = (p: Vec2) => Math.abs((p[0] - ln.a[0]) * d[1] - (p[1] - ln.a[1]) * d[0]) < tol * 10; + const cands = entities.filter( + (e): e is LineE => e.kind === "line" && e.id !== id && !!e.construction === !!ln.construction && onAxis(e.a) && onAxis(e.b) && [e.a, e.b].some((p) => near2(p, ln.a, tol) || near2(p, ln.b, tol)), + ); + if (!cands.length) return null; + // Two candidates (one at each end): the one on the side that was tapped. + const along = (p: Vec2) => (p[0] - ln.a[0]) * d[0] + (p[1] - ln.a[1]) * d[1]; + const pick = prefer && cands.length > 1 ? cands.reduce((x, y) => (Math.abs(along(mid(x)) - along(prefer)) < Math.abs(along(mid(y)) - along(prefer)) ? x : y)) : cands[0]; + const pts = [ln.a, ln.b, pick.a, pick.b].sort((p, q) => along(p) - along(q)); + const joined: LineE = { ...ln, a: pts[0], b: pts[3] }; + return { entities: entities.filter((e) => e.id !== pick.id).map((e) => (e.id === id ? joined : e)), removed: pick.id }; +} + +function mid(l: LineE): Vec2 { + return [(l.a[0] + l.b[0]) / 2, (l.a[1] + l.b[1]) / 2]; +} diff --git a/src/sketch/regions.ts b/src/sketch/regions.ts new file mode 100644 index 0000000..0288ab4 --- /dev/null +++ b/src/sketch/regions.ts @@ -0,0 +1,390 @@ +// Planar arrangement of sketch curves → selectable regions. +// +// All curves are split where they cross, the pieces form a planar graph, and +// every bounded face of that graph is a region (with holes for anything nested +// inside it). This is what lets overlapping shapes be extruded piece by piece. + +import type { SketchEntity, Vec2 } from "../doc/types"; +import { closestOnPrim, entityPrims, evalPrim, isClosedPrim, pointInPoly, polyArea, polyCentroid, primSegments, samplePrim, type Prim } from "./curves"; + +export interface Piece { + prim: number; + t0: number; + t1: number; + n0: number; + n1: number; + /** Polyline from node n0 to node n1 (endpoints are the node positions). */ + poly: Vec2[]; +} + +export interface LoopRef { + piece: number; + reversed: boolean; +} + +export interface Loop { + pieces: LoopRef[]; + poly: Vec2[]; +} + +export interface Region { + index: number; + outer: Loop; + holes: Loop[]; + area: number; + centroid: Vec2; +} + +export interface Arrangement { + prims: Prim[]; + nodes: Vec2[]; + pieces: Piece[]; + regions: Region[]; +} + +export interface RegionRef { + c: Vec2; + a: number; +} + +const cache = new Map(); + +/** Regions of a sketch. Memoised on the entity list, so callers can call freely. */ +export function arrangement(entities: SketchEntity[]): Arrangement { + const key = JSON.stringify(entities); + const hit = cache.get(key); + if (hit) return hit; + const result = compute(entities.filter((e) => !e.construction)); + cache.set(key, result); + if (cache.size > 64) cache.delete(cache.keys().next().value!); + return result; +} + +export function regionRef(r: Region): RegionRef { + return { c: r.centroid, a: r.area }; +} + +/** The region best matching a stored reference (survives edits that move it a bit). */ +export function resolveRegion(arr: Arrangement, ref: RegionRef): Region | null { + let best: { r: Region; s: number } | null = null; + for (const r of arr.regions) { + const scale = Math.sqrt(Math.max(ref.a, 1e-9)); + const s = Math.hypot(r.centroid[0] - ref.c[0], r.centroid[1] - ref.c[1]) / scale + Math.abs(Math.log((r.area + 1e-12) / (ref.a + 1e-12))); + if (!best || s < best.s) best = { r, s }; + } + return best && best.s < 3 ? best.r : null; +} + +function compute(entities: SketchEntity[]): Arrangement { + const prims = entities.flatMap(entityPrims); + const empty: Arrangement = { prims, nodes: [], pieces: [], regions: [] }; + if (!prims.length) return empty; + + // ---- discretise + const samples = prims.map((p) => { + const n = primSegments(p); + const ts = Array.from({ length: n + 1 }, (_, i) => i / n); + return { ts, pts: ts.map((t) => evalPrim(p, t)) }; + }); + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const s of samples) + for (const [x, y] of s.pts) { + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + } + const size = Math.hypot(maxX - minX, maxY - minY) || 1; + const eps = size * 1e-7; + + // ---- intersections (sweep over segments sorted by min x) + interface Seg { + p: number; + i: number; + a: Vec2; + b: Vec2; + x0: number; + x1: number; + y0: number; + y1: number; + } + const segs: Seg[] = []; + samples.forEach((s, p) => { + for (let i = 0; i < s.pts.length - 1; i++) { + const a = s.pts[i]; + const b = s.pts[i + 1]; + segs.push({ p, i, a, b, x0: Math.min(a[0], b[0]) - eps, x1: Math.max(a[0], b[0]) + eps, y0: Math.min(a[1], b[1]) - eps, y1: Math.max(a[1], b[1]) + eps }); + } + }); + segs.sort((u, v) => u.x0 - v.x0); + const splits: number[][] = prims.map(() => []); + const tParam = (p: number, i: number, u: number) => samples[p].ts[i] + (samples[p].ts[i + 1] - samples[p].ts[i]) * u; + for (let i = 0; i < segs.length; i++) { + const A = segs[i]; + for (let j = i + 1; j < segs.length && segs[j].x0 <= A.x1; j++) { + const B = segs[j]; + if (B.y0 > A.y1 || B.y1 < A.y0) continue; + if (A.p === B.p) continue; // self-intersections are ignored + // Lines lying on each other (e.g. drawn over a face's edge): each is split + // where the other one ends, and the doubled pieces merge below. + const lap = overlap(A.a, A.b, B.a, B.b, eps); + if (lap) { + for (const u of lap[0]) splits[A.p].push(tParam(A.p, A.i, u)); + for (const v of lap[1]) splits[B.p].push(tParam(B.p, B.i, v)); + continue; + } + const hit = segHit(A.a, A.b, B.a, B.b, eps); + if (!hit) continue; + let ta = tParam(A.p, A.i, hit[0]); + let tb = tParam(B.p, B.i, hit[1]); + [ta, tb] = refine(prims[A.p], prims[B.p], ta, tb); + splits[A.p].push(ta); + splits[B.p].push(tb); + } + } + + // ---- pieces + const nodes: Vec2[] = []; + const nodeOf = (pt: Vec2): number => { + const tol = eps * 50; + for (let k = 0; k < nodes.length; k++) if (Math.abs(nodes[k][0] - pt[0]) < tol && Math.abs(nodes[k][1] - pt[1]) < tol) return k; + nodes.push(pt); + return nodes.length - 1; + }; + let pieces: Piece[] = []; + prims.forEach((p, pi) => { + const closed = isClosedPrim(p); + let ts = [...splits[pi]].map((t) => Math.min(1, Math.max(0, t))).sort((a, b) => a - b); + if (closed) { + ts = ts.map((t) => (t >= 1 - 1e-9 ? 0 : t)).sort((a, b) => a - b); + if (ts.length === 0) ts = [0, 0.5]; + else if (ts.length === 1) ts.push(ts[0] + 0.5 > 1 ? ts[0] - 0.5 : ts[0] + 0.5), ts.sort((a, b) => a - b); + } else { + ts.unshift(0); + ts.push(1); + } + const uniq = ts.filter((t, k) => k === 0 || t - ts[k - 1] > 1e-9); + const bounds: [number, number][] = []; + for (let k = 0; k < uniq.length - 1; k++) bounds.push([uniq[k], uniq[k + 1]]); + if (closed) bounds.push([uniq[uniq.length - 1], uniq[0] + 1]); + for (const [t0, t1] of bounds) { + const a = evalPrim(p, t0 % 1); + const b = evalPrim(p, t1 > 1 ? t1 - 1 : t1); + const poly = closed && t1 > 1 ? [...samplePrim(p, t0, 1).slice(0, -1), ...samplePrim(p, 0, t1 - 1)] : samplePrim(p, t0, t1); + if (polyLength(poly) < eps * 10) continue; + const n0 = nodeOf(a); + const n1 = nodeOf(b); + poly[0] = nodes[n0]; + poly[poly.length - 1] = nodes[n1]; + pieces.push({ prim: pi, t0, t1, n0, n1, poly }); + } + }); + + // ---- the same stretch drawn twice counts once + { + const seen = new Map(); + pieces = pieces.filter((pc) => { + const key = pc.n0 < pc.n1 ? `${pc.n0}:${pc.n1}` : `${pc.n1}:${pc.n0}`; + const mid = pc.poly[Math.floor(pc.poly.length / 2)]; + const m = pc.poly.length > 2 ? mid : [(pc.poly[0][0] + pc.poly[1][0]) / 2, (pc.poly[0][1] + pc.poly[1][1]) / 2] as Vec2; + for (const [k, q] of seen) if (k.split("#")[0] === key && Math.hypot(q[0] - m[0], q[1] - m[1]) < eps * 1e3) return false; + seen.set(`${key}#${seen.size}`, m); + return true; + }); + } + + // ---- drop dangling pieces (they can't bound a region) + for (;;) { + const deg = new Array(nodes.length).fill(0); + for (const pc of pieces) { + deg[pc.n0]++; + deg[pc.n1]++; + } + const keep = pieces.filter((pc) => deg[pc.n0] > 1 && deg[pc.n1] > 1); + if (keep.length === pieces.length) break; + pieces = keep; + } + if (!pieces.length) return { prims, nodes, pieces, regions: [] }; + + // ---- half-edge traversal + const H = pieces.length * 2; + const from = (h: number) => (h % 2 === 0 ? pieces[h >> 1].n0 : pieces[h >> 1].n1); + const hpoly = (h: number) => (h % 2 === 0 ? pieces[h >> 1].poly : [...pieces[h >> 1].poly].reverse()); + const angleOf = (h: number) => { + const pl = hpoly(h); + const a = pl[0]; + const b = pl[1]; + const c = pl[Math.min(2, pl.length - 1)]; + const main = Math.atan2(b[1] - a[1], b[0] - a[0]); + // Tie-break tangent pieces by where they head next. + const next = Math.atan2(c[1] - a[1], c[0] - a[0]); + return main + angleDiff(main, next) * 1e-3; + }; + const out: number[][] = nodes.map(() => []); + for (let h = 0; h < H; h++) out[from(h)].push(h); + const ang = new Float64Array(H); + for (let h = 0; h < H; h++) ang[h] = angleOf(h); + for (const list of out) list.sort((x, y) => ang[x] - ang[y]); + const next = (h: number) => { + const twin = h ^ 1; + const list = out[from(twin)]; + const k = list.indexOf(twin); + return list[(k - 1 + list.length) % list.length]; + }; + const seen = new Uint8Array(H); + const cycles: { hs: number[]; poly: Vec2[]; area: number }[] = []; + for (let h0 = 0; h0 < H; h0++) { + if (seen[h0]) continue; + const hs: number[] = []; + let h = h0; + let guard = 0; + while (!seen[h] && guard++ < H + 1) { + seen[h] = 1; + hs.push(h); + h = next(h); + } + const poly: Vec2[] = []; + for (const x of hs) poly.push(...hpoly(x).slice(0, -1)); + cycles.push({ hs, poly, area: polyArea(poly) }); + } + + // ---- components (union-find over nodes) + const parent = nodes.map((_, i) => i); + const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]))); + for (const pc of pieces) parent[find(pc.n0)] = find(pc.n1); + const comp = (c: { hs: number[] }) => find(from(c.hs[0])); + + const minArea = eps * eps * 100; + const faces = cycles.filter((c) => c.area > minArea); + const outers = cycles.filter((c) => c.area <= minArea); + const holes = new Map<(typeof faces)[number], typeof outers>(); + for (const o of outers) { + const p = o.poly[0]; + let best: (typeof faces)[number] | null = null; + for (const f of faces) { + if (comp(f) === comp(o)) continue; + if (!pointInPoly(p, f.poly)) continue; + if (!best || f.area < best.area) best = f; + } + if (best) holes.set(best, [...(holes.get(best) ?? []), o]); + } + + const toLoop = (c: { hs: number[]; poly: Vec2[] }): Loop => ({ + pieces: c.hs.map((h) => ({ piece: h >> 1, reversed: h % 2 === 1 })), + poly: c.poly, + }); + const regions: Region[] = faces.map((f, index) => { + const hs = holes.get(f) ?? []; + const holeArea = hs.reduce((s, o) => s + Math.abs(o.area), 0); + const area = f.area - holeArea; + // Area-weighted centroid of the face minus its holes. + const c0 = polyCentroid(f.poly); + let cx = c0[0] * f.area; + let cy = c0[1] * f.area; + for (const o of hs) { + const ch = polyCentroid(o.poly); + cx -= ch[0] * Math.abs(o.area); + cy -= ch[1] * Math.abs(o.area); + } + return { index, outer: toLoop(f), holes: hs.map(toLoop), area, centroid: [cx / area, cy / area] }; + }); + return { prims, nodes, pieces, regions }; +} + +/** + * Two collinear, overlapping segments → where (as fractions along each) the + * other one's ends fall inside it. Null when they don't lie on each other. + */ +function overlap(a: Vec2, b: Vec2, c: Vec2, d: Vec2, eps: number): [number[], number[]] | null { + const rx = b[0] - a[0]; + const ry = b[1] - a[1]; + const sx = d[0] - c[0]; + const sy = d[1] - c[1]; + const lu = Math.hypot(rx, ry); + const lv = Math.hypot(sx, sy); + if (lu < eps || lv < eps) return null; + if (Math.abs(rx * sy - ry * sx) > lu * lv * 1e-6) return null; + // Both ends of cd on the line through ab? + const off = (p: Vec2) => Math.abs((p[0] - a[0]) * ry - (p[1] - a[1]) * rx) / lu; + if (off(c) > eps * 10 || off(d) > eps * 10) return null; + const along = (p: Vec2, o: Vec2, x: number, y: number, l: number) => ((p[0] - o[0]) * x + (p[1] - o[1]) * y) / (l * l); + const inside = (u: number, l: number) => u > (eps * 10) / l && u < 1 - (eps * 10) / l; + const ua = [along(c, a, rx, ry, lu), along(d, a, rx, ry, lu)].filter((u) => inside(u, lu)); + const vb = [along(a, c, sx, sy, lv), along(b, c, sx, sy, lv)].filter((v) => inside(v, lv)); + const lo = Math.min(along(c, a, rx, ry, lu), along(d, a, rx, ry, lu)); + const hi = Math.max(along(c, a, rx, ry, lu), along(d, a, rx, ry, lu)); + if (hi < 0 || lo > 1) return null; + return [ua, vb]; +} + +function segHit(a: Vec2, b: Vec2, c: Vec2, d: Vec2, eps: number): [number, number] | null { + const rx = b[0] - a[0]; + const ry = b[1] - a[1]; + const sx = d[0] - c[0]; + const sy = d[1] - c[1]; + const den = rx * sy - ry * sx; + if (Math.abs(den) < 1e-18) return null; // parallel / collinear overlaps ignored + const qx = c[0] - a[0]; + const qy = c[1] - a[1]; + const u = (qx * sy - qy * sx) / den; + const v = (qx * ry - qy * rx) / den; + const lu = Math.hypot(rx, ry) || 1; + const lv = Math.hypot(sx, sy) || 1; + const tu = eps / lu; + const tv = eps / lv; + if (u < -tu || u > 1 + tu || v < -tv || v > 1 + tv) return null; + return [Math.min(1, Math.max(0, u)), Math.min(1, Math.max(0, v))]; +} + +/** Newton-refine an intersection on the exact curves. */ +function refine(p: Prim, q: Prim, t: number, s: number): [number, number] { + if (p.t === "spline" && q.t === "spline") return [t, s]; + const h = 1e-7; + for (let k = 0; k < 8; k++) { + const P = evalPrim(p, t); + const Q = evalPrim(q, s); + const fx = P[0] - Q[0]; + const fy = P[1] - Q[1]; + if (Math.abs(fx) + Math.abs(fy) < 1e-12) break; + const Pt = evalPrim(p, Math.min(1, t + h)); + const Qs = evalPrim(q, Math.min(1, s + h)); + const a = (Pt[0] - P[0]) / h; + const c = (Pt[1] - P[1]) / h; + const b = -(Qs[0] - Q[0]) / h; + const d = -(Qs[1] - Q[1]) / h; + const det = a * d - b * c; + if (Math.abs(det) < 1e-14) break; + const dt = (d * fx - b * fy) / det; + const ds = (-c * fx + a * fy) / det; + t = Math.min(1, Math.max(0, t - dt)); + s = Math.min(1, Math.max(0, s - ds)); + } + return [t, s]; +} + +function polyLength(p: Vec2[]): number { + let l = 0; + for (let i = 1; i < p.length; i++) l += Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]); + return l; +} + +function angleDiff(a: number, b: number): number { + let d = b - a; + while (d > Math.PI) d -= Math.PI * 2; + while (d < -Math.PI) d += Math.PI * 2; + return d; +} + +/** Parameter + distance of the closest point on any primitive of an entity. */ +export function closestOnEntity(e: SketchEntity, q: Vec2): { t: number; d: number; pt: Vec2; prim: number } { + const prims = entityPrims(e); + let best = { t: 0, d: Infinity, pt: q, prim: 0 }; + prims.forEach((p, i) => { + const c = closestOnPrim(p, q); + if (c.d < best.d) best = { ...c, prim: i }; + }); + return best; +} diff --git a/src/sketch/text.ts b/src/sketch/text.ts new file mode 100644 index 0000000..97189c8 --- /dev/null +++ b/src/sketch/text.ts @@ -0,0 +1,88 @@ +// Text → closed outline polylines (each glyph contour; holes come out as regions). +// Font: Roboto (Apache-2.0), parsed with opentype.js (MIT). + +import { parse, type Font } from "opentype.js"; +import fontUrl from "@fontsource/roboto/files/roboto-latin-400-normal.woff?url"; +import type { SketchEntity, Vec2 } from "../doc/types"; +import { uid } from "./edit"; + +let font: Promise | null = null; + +function loadFont(): Promise { + font ??= fetch(fontUrl) + .then((r) => r.arrayBuffer()) + .then((b) => parse(b)); + return font; +} + +/** Outline entities for `text` with its baseline-left at `at`, cap height ≈ size. */ +export async function textEntities(text: string, at: Vec2, size: number, angle = 0): Promise { + const f = await loadFont(); + // opentype sizes are em; Roboto caps are ~0.71 em. + const fontSize = size / 0.711; + // Lay glyphs out ourselves: opentype's text shaper chokes on some of Roboto's + // substitution tables ("substFormat 2 not supported"). + const scale = fontSize / f.unitsPerEm; + const commands: { type: string; x?: number; y?: number; x1?: number; y1?: number; x2?: number; y2?: number }[] = []; + let x = 0; + let prev: ReturnType | null = null; + for (const ch of text) { + const g = f.charToGlyph(ch); + if (prev) x += f.getKerningValue(prev, g) * scale; + commands.push(...g.getPath(x, 0, fontSize).commands); + x += (g.advanceWidth ?? 0) * scale; + prev = g; + } + const path = { commands } as { commands: Array<{ type: string; x: number; y: number; x1: number; y1: number; x2: number; y2: number }> }; + const contours: Vec2[][] = []; + let cur: Vec2[] = []; + let last: Vec2 = [0, 0]; + const push = (p: Vec2) => { + cur.push(p); + last = p; + }; + const steps = 8; + for (const c of path.commands) { + if (c.type === "M") { + if (cur.length > 2) contours.push(cur); + cur = []; + push([c.x, -c.y]); + } else if (c.type === "L") push([c.x, -c.y]); + else if (c.type === "Q") { + const p0 = last; + for (let i = 1; i <= steps; i++) { + const t = i / steps; + const u = 1 - t; + push([u * u * p0[0] + 2 * u * t * c.x1 + t * t * c.x, u * u * p0[1] + 2 * u * t * -c.y1 + t * t * -c.y]); + } + } else if (c.type === "C") { + const p0 = last; + for (let i = 1; i <= steps; i++) { + const t = i / steps; + const u = 1 - t; + push([ + u * u * u * p0[0] + 3 * u * u * t * c.x1 + 3 * u * t * t * c.x2 + t * t * t * c.x, + u * u * u * p0[1] + 3 * u * u * t * -c.y1 + 3 * u * t * t * -c.y2 + t * t * t * -c.y, + ]); + } + } else if (c.type === "Z") { + if (cur.length > 2) contours.push(cur); + cur = []; + } + } + if (cur.length > 2) contours.push(cur); + const cs = Math.cos(angle); + const sn = Math.sin(angle); + return contours.map((pts) => { + // Drop a duplicated closing point. + const a = pts[0]; + const b = pts[pts.length - 1]; + if (Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9) pts.pop(); + return { + id: uid(), + kind: "polyline" as const, + closed: true, + points: pts.map(([x, y]) => [at[0] + x * cs - y * sn, at[1] + x * sn + y * cs] as Vec2), + }; + }); +} diff --git a/src/style.css b/src/style.css new file mode 100644 index 0000000..80f7d4f --- /dev/null +++ b/src/style.css @@ -0,0 +1,1654 @@ +:root { + --bg: #2b2d31; + --chrome: rgba(31, 33, 37, 0.94); + --chrome-solid: #1f2125; + --line: rgba(255, 255, 255, 0.08); + --text: #e8e9ec; + --muted: #9a9ea6; + --accent: #3d8bff; + --accent-soft: rgba(61, 139, 255, 0.18); + --ok: #4fd18b; + --danger: #ff6b5e; + --radius: 10px; + --tap: 40px; + --safe-l: env(safe-area-inset-left, 0px); + --safe-r: env(safe-area-inset-right, 0px); + --safe-b: env(safe-area-inset-bottom, 0px); + --safe-t: env(safe-area-inset-top, 0px); + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + height: 100%; + overflow: hidden; + background: var(--bg); + color: var(--text); + font: 13.5px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + overscroll-behavior: none; +} + +button { + font: inherit; + color: inherit; + background: none; + border: 0; + cursor: pointer; + -webkit-tap-highlight-color: transparent; +} +button:disabled { + opacity: 0.35; + cursor: default; +} + +kbd { + font: 10.5px/1 ui-monospace, monospace; + color: var(--muted); + border: 1px solid var(--line); + border-radius: 4px; + padding: 2px 4px; + margin-left: 6px; +} +@media (pointer: coarse) { + kbd { + display: none; + } +} + +#view { + position: fixed; + inset: 0; + width: 100%; + height: 100%; + display: block; + touch-action: none; +} + +/* ---------------------------------------------------------------- top bar */ + +#topbar { + position: fixed; + top: calc(8px + var(--safe-t)); + left: calc(8px + var(--safe-l)); + display: flex; + align-items: center; + gap: 4px; + /* Above the tool column so the File menu is never covered. */ + z-index: 35; +} +/* As wide as the Items panel below it (258 px), the name filling it. */ +.brand { + box-sizing: border-box; + width: 258px; + /* + the top bar's 4 px gap: the name box starts at 274 px, where the tool column sits beside Items. */ + margin-right: 4px; + font-size: 24px; + line-height: 36px; + font-weight: 750; + letter-spacing: 0.01em; + padding: 0 6px; + white-space: nowrap; + overflow: hidden; + color: #cfd6e4; + /* All lowercase: its letters centre on their x-height, ~4 px below the box middle. + Lift it so it lines up with the File / Items / More labels. */ + position: relative; + top: -4px; +} +.brand-tld { + color: var(--accent); + font-weight: 600; +} +/* The project name reads as a tab; click it to type a new name. */ +.project-name { + width: 300px; + min-height: 36px; + padding: 0 12px; + margin-right: 10px; + border-radius: 8px; + border: 1px solid transparent; + background: var(--chrome); + color: var(--text); + font: inherit; + font-weight: 550; + text-overflow: ellipsis; + cursor: text; + -webkit-user-select: text; + user-select: text; +} +.project-name:hover { + border-color: var(--line); +} +.project-name:focus { + outline: 2px solid var(--accent); + outline-offset: -1px; + background: #2b2e34; +} + +.text-btn { + min-height: 36px; + padding: 0 12px; + border-radius: 8px; + background: var(--chrome); + display: inline-flex; + align-items: center; + gap: 6px; + white-space: nowrap; +} +.text-btn svg { + width: 18px; + height: 18px; +} +.text-btn:hover:not(:disabled), +.icon-btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.1); +} +.text-btn.primary { + background: var(--accent); + color: white; +} +.text-btn.primary:hover { + background: #5a9dff; +} +.icon-btn { + width: 36px; + height: 36px; + border-radius: 8px; + display: inline-grid; + place-items: center; + background: var(--chrome); + flex: none; +} +.icon-btn.small { + width: 26px; + height: 26px; + background: none; + margin-left: auto; +} +.icon-btn svg { + width: 20px; + height: 20px; +} + +.menu-wrap { + position: relative; +} +.menu { + position: absolute; + top: 42px; + left: 0; + min-width: 210px; + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 6px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4); + z-index: 30; +} +.menu button { + display: flex; + justify-content: space-between; + width: 100%; + text-align: left; + padding: 10px; + border-radius: 6px; +} +.menu button:hover { + background: rgba(255, 255, 255, 0.08); +} +.copy-toggle { + position: fixed; + left: 0; + top: 0; + display: flex; + align-items: center; + gap: 5px; + height: 32px; + padding: 0 10px 0 8px; + border-radius: 16px; + background: var(--chrome-solid); + border: 1px solid var(--line); + color: var(--muted); + font-size: 12.5px; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35); + z-index: 12; +} +.copy-toggle svg { + width: 17px; + height: 17px; +} +.copy-toggle.on { + background: var(--accent); + border-color: var(--accent); + color: white; +} +.copy-toggle[hidden] { + display: none; +} +.swatch { + width: 20px; + height: 20px; + border-radius: 50%; + display: inline-block; + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.25); + flex: none; +} +#flyout.swatch-grid { + display: grid; + grid-template-columns: repeat(5, 44px); + gap: 4px; + padding: 8px; +} +#flyout.swatch-grid .tool { + width: 44px; + height: 44px; + padding: 0; + justify-content: center; +} +#flyout.swatch-grid .tool .swatch { + width: 28px; + height: 28px; +} +#flyout.swatch-grid .tool.active .swatch { + box-shadow: 0 0 0 2px var(--chrome-solid), 0 0 0 4px var(--accent); +} +#flyout.swatch-grid .tool-label, +#flyout.swatch-grid .tool-key { + display: none; +} +.menu-soon { + font-size: 11px; + color: var(--muted); +} +.menu-note { + padding: 8px 10px 4px; + color: var(--muted); + font-size: 12px; +} +/* Undo / redo dock: bottom-left corner, always; the section/measure buttons sit above it. */ +#undo-dock { + position: fixed; + left: calc(8px + var(--safe-l)); + bottom: calc(10px + var(--safe-b)); + display: flex; + gap: 2px; + padding: 4px; + background: var(--chrome); + border-radius: var(--radius); + z-index: 10; +} +.dock-btn { + width: 52px; + height: 44px; + border-radius: 9px; + display: grid; + place-items: center; +} +.dock-btn svg { + width: 24px; + height: 24px; +} +.dock-btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.08); +} +.dock-btn:disabled { + opacity: 0.35; +} +body.items-open #undo-dock { + left: calc(274px + var(--safe-l)); +} +.menu hr { + border: 0; + border-top: 1px solid var(--line); + margin: 4px 0; +} + +/* ------------------------------------------------------------ tool column */ + +#toolbar, +#bottom-left, +#flyout { + position: fixed; + display: flex; + flex-direction: column; + gap: 1px; + background: var(--chrome); + border-radius: var(--radius); + padding: 4px; + z-index: 10; +} +/* Vertically centred on the left edge. */ +#toolbar { + left: calc(8px + var(--safe-l)); + top: 50%; + transform: translateY(-50%); + max-height: calc(100vh - 200px - var(--safe-t) - var(--safe-b)); + overflow-y: auto; + scrollbar-width: thin; +} +#toolbar:empty, +#bottom-left:empty { + display: none; +} +#bottom-left { + left: calc(8px + var(--safe-l)); + /* Above the undo/redo dock (52 px tall) with a gap. */ + bottom: calc(76px + var(--safe-b)); +} +#flyout { + z-index: 25; + max-height: calc(100vh - 20px); + overflow-y: auto; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4); +} +#flyout[hidden] { + display: none; +} + +.tool { + display: flex; + align-items: center; + gap: 9px; + min-height: var(--tap); + padding: 0 12px 0 7px; + border-radius: 7px; + white-space: nowrap; + text-align: left; + position: relative; +} +.tool svg { + width: 21px; + height: 21px; + flex: none; +} +.tool:hover:not(.disabled) { + background: rgba(255, 255, 255, 0.07); +} +.tool.active { + background: var(--accent-soft); + color: #b9d4ff; +} +.tool.disabled { + opacity: 0.38; + cursor: default; +} +.tool.has-children::after { + content: ""; + position: absolute; + left: 23px; + top: 25px; + border: 3px solid transparent; + border-left-color: currentColor; + border-bottom-color: currentColor; + transform: rotate(-90deg); + opacity: 0.7; +} +.tool-label { + display: flex; + flex-direction: column; +} +.tool-name { + display: flex; + align-items: center; +} +.tool-sub { + font-size: 11px; + color: var(--muted); +} +.tool-sep { + height: 1px; + background: var(--line); + margin: 3px 4px; +} + +/* ------------------------------------------------- right column + popover */ + +#viewcube-host { + position: fixed; + top: calc(10px + var(--safe-t)); + right: calc(60px + var(--safe-r)); + z-index: 5; +} +#viewcube { + position: relative; + width: 110px; + height: 110px; +} +#viewcube canvas { + display: block; + touch-action: none; + cursor: grab; +} +.vc-roll { + position: absolute; + top: 0; + width: 22px; + height: 22px; + border-radius: 50%; + font-size: 14px; + color: var(--muted); +} +.vc-roll.left { + left: 0; +} +.vc-roll.right { + right: 0; +} +.vc-roll:hover { + color: var(--text); + background: var(--chrome); +} + +#right-col { + position: fixed; + top: calc(8px + var(--safe-t)); + right: calc(8px + var(--safe-r)); + display: flex; + flex-direction: column; + gap: 2px; + background: var(--chrome); + border-radius: var(--radius); + padding: 4px; + z-index: 10; +} +.right-btn { + width: 40px; + min-height: 40px; + border-radius: 7px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1px; +} +.right-btn svg { + width: 20px; + height: 20px; +} +.right-btn:hover { + background: rgba(255, 255, 255, 0.08); +} +.right-btn.on { + background: var(--accent-soft); + color: #b9d4ff; +} +/* Buttons that only make sense while sketching. */ +.right-btn.sketch-only { + display: none; +} +body.sketching .right-btn.sketch-only { + display: flex; +} +.right-label { + font-size: 9.5px; + color: var(--muted); +} +#popover { + position: fixed; + right: calc(60px + var(--safe-r)); + width: 270px; + max-height: calc(100vh - 20px); + overflow-y: auto; + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 8px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45); + z-index: 30; +} +#popover[hidden] { + display: none; +} +.pop-heading { + font-weight: 600; + padding: 8px 8px 4px; +} +.pop-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + text-align: left; + min-height: 38px; + padding: 0 8px; + border-radius: 6px; +} +.pop-row:hover { + background: rgba(255, 255, 255, 0.06); +} +.choice-row.active { + box-shadow: inset 3px 0 0 var(--accent); + background: rgba(255, 255, 255, 0.05); +} +.switch { + width: 34px; + height: 20px; + border-radius: 10px; + background: #4a4e57; + position: relative; + flex: none; + transition: 0.15s; +} +.switch::after { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 14px; + height: 14px; + border-radius: 50%; + background: #cfd3da; + transition: 0.15s; +} +.toggle-row.on .switch { + background: var(--accent); +} +.toggle-row.on .switch::after { + left: 17px; + background: white; +} +.pop-note { + color: var(--muted); + font-size: 12px; + padding: 6px 8px; +} +.pop-input { + width: 70px; + font: 13px ui-monospace, monospace; + color: var(--text); + background: #2b2e34; + border: 1px solid var(--line); + border-radius: 6px; + padding: 6px; + -webkit-user-select: text; + user-select: text; +} +.pop-tabs { + display: flex; + gap: 4px; + padding: 2px 2px 6px; + border-bottom: 1px solid var(--line); + margin-bottom: 4px; +} +.pop-tabs button { + padding: 6px 10px; + border-radius: 6px; + color: var(--muted); +} +.pop-tabs button.active { + color: var(--text); + background: rgba(255, 255, 255, 0.08); +} + +/* ------------------------------------------------------ hint / status / label */ + +/* Below the top bar, so it never covers File / Items / Undo. */ +#hint { + position: fixed; + top: calc(54px + var(--safe-t)); + left: 50%; + transform: translateX(-50%); + max-width: min(560px, calc(100vw - 440px)); + background: var(--chrome); + border-radius: 12px; + padding: 8px 16px; + color: #c6cad2; + text-align: center; + pointer-events: none; + z-index: 9; +} +#hint[hidden], +#status[hidden], +#panel[hidden], +#label[hidden] { + display: none; +} + +#status { + position: fixed; + inset: 0; + margin: auto; + width: fit-content; + height: fit-content; + max-width: calc(100vw - 32px); + background: var(--chrome-solid); + border-radius: var(--radius); + padding: 14px 20px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4); + z-index: 40; +} + +#label { + position: fixed; + left: 0; + top: 0; + pointer-events: none; + background: var(--chrome-solid); + border: 1px solid rgba(61, 139, 255, 0.55); + border-radius: 8px; + padding: 4px 8px; + font: 13px/1.25 ui-monospace, monospace; + white-space: nowrap; + z-index: 20; + display: flex; + flex-direction: column; + gap: 2px; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35); +} +.label-value { + font-weight: 600; +} +.label-tip { + font: 11px/1.2 system-ui, sans-serif; + color: #9fc3ff; +} +#label.typing { + border-color: var(--accent); + background: #1d2a40; +} + +#toast { + position: fixed; + left: 50%; + bottom: calc(96px + var(--safe-b)); + transform: translate(-50%, 20px); + opacity: 0; + transition: 0.2s; + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 16px; + pointer-events: none; + max-width: calc(100vw - 32px); + z-index: 45; +} +#toast.show { + opacity: 1; + transform: translate(-50%, 0); +} +#toast.error { + border-color: rgba(255, 107, 94, 0.5); +} + +.dim-widget { + position: fixed; + left: 0; + top: 0; + display: flex; + align-items: center; + gap: 4px; + padding: 3px; + background: rgba(31, 33, 37, 0.95); + border: 1px solid rgba(61, 139, 255, 0.7); + border-radius: 8px; + z-index: 16; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35); +} +.dim-widget[hidden] { + display: none; +} +.dim-widget select { + font: inherit; + font-size: 12px; + color: var(--text); + background: #2b2e34; + border: 0; + border-radius: 5px; + padding: 4px 2px; +} +.dim-widget input { + width: 64px; + font: 13px ui-monospace, monospace; + color: var(--text); + background: #2b2e34; + border: 1px solid transparent; + border-radius: 5px; + padding: 4px 6px; + -webkit-user-select: text; + user-select: text; +} +.dim-widget input:focus { + border-color: var(--accent); + outline: none; +} +.dim-widget input.invalid, +.dim-widget.invalid input { + border-color: var(--danger); +} +/* Keys typed while drawing land here (the box isn't focused). */ +.dim-widget.typing input { + border-color: var(--accent); + background: #1d2a40; +} +.dim-unit { + font-size: 11.5px; + color: var(--muted); +} +.dim-pin { + font-size: 13px; + padding: 2px 4px; + border-radius: 5px; +} +.dim-pin:hover { + background: rgba(255, 255, 255, 0.1); +} + +/* Sketch constraints: column of buttons + badges next to the geometry. */ +/* Placed by the sketch tool: beside the right-hand bar, its top at the Constraints button. */ +#constraint-bar { + position: fixed; + right: calc(60px + var(--safe-r)); + top: 50%; + display: flex; + flex-direction: column; + gap: 1px; + background: var(--chrome); + border-radius: var(--radius); + padding: 4px; + z-index: 10; +} + +#constraint-bar button { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + min-height: 34px; + padding: 0 10px; + border-radius: 7px; + text-align: left; + white-space: nowrap; +} +#constraint-bar button:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.07); +} +#constraint-bar button.on { + background: var(--accent-soft); + color: #cfe0ff; +} +#constraint-bar button.on .cg::after { + content: " ✓"; + font-size: 10px; +} +#constraint-bar hr { + border: 0; + border-top: 1px solid var(--line); + margin: 3px 2px; +} +.cbar-toggle .switch { + width: 28px; + height: 16px; + border-radius: 8px; + background: #3a3e46; + position: relative; + flex: none; +} +.cbar-toggle .switch::after { + content: ""; + position: absolute; + top: 2px; + left: 2px; + width: 12px; + height: 12px; + border-radius: 50%; + background: #c9ced8; + transition: left 0.12s; +} +.cbar-toggle.on .switch { + background: var(--accent); +} +.cbar-toggle.on .switch::after { + left: 14px; + background: white; +} +#constraint-bar .cg { + width: 22px; + text-align: center; + color: #9fd1ff; + font-weight: 600; +} +.cglyphs[hidden] { + display: none; +} +.cglyphs { + position: fixed; + inset: 0; + pointer-events: none; + z-index: 7; +} +.cglyph { + position: absolute; + left: 0; + top: 0; + pointer-events: auto; + min-width: 18px; + height: 18px; + padding: 0 4px; + font-size: 11px; + line-height: 18px; + border-radius: 5px; + color: #cfe3ff; + background: rgba(40, 70, 120, 0.85); + border: 1px solid rgba(110, 160, 255, 0.6); +} +.cglyph.dim { + height: 22px; + line-height: 20px; + padding: 0 6px; + font: 12px ui-monospace, monospace; + color: #fff; + background: rgba(31, 33, 37, 0.92); + border-color: rgba(255, 255, 255, 0.35); +} +.cglyph.expr { + color: #9fd1ff; +} +.cglyph.sel { + border-color: #ffd34d; + box-shadow: 0 0 0 2px rgba(255, 211, 77, 0.35); +} +.cglyph[hidden] { + display: none; +} +@media (max-width: 720px) { + #constraint-bar { + top: auto; + transform: none; + bottom: calc(120px + var(--safe-b)); + right: calc(8px + var(--safe-r)); + max-height: 40vh; + overflow-y: auto; + } + #constraint-bar .cl { + display: none; + } +} + +#warn { + position: fixed; + left: 50%; + bottom: calc(62px + var(--safe-b)); + transform: translateX(-50%); + max-width: min(520px, calc(100vw - 32px)); + padding: 5px 12px; + border-radius: 999px; + font-size: 12px; + color: #ffd2a8; + background: rgba(60, 38, 20, 0.85); + border: 1px solid rgba(255, 154, 61, 0.45); + pointer-events: none; + z-index: 9; +} +#warn[hidden] { + display: none; +} + +#marquee { + position: fixed; + border: 1px solid var(--accent); + background: rgba(61, 139, 255, 0.12); + pointer-events: none; + z-index: 6; +} +#marquee[hidden] { + display: none; +} + +#pins { + position: fixed; + inset: 0; + pointer-events: none; + z-index: 4; +} +.pin { + position: absolute; + left: 0; + top: 0; + background: rgba(31, 33, 37, 0.92); + border: 1px solid rgba(61, 139, 255, 0.6); + border-radius: 6px; + padding: 3px 7px; + font: 12px ui-monospace, monospace; + white-space: nowrap; +} + +/* ---------------------------------------------------------- value panel */ + +#panel { + position: fixed; + bottom: calc(10px + var(--safe-b)); + left: 50%; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + justify-content: center; + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: 14px; + padding: 8px 8px 8px 14px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35); + max-width: min(980px, calc(100vw - 16px)); + z-index: 15; +} +.panel-title { + font-weight: 600; +} +.panel-fields, +.panel-buttons { + display: flex; + gap: 8px; + align-items: center; + flex-wrap: wrap; +} +.field { + display: flex; + align-items: center; + gap: 5px; + color: var(--muted); +} +.field input, +.text-input { + width: 92px; + min-height: 36px; + font: 14px ui-monospace, monospace; + color: var(--text); + background: #2b2e34; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 8px; + -webkit-user-select: text; + user-select: text; +} +.text-input { + width: 180px; + font-family: inherit; +} +.field input:focus, +.text-input:focus { + outline: 2px solid var(--accent); + outline-offset: -1px; +} +.field input.invalid { + outline: 2px solid var(--danger); +} +.field input.has-expr { + color: #9fd1ff; +} +.fx-btn { + font: italic 600 12px Georgia, serif; + color: var(--muted); + padding: 4px 6px; + border-radius: 6px; +} +.fx-btn:hover { + color: var(--text); + background: rgba(255, 255, 255, 0.08); +} +.slot { + display: flex; + flex-direction: column; + align-items: flex-start; + min-height: 38px; + padding: 3px 10px; + border-radius: 8px; + border: 1px dashed rgba(255, 255, 255, 0.25); + text-align: left; +} +.slot.active { + border: 1px solid var(--accent); + background: var(--accent-soft); +} +.slot.filled { + border-style: solid; +} +.slot-label { + font-size: 11px; + color: var(--muted); +} +.choice { + display: flex; + align-items: center; + gap: 2px; + background: #2b2e34; + border-radius: 8px; + padding: 2px; +} +.choice button { + padding: 7px 10px; + border-radius: 6px; + color: var(--muted); +} +.choice button.active { + background: var(--accent); + color: white; +} +.toggle { + padding: 8px 12px; + border-radius: 8px; + background: #2b2e34; + color: var(--muted); +} +.toggle.on { + background: var(--accent-soft); + color: #b9d4ff; + box-shadow: inset 0 0 0 1px var(--accent); +} +#panel .tool { + min-height: 36px; + background: #2b2e34; +} + +/* --------------------------------------------------------------- history */ + +/* History docks at the right edge; the right column, cube and popovers slide left of it. */ +#history { + position: fixed; + top: calc(8px + var(--safe-t)); + right: calc(8px + var(--safe-r)); + bottom: calc(8px + var(--safe-b)); + width: 250px; + display: none; + flex-direction: column; + background: var(--chrome); + border-radius: var(--radius); + overflow: hidden; + z-index: 8; +} +#history.open { + display: flex; +} +.history-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 4px 4px 4px 12px; + font-weight: 600; + border-bottom: 1px solid var(--line); +} +.history-head .icon-btn { + background: none; +} +#history-list { + list-style: none; + margin: 0; + padding: 4px; + overflow-y: auto; +} +.history-item { + display: flex; + flex-wrap: wrap; + align-items: center; + border-radius: 8px; +} +.history-item:hover { + background: rgba(255, 255, 255, 0.05); +} +.history-item.active { + background: var(--accent-soft); +} +.history-item.suppressed .history-name { + opacity: 0.45; + text-decoration: line-through; +} +.history-name { + flex: 1; + text-align: left; + min-height: 36px; + padding: 0 10px; +} +.history-item .icon-btn { + background: none; + opacity: 0.55; + width: 32px; + height: 32px; +} +.history-item .icon-btn:hover { + opacity: 1; +} +.history-item.error .history-name { + color: var(--danger); +} +.history-warn { + display: inline-grid; + place-items: center; + width: 16px; + height: 16px; + margin-right: 7px; + border-radius: 50%; + background: var(--danger); + color: white; + font-size: 11px; + font-weight: 700; + vertical-align: 1px; +} +.history-error { + flex-basis: 100%; + padding: 0 10px 8px; + color: var(--danger); + font-size: 12px; +} +.history-empty { + color: var(--muted); + padding: 12px; +} + +body.history-open #right-col { + right: calc(266px + var(--safe-r)); +} +body.history-open #viewcube-host { + right: calc(318px + var(--safe-r)); +} +body.history-open #popover, +body.history-open .measure-card { + right: calc(318px + var(--safe-r)); +} +/* Items docks at the left edge (like History on the right); the tools move right of it. */ +body.items-open #toolbar, +body.items-open #bottom-left { + left: calc(274px + var(--safe-l)); +} + +/* ----------------------------------------------------------------- items */ + +#items { + position: fixed; + top: calc(52px + var(--safe-t)); + left: calc(8px + var(--safe-l)); + bottom: calc(8px + var(--safe-b)); + width: 258px; + display: none; + flex-direction: column; + background: var(--chrome); + border-radius: var(--radius); + overflow: hidden; + z-index: 8; +} +#items.open { + display: flex; +} +#items-list { + list-style: none; + margin: 0; + padding: 4px; + overflow-y: auto; +} +.items-heading { + font-size: 11.5px; + color: var(--muted); + padding: 8px 8px 2px; +} +.items-empty { + color: var(--muted); + padding: 4px 10px 8px; +} +.items-row { + display: flex; + align-items: center; + border-radius: 7px; +} +.items-head-btns { + display: flex; + align-items: center; + gap: 2px; +} +.text-btn.small { + min-height: 28px; + padding: 0 9px; + font-size: 12.5px; + background: none; +} +.text-btn.small.on { + background: var(--accent-soft); + color: #cfe0ff; +} +.items-check { + margin: 0 2px 0 8px; + accent-color: var(--accent); +} +.items-row.checked { + background: var(--accent-soft); +} +.items-row.in-folder { + padding-left: 18px; +} +.folder-row .items-name { + font-weight: 600; +} +.items-count { + color: var(--muted); + font-weight: 400; +} +.items-caret { + color: var(--muted); +} +.items-groupbar { + display: flex; + gap: 6px; + padding: 8px 6px; + position: sticky; + bottom: 0; + background: var(--chrome-solid); + border-top: 1px solid var(--line); +} +.items-row:hover { + background: rgba(255, 255, 255, 0.05); +} +.items-row .icon-btn { + background: none; + width: 32px; + height: 32px; + opacity: 0.6; +} +.items-row .icon-btn:hover { + opacity: 1; +} +.items-name { + flex: 1; + display: flex; + align-items: center; + gap: 8px; + min-height: 34px; + text-align: left; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} +.items-name svg { + width: 17px; + height: 17px; + flex: none; + opacity: 0.8; +} +.hidden-item .items-name, +.isolated-out .items-name { + opacity: 0.4; +} + +/* --------------------------------------------------------------- measure */ + +.measure-card { + position: fixed; + right: calc(60px + var(--safe-r)); + bottom: calc(10px + var(--safe-b)); + width: 280px; + max-height: 50vh; + overflow-y: auto; + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 8px; + z-index: 15; +} +.measure-toggle { + display: flex; + gap: 8px; + align-items: center; + padding: 4px 6px 8px; + color: var(--muted); +} +.measure-row { + display: grid; + grid-template-columns: 1fr auto; + align-items: center; + padding: 6px; + border-radius: 6px; +} +.measure-row:hover { + background: rgba(255, 255, 255, 0.05); +} +.measure-row .icon-btn { + grid-row: 1 / span 2; + grid-column: 2; + background: none; +} +.measure-value { + grid-column: 1; + font: 14px ui-monospace, monospace; +} +.measure-name { + grid-column: 1; + font-size: 11.5px; + color: var(--muted); +} +.measure-empty { + color: var(--muted); + padding: 6px; +} + +/* ---------------------------------------------------------------- dialog */ + +.dialog-back { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.45); + display: grid; + place-items: center; + z-index: 50; +} +.dialog { + width: min(380px, calc(100vw - 24px)); + background: var(--chrome-solid); + border: 1px solid var(--line); + border-radius: 14px; + padding: 16px; + display: flex; + flex-direction: column; + gap: 10px; +} +.dialog-note { + color: var(--muted); + font-size: 12.5px; +} +.dialog-field { + display: flex; + flex-direction: column; + gap: 4px; + color: var(--muted); +} +.dialog-field input { + min-height: 38px; + font: 14px ui-monospace, monospace; + color: var(--text); + background: #2b2e34; + border: 1px solid var(--line); + border-radius: 8px; + padding: 0 10px; + -webkit-user-select: text; + user-select: text; +} +.dialog .panel-buttons { + justify-content: flex-end; +} + +/* ---------------------------------------------------------- small screens */ + +@media (max-width: 720px) { + .brand { + display: none; + } + /* Tool column becomes a scrollable strip along the bottom, labels hidden. */ + #toolbar { + top: auto; + transform: none; + bottom: calc(8px + var(--safe-b)); + left: calc(8px + var(--safe-l)); + right: calc(8px + var(--safe-r)); + flex-direction: row; + overflow-x: auto; + overflow-y: hidden; + max-height: none; + } + #toolbar .tool-label, + #bottom-left .tool-label { + display: none; + } + #bottom-left { + bottom: calc(64px + var(--safe-b)); + /* Right of the undo dock, which keeps the corner. */ + left: calc(128px + var(--safe-l)); + flex-direction: row; + } + #undo-dock { + bottom: calc(64px + var(--safe-b)); + } + .dock-btn { + width: 46px; + height: 40px; + } + .tool { + padding: 0 9px; + } + .tool.has-children::after { + left: 25px; + } + #panel { + bottom: calc(120px + var(--safe-b)); + } + #hint { + top: auto; + bottom: calc(66px + var(--safe-b)); + left: auto; + right: calc(8px + var(--safe-r)); + transform: none; + max-width: calc(100vw - 140px); + font-size: 12px; + text-align: left; + } + #viewcube-host { + right: calc(56px + var(--safe-r)); + transform: scale(0.8); + transform-origin: top right; + } + #history { + left: calc(8px + var(--safe-l)); + right: calc(60px + var(--safe-r)); + bottom: auto; + width: auto; + max-height: 45vh; + } + /* On phones History floats instead of docking. */ + body.history-open #right-col { + right: calc(8px + var(--safe-r)); + } + body.history-open #viewcube-host { + right: calc(56px + var(--safe-r)); + } + body.history-open #popover, + body.history-open .measure-card { + right: calc(60px + var(--safe-r)); + } + /* On phones Items floats over the view instead of docking. */ + #items { + width: auto; + right: calc(60px + var(--safe-r)); + bottom: auto; + max-height: 55vh; + z-index: 34; + background: var(--chrome-solid); + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45); + } + body.items-open #toolbar, + body.items-open #bottom-left { + left: calc(128px + var(--safe-l)); + } + body.items-open #undo-dock { + left: calc(8px + var(--safe-l)); + } + .measure-card { + left: calc(8px + var(--safe-l)); + width: auto; + bottom: calc(120px + var(--safe-b)); + } +} + +/* Steps done inside a sketch, under it in History. */ +.history-steps { + list-style: none; + display: flex; + flex-direction: column; + padding: 0 0 4px 22px; +} +.history-step { + text-align: left; + font-size: 12px; + color: var(--muted, #9aa3b5); + background: none; + border: 0; + padding: 2px 6px; + border-left: 1px solid var(--line); + cursor: pointer; +} +.history-step:hover { + color: var(--text, #e6ebf5); +} +.history-step.more { + cursor: default; + font-style: italic; +} + +/* Orbit centre button, under the view cube. */ +.pivot-btn { + display: block; + margin: 2px auto 0; + width: 30px; + height: 30px; + padding: 5px; + border-radius: 8px; + border: 1px solid var(--line); + background: var(--chrome-solid); + color: var(--muted); + cursor: pointer; +} +.pivot-btn:hover { + color: var(--text); +} +.pivot-btn.on { + color: #fff; + background: #3d8bff; + border-color: #3d8bff; +} +.pivot-cursor { + position: fixed; + left: 0; + top: 0; + width: 22px; + height: 22px; + color: #3d8bff; + pointer-events: none; + z-index: 40; +} +.pivot-cursor[hidden] { + display: none; +} + +/* Pattern count + spacing box. */ +.pattern-box input:first-of-type { + width: 3.2em; +} +.pattern-box select { + margin: 0 4px; +} + +/* Busy indicator: the geometry engine is working. */ +#busy { + position: fixed; + left: 50%; + top: calc(62px + var(--safe-t)); + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 8px; + padding: 6px 12px; + border-radius: 999px; + background: var(--chrome-solid); + border: 1px solid var(--line); + color: var(--text); + font-size: 13px; + z-index: 60; + pointer-events: none; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35); +} +#busy[hidden] { + display: none; +} +#busy .spinner { + width: 14px; + height: 14px; + border-radius: 50%; + border: 2px solid rgba(255, 255, 255, 0.25); + border-top-color: #3d8bff; + animation: busy-spin 0.8s linear infinite; +} +@keyframes busy-spin { + to { + transform: rotate(360deg); + } +} + +/* ------------------------------------------------ phones: nothing overlaps */ +@media (max-width: 720px) { + /* The top bar stops before the right-hand column; the name shrinks to fit. */ + #topbar { + right: calc(60px + var(--safe-r)); + } + .project-name { + flex: 1 1 auto; + width: auto; + min-width: 0; + margin-right: 2px; + padding: 0 8px; + } + #topbar .text-btn { + padding: 0 8px; + } + /* The view cube sits under the top bar, beside the column. */ + #viewcube-host, + body.history-open #viewcube-host { + top: calc(50px + var(--safe-t)); + } + #busy { + top: calc(96px + var(--safe-t)); + } +} +/* Tablets in portrait: the brand gives way so the bar fits beside the column. */ +@media (min-width: 721px) and (max-width: 1100px) { + .brand { + width: auto; + font-size: 20px; + } + .project-name { + width: 220px; + } +} +@media (max-width: 720px) { + /* The hint goes under the top bar, left of the view cube (clear of the bottom buttons). */ + #hint { + top: calc(52px + var(--safe-t)); + bottom: auto; + left: calc(8px + var(--safe-l)); + right: auto; + max-width: calc(100vw - 170px); + } + /* History / Items open under the top bar; the view cube steps aside meanwhile. */ + #history, + #items { + top: calc(52px + var(--safe-t)); + } + body.history-open #viewcube-host, + body.items-open #viewcube-host { + display: none; + } +} +@media (min-width: 721px) and (max-width: 1100px) { + /* The bar ends before the view cube (which keeps its corner); the name shrinks. */ + #topbar { + right: calc(178px + var(--safe-r)); + } + body.history-open #topbar { + right: calc(436px + var(--safe-r)); + } + body.history-open .brand { + display: none; + } + .project-name { + flex: 0 1 220px; + min-width: 80px; + } +} +@media (min-width: 721px) and (max-width: 1100px) { + /* History docked leaves no room for the hint line: it steps aside until History closes. */ + body.history-open #hint { + display: none; + } +} diff --git a/src/tools/annotate.ts b/src/tools/annotate.ts new file mode 100644 index 0000000..74c5f8b --- /dev/null +++ b/src/tools/annotate.ts @@ -0,0 +1,292 @@ +// 3D dimension annotations: a dimension line with arrowheads, an optional +// floating input (Total/Offset + value + pin), and the layer of pinned measurements. + +import { BufferGeometry, ConeGeometry, Group, Line, LineBasicMaterial, LineDashedMaterial, Mesh, MeshBasicMaterial, Vector3 } from "three"; +import type { PinDef, Vec3 } from "../doc/types"; +import { el } from "../ui/ui"; +import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units"; +import type { Viewport } from "../view/viewport"; + +const COLOR = 0xdfe6f3; + +/** Dashed line a→b with screen-constant arrowheads at both ends. */ +class DimLine { + readonly group = new Group(); + private line: Line; + private heads: Mesh[]; + private a = new Vector3(); + private b = new Vector3(); + + constructor( + private view: Viewport, + color = COLOR, + private solid = false, + ) { + const opts = { color, depthTest: false, transparent: true }; + this.line = new Line(new BufferGeometry(), solid ? new LineBasicMaterial(opts) : new LineDashedMaterial({ ...opts, dashSize: 1, gapSize: 1 })); + this.line.renderOrder = 11; + const mat = new MeshBasicMaterial({ color, depthTest: false, transparent: true }); + this.heads = [0, 1].map(() => { + const m = new Mesh(new ConeGeometry(0.35, 1, 12), mat); + m.renderOrder = 11; + return m; + }); + this.group.add(this.line, ...this.heads); + } + + set(a: Vec3, b: Vec3): void { + this.a.set(...a); + this.b.set(...b); + this.line.geometry.setFromPoints([this.a, this.b]); + this.layout(); + } + + layout(): void { + const wpp = this.view.cam.worldPerPixel(this.view.height); + if (!this.solid) { + const mat = this.line.material as LineDashedMaterial; + mat.dashSize = wpp * 6; + mat.gapSize = wpp * 4; + this.line.computeLineDistances(); + } + const dir = this.b.clone().sub(this.a); + const len = dir.length(); + const show = len > wpp * 20; + dir.normalize(); + const s = wpp * 11; + for (const [i, h] of this.heads.entries()) { + h.visible = show; + h.scale.setScalar(s); + // Cone points +Y; tips sit on the ends, pointing outwards. + const out = i === 0 ? dir.clone().negate() : dir.clone(); + h.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), out); + h.position.copy(i === 0 ? this.a : this.b).addScaledVector(out, -s / 2); + } + } + + dispose(): void { + this.line.geometry.dispose(); + this.heads.forEach((h) => h.geometry.dispose()); + } +} + +export interface DimWidgetOptions { + value: number; + modes?: { id: string; label: string }[]; + mode?: string; + onMode?(id: string): void; + onInput?(v: number): void; + onCommit?(): void; + onPin?(): void; + /** Text to restore into the input (when another tool takes over while typing). */ + typed?: string; + focus?: boolean; + /** Draw the dimension as a solid line of this colour (it *is* the geometry, e.g. a line being drawn). */ + solidColor?: number; + /** + * Keep the value box off the geometry: "side" puts it beside the middle of + * the dimension, "beyond" past its end b (e.g. outside a fillet arc). + */ + boxAt?: "middle" | "side" | "beyond"; + /** Extra screen distance past the end for "beyond" (e.g. to clear a drag arrow there). */ + boxGap?: number; + /** Which way "beyond" goes when the dimension has no length yet (e.g. the arrow's direction). */ + dir?: Vec3; +} + +/** + * A dimension in the viewport: dashed line with arrows and, at its middle, + * a small editable value with an optional mode dropdown and a pin button. + */ +export class DimWidget { + private line: DimLine; + private box = el("div", "dim-widget"); + private input = document.createElement("input"); + private mid = new Vector3(); + private ends: [Vector3, Vector3] = [new Vector3(), new Vector3()]; + private boxAt: "middle" | "side" | "beyond"; + private boxGap: number; + private dir?: Vec3; + private hook = () => this.layout(); + + constructor( + private view: Viewport, + opts: DimWidgetOptions, + ) { + this.line = opts.solidColor !== undefined ? new DimLine(view, opts.solidColor, true) : new DimLine(view); + this.boxAt = opts.boxAt ?? "middle"; + this.boxGap = opts.boxGap ?? 0; + this.dir = opts.dir; + view.overlay.add(this.line.group); + if (opts.modes) { + const sel = document.createElement("select"); + for (const m of opts.modes) { + const o = document.createElement("option"); + o.value = m.id; + o.textContent = m.label; + sel.append(o); + } + sel.value = opts.mode ?? opts.modes[0].id; + sel.addEventListener("change", () => opts.onMode?.(sel.value)); + this.box.append(sel); + } + this.input.inputMode = "decimal"; + this.input.spellcheck = false; + this.input.value = opts.typed ?? trim(toDisplay(opts.value), 3); + this.input.readOnly = !opts.onInput; + this.input.addEventListener("input", () => { + const v = evaluate(this.input.value, "length"); + this.input.classList.toggle("invalid", v === null); + if (v !== null) opts.onInput?.(v); + }); + this.input.addEventListener("keydown", (e) => { + e.stopPropagation(); + if (e.key === "Enter") opts.onCommit?.(); + if (e.key === "Escape") this.input.blur(); + }); + this.box.append(this.input, el("span", "dim-unit", UNIT_LABEL[units()])); + if (opts.onPin) { + const pin = el("button", "dim-pin", "📌"); + pin.title = "Pin this measurement"; + pin.addEventListener("click", () => opts.onPin!()); + this.box.append(pin); + } + // Clicks on the widget must not reach the viewport. + this.box.addEventListener("pointerdown", (e) => e.stopPropagation()); + document.body.append(this.box); + view.frameHooks.add(this.hook); + view.helpers.add(this); + if (opts.focus) { + setTimeout(() => { + this.input.focus(); + const n = this.input.value.length; + this.input.setSelectionRange(n, n); + }, 0); + } + } + + get text(): string { + return this.input.value; + } + + set(a: Vec3, b: Vec3): void { + this.line.set(a, b); + this.ends[0].set(...a); + this.ends[1].set(...b); + this.mid.set((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2); + this.layout(); + this.view.requestRender(); + } + + setValue(v: number): void { + if (document.activeElement !== this.input) this.input.value = trim(toDisplay(v), 3); + this.box.classList.remove("typing", "invalid"); + } + + /** Start typing into the box with this first character (keys pressed elsewhere). */ + focusWith(ch: string): void { + this.input.value = ch; + this.input.focus(); + this.input.setSelectionRange(1, 1); + this.input.dispatchEvent(new Event("input")); + } + + /** Mark the value as not usable (e.g. a fillet radius too big for the lines). */ + markInvalid(bad: boolean): void { + this.box.classList.toggle("invalid", bad); + } + + /** Text typed elsewhere (keys while drawing), shown in the box with a caret. */ + setText(text: string, invalid = false): void { + if (document.activeElement === this.input) return; + this.input.value = text; + this.box.classList.add("typing"); + this.box.classList.toggle("invalid", invalid); + } + + private layout(): void { + this.line.layout(); + let s = this.view.toScreen(this.mid); + const sa = this.view.toScreen(this.ends[0]); + const sb = this.view.toScreen(this.ends[1]); + if (s && sa && sb && this.boxAt !== "middle") { + let dx = sb[0] - sa[0]; + let dy = sb[1] - sa[1]; + // No length yet: use the given direction on screen. + if (Math.hypot(dx, dy) < 2 && this.dir) { + const e = this.view.toScreen(this.ends[1].clone().add(new Vector3(...this.dir).multiplyScalar(this.view.cam.worldPerPixel(this.view.height) * 50))); + if (e) [dx, dy] = [e[0] - sb[0], e[1] - sb[1]]; + } + const l = Math.hypot(dx, dy) || 1; + const half = { w: this.box.offsetWidth / 2 + 10, h: this.box.offsetHeight / 2 + 10 }; + if (this.boxAt === "beyond") { + // Past the end, far enough that the box's own size clears it. + const k = Math.abs((dx / l) * half.w) + Math.abs((dy / l) * half.h) + this.boxGap; + s = [sb[0] + (dx / l) * k, sb[1] + (dy / l) * k]; + } else { + // Beside the middle, on the upper side of the line. + let n: [number, number] = [-dy / l, dx / l]; + if (n[1] > 0) n = [-n[0], -n[1]]; + const k = Math.abs(n[0] * half.w) + Math.abs(n[1] * half.h); + s = [s[0] + n[0] * k, s[1] + n[1] * k]; + } + } + this.box.hidden = !s; + if (s) this.box.style.transform = `translate(${Math.round(s[0])}px, ${Math.round(s[1])}px) translate(-50%, -50%)`; + } + + dispose(): void { + this.view.helpers.delete(this); + this.view.frameHooks.delete(this.hook); + this.view.overlay.remove(this.line.group); + this.line.dispose(); + this.box.remove(); + this.view.requestRender(); + } +} + +/** Pinned measurements: label + (optional) dimension line, always on top. */ +export class PinLayer { + private group = new Group(); + private lines: DimLine[] = []; + private labels: HTMLElement[] = []; + private pins: PinDef[] = []; + private visible = true; + private host = document.getElementById("pins")!; + + constructor(private view: Viewport) { + view.overlay.add(this.group); + view.frameHooks.add(() => this.layout()); + } + + set(pins: PinDef[], visible: boolean): void { + this.lines.forEach((l) => (this.group.remove(l.group), l.dispose())); + this.labels.forEach((l) => l.remove()); + this.pins = pins; + this.visible = visible; + this.lines = []; + this.labels = pins.map((p) => { + if (p.a && p.b) { + const l = new DimLine(this.view, 0x8fb4ff); + l.set(p.a, p.b); + this.group.add(l.group); + this.lines.push(l); + } + const tag = el("div", "pin", p.text); + this.host.append(tag); + return tag; + }); + this.group.visible = visible; + this.view.requestRender(); + } + + private layout(): void { + this.lines.forEach((l) => l.layout()); + this.pins.forEach((p, i) => { + const s = this.view.toScreen(p.at); + const tag = this.labels[i]; + tag.hidden = !this.visible || !s; + if (s) tag.style.transform = `translate(${Math.round(s[0])}px, ${Math.round(s[1])}px) translate(-50%, -50%)`; + }); + } +} diff --git a/src/tools/copyToggle.ts b/src/tools/copyToggle.ts new file mode 100644 index 0000000..b1f7918 --- /dev/null +++ b/src/tools/copyToggle.ts @@ -0,0 +1,60 @@ +// The Copy switch next to a Move/Rotate gimbal. While it's on, a gimbal drag +// leaves the original where it was and makes a copy; the copy is then +// selected, so the next drag (or typed value + Enter) copies again. + +import type { Vec3 } from "../doc/types"; +import { icons } from "../ui/icons"; +import type { Viewport } from "../view/viewport"; + +/** Shared by bodies, sketches and images: the switch stays as you left it. */ +export const copyMode = { on: false }; + +export class CopyToggle { + private btn = document.createElement("button"); + private hook = () => this.layout(); + + constructor( + private view: Viewport, + /** Where the gimbal is (world). */ + private at: () => Vec3 | null, + private onChange?: (on: boolean) => void, + ) { + this.btn.className = "copy-toggle"; + this.btn.title = "Copy: drag to make copies (each Enter or release makes one, then keep dragging)"; + this.btn.innerHTML = `${icons.copy}Copy`; + // Never let the press reach the viewport (it would start a drag or deselect). + this.btn.addEventListener("pointerdown", (e) => e.stopPropagation()); + this.btn.addEventListener("click", (e) => { + e.stopPropagation(); + copyMode.on = !copyMode.on; + this.paint(); + this.onChange?.(copyMode.on); + }); + this.paint(); + document.body.append(this.btn); + view.frameHooks.add(this.hook); + view.helpers.add(this); + this.layout(); + } + + private paint(): void { + this.btn.classList.toggle("on", copyMode.on); + } + + private layout(): void { + const w = this.at(); + const s = w && this.view.toScreen(w); + this.btn.hidden = !s; + if (s) { + const r = this.view.canvas.getBoundingClientRect(); + // Up and to the right of the gimbal, clear of its arrows. + this.btn.style.transform = `translate(${Math.round(r.left + s[0] + 70)}px, ${Math.round(r.top + s[1] - 96)}px)`; + } + } + + dispose(): void { + this.view.helpers.delete(this); + this.view.frameHooks.delete(this.hook); + this.btn.remove(); + } +} diff --git a/src/tools/dragTyping.ts b/src/tools/dragTyping.ts new file mode 100644 index 0000000..592838a --- /dev/null +++ b/src/tools/dragTyping.ts @@ -0,0 +1,86 @@ +// Type a value while holding a drag: digits set the value live, Enter applies +// it and finishes, Esc drops what was typed. "," is accepted as decimal point. + +import { evaluate, UNIT_LABEL, units } from "../units"; +import type { ToolPointer } from "../view/input"; +import type { AppContext } from "./tool"; + +export interface DragTypingTarget { + kind: "length" | "angle" | "number"; + /** Apply a typed value (mm for lengths, degrees for angles). */ + apply(v: number): void; + /** Enter: finish with the current value. */ + commit(): void; + /** Esc: drop the typed text and go back to following the pointer. */ + cancel?(): void; + /** Tab: move to the next dimension (e.g. rectangle width → height). */ + next?(): boolean; + /** Show the typed text somewhere else than the pointer label (e.g. a dimension box). */ + show?(text: string, invalid: boolean): void; +} + +export class DragTyping { + text = ""; + private at: { x: number; y: number } = { x: 0, y: 0 }; + + constructor(private app: AppContext) {} + + /** While text is typed, pointer motion shouldn't change the value. */ + get active(): boolean { + return this.text.length > 0; + } + + /** Remember where the pointer is (the typed value is shown next to it). */ + track(p: ToolPointer): void { + this.at = { x: p.x, y: p.y }; + if (this.active) this.show(); + } + + reset(): void { + this.text = ""; + } + + /** Handle a key during a drag; true if it was used. */ + key(e: KeyboardEvent, t: DragTypingTarget): boolean { + if (e.ctrlKey || e.metaKey || e.altKey) return false; + this.display = t.show ?? null; + this.unit = t.kind === "length" ? UNIT_LABEL[units()] : t.kind === "angle" ? "°" : ""; + if (e.key === "Enter") { + this.text = ""; + this.app.ui.setLabel(0, 0, null); + t.commit(); + return true; + } + if (e.key === "Escape") { + if (!this.text) return false; + this.text = ""; + this.app.ui.setLabel(0, 0, null); + t.cancel?.(); + return true; + } + if (e.key === "Tab") { + if (!t.next?.()) return false; + this.text = ""; + this.show(); + return true; + } + if (e.key === "Backspace") { + this.text = this.text.slice(0, -1); + } else if (e.key.length === 1 && /[0-9.,+\-*/()a-z"' ]/i.test(e.key)) { + this.text += e.key === "," ? "." : e.key; + } else return false; + const v = this.text ? evaluate(this.text, t.kind) : null; + if (v !== null) t.apply(v); + else if (!this.text) t.cancel?.(); + this.show(v === null && !!this.text); + return true; + } + + private unit = ""; + private display: DragTypingTarget["show"] | null = null; + + private show(invalid = false): void { + if (this.display) return this.display(this.text, invalid); + this.app.ui.setLabel(this.at.x, this.at.y, this.text ? `${this.text}▌ ${this.unit}${invalid ? " ?" : ""}` : null); + } +} diff --git a/src/tools/featureOp.ts b/src/tools/featureOp.ts new file mode 100644 index 0000000..2392028 --- /dev/null +++ b/src/tools/featureOp.ts @@ -0,0 +1,258 @@ +import { getPath, setPath } from "../doc/params"; +import type { ExtrudeSource, Feature } from "../doc/types"; +import type { FieldKind, PanelItem, ToolItem } from "../ui/ui"; +import type { ToolPointer } from "../view/input"; +import type { PickHit, PickOptions } from "../view/viewport"; +import { hitToSel, type AppContext, type Sel, type Tool } from "./tool"; + +/** Something the user has to point at (an axis, a path, faces to remove, …). */ +export interface Slot { + label: string; + /** What the slot shows: "X axis", "2 faces", "Select…". */ + describe(): string; + filled(): boolean; + pick: PickOptions; + /** Store the hit into the draft; return false if it doesn't fit this slot. */ + accept(hit: PickHit): boolean; + multi?: boolean; + /** Quick choices shown next to the slot (e.g. X / Y / Z). */ + presets?: { label: string; apply(): void }[]; + /** Highlights of what the slot currently holds. */ + shows?(): Sel[]; + /** Show the XY/XZ/YZ planes while this slot is waiting for a pick. */ + originPlanes?: boolean; + /** Said when a tap hits something this slot can't take. */ + rejectHint?: string; +} + +/** + * Base for tools that create or edit one feature: pick slots + numbers + + * live preview + Done/Cancel. Subclasses describe the draft; this does the rest. + */ +export abstract class FeatureOp implements Tool { + abstract readonly id: string; + feature: F; + protected slots: Slot[] = []; + protected active = -1; + protected error: string | null = null; + + constructor( + protected app: AppContext, + draft: F, + protected existing?: F, + ) { + this.feature = existing ? structuredClone(existing) : draft; + } + + get editingId(): string { + return this.feature.id; + } + + /** One-line instruction for the hint bar. */ + protected abstract hint(): string; + /** Numbers / choices / toggles in the panel. */ + protected abstract items(): PanelItem[]; + /** Is the draft complete enough to preview and commit? */ + protected ready(): boolean { + return this.slots.every((s) => s.filled()); + } + /** Extra panel buttons. */ + protected actions(): ToolItem[] { + return []; + } + + enter(): void { + this.app.ui.setTools([{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.app.setTool(null) }]); + this.app.ui.setBottom([]); + this.active = this.slots.findIndex((s) => !s.filled()); + this.render(); + this.update(); + this.app.ui.focusPanel(); + } + + exit(): void { + this.app.view.setOriginPlanesVisible(false); + this.app.ui.showPanel(null); + this.app.ui.setHint(null); + this.app.ui.setLabel(0, 0, null); + this.app.setHover(null); + this.app.setSelection([]); + } + + hover(p: ToolPointer | null): void { + const slot = this.slots[this.active]; + if (!p || !slot) return this.app.setHover(null); + const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...slot.pick }); + this.lastHover = { x: p.x, y: p.y, hit }; + this.app.setHover(hitToSel(hit)); + } + + /** What hover highlighted: a tap at the same spot takes exactly that. */ + private lastHover: { x: number; y: number; hit: PickHit | null } | null = null; + + tap(p: ToolPointer): void { + const slot = this.slots[this.active]; + const h = this.lastHover; + const hit = h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6 ? h.hit : this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}) }); + // Tapping empty space ends the tool: keep the result if it's complete. + if (!hit) { + if (this.ready()) this.done(); + else this.app.setTool(null); + return; + } + if (!slot) return; + if (!slot.accept(hit)) { + if (slot.rejectHint) this.app.ui.toast(slot.rejectHint); + return; + } + if (!slot.multi) this.active = this.slots.findIndex((s, i) => i > this.active && !s.filled()); + this.render(); + if (this.finishWhenPicked && this.ready()) return void this.finishIfOk(); + this.update(); + } + + /** Nothing left to set once the picks are made (e.g. Replace Face): the last pick finishes. */ + protected finishWhenPicked = false; + + private async finishIfOk(): Promise { + this.onDraftChanged(); + const r = await this.app.preview(this.featuresWith()); + const err = r?.errors.find((e) => e.featureId === this.feature.id)?.message; + if (err) { + this.error = err; + this.setHint(); + this.app.ui.toast(err); + return; + } + this.done(); + } + + key(e: KeyboardEvent): boolean { + if (e.key === "Enter") this.done(); + else if (e.key === "Escape") this.app.setTool(null); + else return false; + return true; + } + + /** Rebuild the panel (after slots/choices change). */ + protected render(): void { + const slotItems: PanelItem[] = this.slots.flatMap((s, i): PanelItem[] => [ + { type: "slot", label: s.label, value: s.describe(), active: i === this.active, filled: s.filled(), onClick: () => ((this.active = i), this.render()) }, + ...(s.presets?.length && i === this.active + ? [{ type: "choice" as const, options: s.presets.map((p, k) => ({ id: String(k), label: p.label })), value: "", onChange: (k: string) => (s.presets![Number(k)].apply(), this.advance(), this.render(), this.update()) }] + : []), + ]); + this.app.ui.showPanel({ + title: this.feature.name, + items: [...slotItems, ...this.items()], + actions: this.actions(), + onDone: () => this.done(), + onCancel: () => this.app.setTool(null), + }); + this.showSlotHighlights(); + this.setHint(); + this.app.view.setOriginPlanesVisible(!!this.slots[this.active]?.originPlanes); + } + + private advance(): void { + const s = this.slots[this.active]; + if (s && !s.multi) this.active = this.slots.findIndex((x, i) => i > this.active && !x.filled()); + } + + private showSlotHighlights(): void { + this.app.setSelection(this.slots.flatMap((s) => s.shows?.() ?? [])); + } + + private setHint(): void { + const slot = this.slots[this.active]; + const text = this.error ? `⚠ ${this.error}` : slot && !slot.filled() ? `${slot.label}: ${slot.describe()}` : this.hint(); + this.app.ui.setHint(text); + } + + /** Re-run the preview with the current draft. */ + protected update(): void { + this.onDraftChanged(); + if (!this.ready()) { + this.app.preview([...this.app.store.features]); + return; + } + this.app.preview(this.featuresWith()).then((r) => { + this.error = r?.errors.find((e) => e.featureId === this.feature.id)?.message ?? null; + this.setHint(); + }); + } + + /** Hook for handles etc. */ + protected onDraftChanged(): void {} + + /** + * A number field bound to a path in the feature (e.g. "distance", + * "op.translate.2") that can also hold a variable expression. + */ + protected num(label: string, path: string, kind: FieldKind, opts: { min?: number; onInput?: (v: number) => void } = {}): PanelItem { + const f = this.feature as Feature; + return { + type: "number", + label, + value: Number(getPath(f, path) ?? 0), + kind, + min: opts.min, + expr: f.exprs?.[path], + onExpr: (expr) => { + const exprs = { ...(f.exprs ?? {}) }; + if (expr) exprs[path] = expr; + else delete exprs[path]; + f.exprs = Object.keys(exprs).length ? exprs : undefined; + }, + onInput: (v) => { + setPath(f, path, v); + if (opts.onInput) opts.onInput(v); + else this.update(); + }, + }; + } + + protected featuresWith(): Feature[] { + const list = [...this.app.store.features]; + if (!this.existing) return [...list, this.feature]; + list[list.findIndex((f) => f.id === this.feature.id)] = this.feature; + return list; + } + + protected done(): void { + if (!this.ready()) { + const missing = this.slots.find((s) => !s.filled()); + // Nothing left to pick means nothing changed: just close the tool. + if (!missing) return this.app.setTool(null); + this.app.ui.toast("Finish picking first: " + missing.label); + return; + } + if (this.existing) this.app.store.update(this.feature.id, this.feature); + else { + // A new solid from sketches: the sketches step out of the way (the eye in Items brings them back). + const used = sketchesUsed(this.feature as Feature); + const f = this.feature as Feature; + this.app.store.commit((d) => { + d.features.push(f); + if (used.length) d.hidden = [...new Set([...d.hidden, ...used])]; + }); + } + this.app.setTool(null); + } +} + +/** The sketches an extrude / revolve / sweep / loft was made from. */ +function sketchesUsed(f: Feature): string[] { + const of = (s: ExtrudeSource) => (s.kind === "profile" ? [s.sketch] : []); + switch (f.type) { + case "extrude": + case "revolve": + return of(f.source); + case "sweep": + return [...of(f.source), ...(f.path.kind === "sketch" ? [f.path.sketch] : [])]; + case "loft": + return f.sections.flatMap(of); + default: + return []; + } +} diff --git a/src/tools/freeform.ts b/src/tools/freeform.ts new file mode 100644 index 0000000..caa4c34 --- /dev/null +++ b/src/tools/freeform.ts @@ -0,0 +1,629 @@ +// Freeform: shape a smooth body by pulling its control cage. Tap cage points, +// edges or faces (Shift adds), then drag the gimbal — or type a value while +// dragging. The smooth surface updates live; Done turns it into a body. + +import { BufferAttribute, BufferGeometry, DoubleSide, LineBasicMaterial, LineSegments, Mesh, MeshStandardMaterial, Points, Raycaster, Vector2 } from "three"; +import type { Feature, FreeformFeature, TransformFeature, Vec3 } from "../doc/types"; +import { boundaryEdges, bridgeLoops, cageEdgeKey, cageEdges, deleteFaces, fillLoop, holeLoops, isClosed, previewMesh, primitiveCage, subdivide, type Cage, type CagePrimitive } from "../freeform/cage"; +import { add, cross, dot, len, niceStep, norm, scale, sub, xDirFor } from "../geom"; +import type { PanelItem } from "../ui/ui"; +import { fmtLen } from "../units"; +import type { ToolPointer } from "../view/input"; +import { dotMaterial } from "../view/viewport"; +import { DragTyping } from "./dragTyping"; +import { Gimbal, GIMBAL_AXES, type GimbalPart } from "./gimbal"; +import { axisDrag } from "./handles"; +import type { AppContext, Tool } from "./tool"; + +type Pick = { kind: "vert"; i: number } | { kind: "edge"; e: [number, number] } | { kind: "face"; f: number }; + +const SEL = 0xffa31a; +const HOVER = 0xffd27a; + +export class FreeformTool implements Tool { + readonly id = "freeform"; + private cage: Cage; + private existing?: FreeformFeature; + private picks: Pick[] = []; + private hovered: Pick | null = null; + private gimbal: Gimbal | null = null; + private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number } | null = null; + private typing: DragTyping; + private uniform = 1; + /** Moves applied to the body later in History: the cage is shown (and edited) where the body is. */ + private place: Placement = { fwd: (v) => v, inv: (v) => v }; + private surfaceSheet = false; + private thickness = 0; + private thickSide: "up" | "down" | "both" = "up"; + /** A new shape that spawned inside another body: first moved into place as a whole. */ + private placing = false; + + // Scene objects. + private surface = new Mesh(new BufferGeometry(), new MeshStandardMaterial({ color: 0xb9c6dc, roughness: 0.5, metalness: 0.05, side: DoubleSide, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 })); + private lines = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: 0x5f8fe8, transparent: true, opacity: 0.85, depthTest: false })); + private dots = new Points(new BufferGeometry(), dotMaterial({ color: 0xffffff, size: 8 })); + private marks = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: SEL, depthTest: false, linewidth: 2 })); + private markDots = new Points(new BufferGeometry(), dotMaterial({ color: SEL, size: 12 })); + private hoverMarks = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: HOVER, depthTest: false })); + private hoverDots = new Points(new BufferGeometry(), dotMaterial({ color: HOVER, size: 12 })); + + constructor( + private app: AppContext, + from: { primitive: CagePrimitive } | { feature: FreeformFeature }, + ) { + if ("feature" in from) { + this.existing = from.feature; + this.place = placementOf(app.store.features, from.feature.id); + const c = structuredClone(from.feature.cage); + this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd) }; + this.surfaceSheet = !!from.feature.surface; + this.thickness = from.feature.thickness ?? 0; + this.thickSide = from.feature.thickSide ?? "up"; + } else { + this.cage = primitiveCage(from.primitive); + this.surfaceSheet = from.primitive === "plane"; + } + this.typing = new DragTyping(app); + this.lines.renderOrder = 11; + this.dots.renderOrder = 12; + for (const o of [this.marks, this.markDots, this.hoverMarks, this.hoverDots]) o.renderOrder = 13; + } + + get editingId(): string | undefined { + return this.existing?.id; + } + + enter(): void { + const view = this.app.view; + view.overlay.add(this.surface, this.lines, this.dots, this.marks, this.markDots, this.hoverMarks, this.hoverDots); + // Editing an existing freeform: hide its finished body while the cage is out. + if (this.existing) view.setHidden(new Set([...this.app.store.doc.hidden, this.existing.id])); + this.app.setSelection([]); + this.app.ui.setTools([{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.cancel() }]); + this.app.ui.setBottom([]); + this.rebuild(); + if (!this.existing && this.overlapsBodies()) { + // Grab the whole shape first; point editing starts after it's been moved. + this.placing = true; + this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i })); + this.drawMarks(); + this.placeGimbal(); + } + this.panel(); + this.hint(); + } + + /** Does the cage's box overlap any visible body's box? */ + private overlapsBodies(): boolean { + const lo = [0, 1, 2].map((k) => Math.min(...this.cage.verts.map((v) => v[k]))); + const hi = [0, 1, 2].map((k) => Math.max(...this.cage.verts.map((v) => v[k]))); + const hidden = new Set(this.app.store.doc.hidden); + return this.app.view.bodyList.some((b) => { + if (hidden.has(b.id) || !b.positions.length) return false; + for (let k = 0; k < 3; k++) { + let mn = Infinity; + let mx = -Infinity; + for (let i = k; i < b.positions.length; i += 3) { + mn = Math.min(mn, b.positions[i]); + mx = Math.max(mx, b.positions[i]); + } + if (mx < lo[k] || mn > hi[k]) return false; + } + return true; + }); + } + + exit(): void { + const view = this.app.view; + for (const o of [this.surface, this.lines, this.dots, this.marks, this.markDots, this.hoverMarks, this.hoverDots]) { + view.overlay.remove(o); + o.geometry.dispose(); + } + this.gimbal?.dispose(); + this.gimbal = null; + view.setHidden(new Set(this.app.store.doc.hidden)); + this.app.ui.showPanel(null); + this.app.ui.setHint(null); + this.app.ui.setLabel(0, 0, null); + view.requestRender(); + } + + private hint(): void { + if (this.placing) return this.app.ui.setHint("It's inside another body: drag the gimbal to move it into place first. Then tap points, edges or faces to shape it."); + this.app.ui.setHint( + this.picks.length + ? "Drag the gimbal to move or turn the selection (type a value while dragging). Shift+tap adds. Tap empty space to deselect." + : "Tap cage points, edges or faces to select them (Shift adds). Done turns the shape into a body.", + ); + } + + private panel(): void { + const n = this.selectedVerts().length; + const items: PanelItem[] = []; + if (n) items.push({ type: "number", label: "Scale", value: 1, kind: "number", min: 0.01, onInput: (v) => this.scaleSelection(v) }); + const faces = this.picks.filter((p) => p.kind === "face").length; + if (faces) items.push({ type: "button", label: `Delete face${faces > 1 ? "s" : ""}`, icon: "trash", onClick: () => this.deleteSelectedFaces() }); + // Rim edges of holes picked: one hole → Fill, two facing holes → Bridge. + const loops = this.pickedLoops(); + if (loops.length === 1) items.push({ type: "button", label: "Fill hole", icon: "fill", onClick: () => this.fillHoles(loops) }); + if (loops.length === 2) items.push({ type: "button", label: "Bridge holes", icon: "loft", onClick: () => this.fillHoles(loops) }); + // An open shape can be given a thickness to become a solid. + if (!isClosed(this.cage)) { + items.push( + { type: "number", label: "Thickness", value: this.thickness, kind: "length", min: 0, onInput: (v) => ((this.thickness = Math.max(0, v)), this.panelHint()) }, + { type: "choice", options: [{ id: "up", label: "Up" }, { id: "down", label: "Down" }, { id: "both", label: "Symmetric" }], value: this.thickSide, onChange: (v) => ((this.thickSide = v as typeof this.thickSide), this.panel()) }, + ); + } + this.uniform = 1; + this.app.ui.showPanel({ + title: `Freeform${n ? ` · ${n} point${n > 1 ? "s" : ""}` : ""}`, + items, + actions: [{ id: "all", label: "Select all", icon: "pointer", run: () => ((this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i }))), this.selectionChanged()) }], + onDone: () => this.done(), + onCancel: () => this.cancel(), + }); + } + + private panelHint(): void { + if (!isClosed(this.cage)) this.app.ui.setHint(this.thickness > 0 ? `Done makes a solid ${fmtLen(this.thickness)} thick.` : "Open shape: Done makes a surface. Give it a Thickness to make a solid."); + } + + /** Holes whose rim edges are all picked (edges, or the points along them). */ + private pickedLoops(): number[][] { + const verts = new Set(this.selectedVerts()); + const chosen = new Set(); + for (const [a, b] of boundaryEdges(this.cage)) if (verts.has(a) && verts.has(b)) chosen.add(cageEdgeKey(a, b)); + return chosen.size ? holeLoops(this.cage, chosen) : []; + } + + private deleteSelectedFaces(): void { + const faces = this.picks.flatMap((p) => (p.kind === "face" ? [p.f] : [])); + if (!faces.length) return; + if (faces.length >= this.cage.faces.length) return this.app.ui.toast("At least one face has to stay"); + this.cage = deleteFaces(this.cage, faces); + this.picks = []; + this.rebuild(); + this.selectionChanged(); + this.panelHint(); + } + + private fillHoles(loops: number[][]): void { + const next = loops.length === 2 ? bridgeLoops(this.cage, loops[0], loops[1]) : fillLoop(this.cage, loops[0]); + if (!next) return this.app.ui.toast(loops.length === 2 ? "Bridging needs two holes with the same number of edges" : "Fill needs a hole with an even number of edges"); + this.cage = next; + this.picks = []; + this.rebuild(); + this.selectionChanged(); + } + + // --------------------------------------------------------------- picking + + private selectedVerts(): number[] { + const s = new Set(); + for (const p of this.picks) { + if (p.kind === "vert") s.add(p.i); + else if (p.kind === "edge") p.e.forEach((i) => s.add(i)); + else this.cage.faces[p.f].forEach((i) => s.add(i)); + } + return [...s]; + } + + /** How far along the pointer's ray the smooth surface is (∞ if missed). */ + private surfaceDepth(p: ToolPointer): number { + const view = this.app.view; + const r = view.canvas.getBoundingClientRect(); + this.ray.setFromCamera(new Vector2((p.x / r.width) * 2 - 1, -(p.y / r.height) * 2 + 1), view.cam.camera); + return this.ray.intersectObject(this.surface, false)[0]?.distance ?? Infinity; + } + private ray = new Raycaster(); + + /** + * Nearest cage point, else edge, else the frontmost face under the pointer. + * Points and edges behind the smooth surface (the far side) don't count. + */ + private pickAt(p: ToolPointer): Pick | null { + const view = this.app.view; + const scr = this.cage.verts.map((v) => view.toScreen(v)); + const tol = Math.max(10, p.tol * 1.3); + const eye = view.cam.camera.position.toArray() as Vec3; + const wall = this.surfaceDepth(p); + const visible = (q: Vec3) => len(sub(q, eye)) < wall + 1e-6; + let best: { d: number; i: number } | null = null; + scr.forEach((s, i) => { + if (!s || !visible(this.cage.verts[i])) return; + const d = Math.hypot(s[0] - p.x, s[1] - p.y); + if (d < tol && (!best || d < best.d)) best = { d, i }; + }); + if (best) return { kind: "vert", i: (best as { i: number }).i }; + let bestE: { d: number; e: [number, number] } | null = null; + for (const e of cageEdges(this.cage)) { + const a = scr[e[0]]; + const b = scr[e[1]]; + if (!a || !b) continue; + const { d, t } = segDist(p.x, p.y, a, b); + const at = add(this.cage.verts[e[0]], scale(sub(this.cage.verts[e[1]], this.cage.verts[e[0]]), t)); + if (d < p.tol && visible(at) && (!bestE || d < bestE.d)) bestE = { d, e }; + } + if (bestE) return { kind: "edge", e: (bestE as { e: [number, number] }).e }; + // Faces: inside the projected quad; nearest to the camera wins. + let bestF: { d: number; f: number } | null = null; + this.cage.faces.forEach((f, fi) => { + const q = f.map((i) => scr[i]); + if (q.some((s) => !s) || !inPoly(p.x, p.y, q as [number, number][])) return; + const c = scale(f.reduce((s, i) => add(s, this.cage.verts[i]), [0, 0, 0] as Vec3), 0.25); + const d = len(sub(c, eye)); + if (!bestF || d < bestF.d) bestF = { d, f: fi }; + }); + return bestF ? { kind: "face", f: (bestF as { f: number }).f } : null; + } + + hover(p: ToolPointer | null): void { + if (this.dragging) return; + const g = p && this.gimbal?.hit(p); + this.gimbal?.setHot(g ?? null); + this.hovered = p && !g ? this.pickAt(p) : null; + this.app.view.canvas.style.cursor = g ? "grab" : ""; + this.drawMarks(); + } + + tap(p: ToolPointer, count = 1): void { + // Double-tap: finish and select the whole body (e.g. to move or colour it). + if (count >= 2) { + const id = this.done(); + if (id) this.app.setSelection([{ kind: "body", body: id }]); + return; + } + // A tap while placing: they'd rather edit right away. + if (this.placing) { + this.placing = false; + this.picks = []; + } + const hit = this.pickAt(p); + if (!hit) { + // Empty space: deselect; with nothing selected, finish. + if (this.picks.length) return ((this.picks = []), this.selectionChanged()); + this.done(); + return; + } + const key = JSON.stringify(hit); + const i = this.picks.findIndex((x) => JSON.stringify(x) === key); + if (p.shift || p.add) { + if (i >= 0) this.picks.splice(i, 1); + else this.picks.push(hit); + } else this.picks = i >= 0 && this.picks.length === 1 ? [] : [hit]; + this.selectionChanged(); + } + + private selectionChanged(): void { + this.drawMarks(); + this.placeGimbal(); + this.panel(); + this.hint(); + } + + private centroid(ids: number[]): Vec3 { + return scale(ids.reduce((s, i) => add(s, this.cage.verts[i]), [0, 0, 0] as Vec3), 1 / Math.max(1, ids.length)); + } + + private placeGimbal(): void { + const ids = this.selectedVerts(); + if (!ids.length) { + this.gimbal?.dispose(); + this.gimbal = null; + return; + } + this.gimbal ??= new Gimbal(this.app.view); + this.gimbal.setCenter(this.centroid(ids)); + } + + // ------------------------------------------------------------ dragging + + down(p: ToolPointer): boolean { + const part = this.gimbal?.hit(p); + if (!part || !this.gimbal) return false; + // One point turned about itself wouldn't move: it turns about the shape's centre instead. + const ids = this.selectedVerts(); + const center = part.kind === "ring" && ids.length === 1 ? this.centroid(this.cage.verts.map((_, i) => i)) : this.gimbal.origin; + this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0 }; + this.gimbal.setHot(part); + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + if (!dr) return; + this.typing.track(p); + if (this.typing.active) return; + const view = this.app.view; + const step = niceStep(view.cam.worldPerPixel(view.height) * 4); + const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step); + const part = dr.part; + if (part.kind === "axis") { + const dir = GIMBAL_AXES[part.i]; + const d = snap(axisDrag(view, dr.center, dir, dr.from, p)); + this.apply(scale(dir, d), 0); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(d)} · type a value`); + } else if (part.kind === "plane" || part.kind === "center") { + const n: Vec3 = part.kind === "plane" ? GIMBAL_AXES[part.i] : (view.cam.viewDir().toArray() as Vec3); + const plane = { origin: dr.center, normal: n, xDir: xDirFor(n) }; + const a = view.rayToPlane(dr.from.x, dr.from.y, plane); + const b = view.rayToPlane(p.x, p.y, plane); + if (!a || !b) return; + const d = sub(b, a); + this.apply([snap(d[0]), snap(d[1]), snap(d[2])], 0); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(len(dr.d))} · type a value`); + } else if (part.kind === "ring") { + const axis = GIMBAL_AXES[part.i]; + const c = view.toScreen(dr.center); + if (!c) return; + const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]); + const facing = dot(axis, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1; + let deg = ((-(ang(p) - ang(dr.from)) * 180) / Math.PI) * facing; + deg = ((deg + 540) % 360) - 180; + const total = p.shift ? deg : Math.round(deg); + this.apply([0, 0, 0], total); + this.app.ui.setLabel(p.x, p.y, `${total}° · type a value`); + } + } + + /** Move the selected points from where the drag began: translate d, then turn `deg` about the gimbal axis. */ + private apply(d: Vec3, deg: number): void { + const dr = this.dragging; + if (!dr) return; + dr.d = d; + dr.ang = deg; + const ids = this.selectedVerts(); + const axis = dr.part.kind === "ring" ? GIMBAL_AXES[dr.part.i] : null; + const t = (deg * Math.PI) / 180; + for (const i of ids) { + let q = dr.base[i]; + if (axis && deg) { + // Rodrigues' rotation about the axis through the centre. + const v = sub(q, dr.center); + const r = add(add(scale(v, Math.cos(t)), scale(cross(axis, v), Math.sin(t))), scale(axis, dot(axis, v) * (1 - Math.cos(t)))); + q = add(dr.center, r); + } + this.cage.verts[i] = add(q, d); + } + this.gimbal?.setCenter(this.centroid(ids)); + this.rebuild(); + } + + up(): void { + const moved = !!this.dragging && (len(this.dragging.d) > 0 || this.dragging.ang !== 0); + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.gimbal?.setHot(null); + if (this.placing && moved) { + // In place: on to editing points, edges and faces. + this.placing = false; + this.picks = []; + this.selectionChanged(); + return; + } + this.placeGimbal(); + } + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + const part = dr.part; + const dragDir = norm(dr.d); + return this.typing.key(e, { + kind: part.kind === "ring" ? "angle" : "length", + apply: (v) => { + if (part.kind === "ring") this.apply([0, 0, 0], v); + else if (part.kind === "axis") this.apply(scale(GIMBAL_AXES[part.i], v), 0); + else if (len(dr.d) > 1e-9) this.apply(scale(dragDir, v), 0); + }, + commit: () => this.up(), + cancel: () => this.apply([0, 0, 0], 0), + }); + } + + /** Panel Scale: grow/shrink the selection about its centre (relative to the last value). */ + private scaleSelection(v: number): void { + if (v <= 0) return; + const ids = this.selectedVerts(); + const c = this.centroid(ids); + const k = v / this.uniform; + this.uniform = v; + for (const i of ids) this.cage.verts[i] = add(c, scale(sub(this.cage.verts[i], c), k)); + this.rebuild(); + this.placeGimbal(); + } + + // --------------------------------------------------------------- drawing + + private rebuild(): void { + const m = previewMesh(subdivide(this.cage, 3)); + const g = this.surface.geometry; + g.setAttribute("position", new BufferAttribute(m.positions, 3)); + g.setAttribute("normal", new BufferAttribute(m.normals, 3)); + g.setIndex(new BufferAttribute(m.indices, 1)); + g.computeBoundingSphere(); + const edges = cageEdges(this.cage).flatMap(([a, b]) => [...this.cage.verts[a], ...this.cage.verts[b]]); + setPositions(this.lines, edges); + setPositions(this.dots, this.cage.verts.flat()); + this.drawMarks(); + } + + private drawMarks(): void { + const seg = (ps: Pick[]) => + ps.flatMap((p) => { + const V = this.cage.verts; + if (p.kind === "edge") return [...V[p.e[0]], ...V[p.e[1]]]; + if (p.kind === "face") { + const f = this.cage.faces[p.f]; + return f.flatMap((i, k) => [...V[i], ...V[f[(k + 1) % 4]]]); + } + return []; + }); + const pts = (ps: Pick[]) => ps.flatMap((p) => (p.kind === "vert" ? [...this.cage.verts[p.i]] : [])); + setPositions(this.marks, seg(this.picks)); + setPositions(this.markDots, pts(this.picks)); + const h = this.hovered ? [this.hovered] : []; + setPositions(this.hoverMarks, seg(h)); + setPositions(this.hoverDots, pts(h)); + this.app.view.requestRender(); + } + + // ------------------------------------------------------------- finishing + + key(e: KeyboardEvent): boolean { + if (e.key === "Escape") { + if (this.picks.length) ((this.picks = []), this.selectionChanged()); + else this.cancel(); + return true; + } + if (e.key === "Enter") return (this.done(), true); + if ((e.key === "Delete" || e.key === "Backspace") && this.picks.some((p) => p.kind === "face")) return (this.deleteSelectedFaces(), true); + if (e.key.toLowerCase() === "a" && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i })); + this.selectionChanged(); + return true; + } + return false; + } + + /** Save and close; returns the body id. */ + private done(): string | null { + // Stored where it was made: later move steps in History still apply on top. + const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv) }; + const open = !isClosed(cage); + const extra = { surface: this.surfaceSheet || undefined, thickness: open && this.thickness > 0 ? this.thickness : undefined, thickSide: open && this.thickness > 0 ? this.thickSide : undefined }; + let id: string; + if (this.existing) { + id = this.existing.id; + this.app.store.update(id, { cage, ...extra } as Partial); + } else { + const f: FreeformFeature = { ...this.app.store.newIdentity("freeform", isClosed(cage) ? "Freeform" : "Freeform surface"), type: "freeform", cage, ...extra }; + this.app.store.add(f); + id = f.id; + } + this.app.setTool(null); + return id; + } + + private cancel(): void { + this.app.setTool(null); + } + + /** Select the cage element under the pointer (used when a tap on the body opens the tool). */ + /** + * Delete the cage faces under picked body geometry (from the select tool): + * a face → its patch; an edge or a point → every patch that touches it. + * The shape opens up, so the Thickness choice shows. + */ + deleteAt(points: Vec3[], kind: "face" | "edge" | "vertex"): void { + const sub3 = subdivide(this.cage, 3); + const n = sub3.n; + const size = Math.max(1e-9, ...[0, 1, 2].map((k) => Math.max(...this.cage.verts.map((v) => v[k])) - Math.min(...this.cage.verts.map((v) => v[k])))); + const dist3 = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + const doomed = new Set(); + for (const q of points) { + if (kind === "face") { + let best = -1; + let bd = Infinity; + sub3.grids.forEach((g, f) => { + const d = dist3(sub3.points[g[n >> 1][n >> 1]], q); + if (d < bd) [bd, best] = [d, f]; + }); + if (best >= 0) doomed.add(best); + continue; + } + // Patches whose rim passes through the edge / point. + const rim = sub3.grids.map((g) => { + let d = Infinity; + for (let i = 0; i <= n; i++) + for (const [a, b] of [[0, i], [n, i], [i, 0], [i, n]]) d = Math.min(d, dist3(sub3.points[g[a][b]], q)); + return d; + }); + const min = Math.min(...rim); + rim.forEach((d, f) => d < min + size * 0.01 && doomed.add(f)); + } + if (!doomed.size) return; + if (doomed.size >= this.cage.faces.length) return this.app.ui.toast("At least one face has to stay"); + this.cage = deleteFaces(this.cage, [...doomed]); + this.picks = []; + this.rebuild(); + this.selectionChanged(); + this.app.ui.toast("The shape is no longer closed: give it a Thickness to make a solid, or Done for a surface."); + this.panelHint(); + } + + selectAt(p: ToolPointer): void { + const hit = this.pickAt(p); + if (!hit) return; + this.picks = [hit]; + this.selectionChanged(); + } +} + +function setPositions(o: LineSegments | Points, xyz: number[]): void { + const g = o.geometry; + g.setAttribute("position", new BufferAttribute(new Float32Array(xyz), 3)); + g.computeBoundingSphere(); +} + +/** Screen distance from (x, y) to segment a–b, and where along it (0…1). */ +function segDist(x: number, y: number, a: [number, number], b: [number, number]): { d: number; t: number } { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const l2 = dx * dx + dy * dy || 1; + const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l2)); + return { d: Math.hypot(x - (a[0] + dx * t), y - (a[1] + dy * t)), t }; +} + +function inPoly(x: number, y: number, q: [number, number][]): boolean { + let inside = false; + for (let i = 0, j = q.length - 1; i < q.length; j = i++) { + const [xi, yi] = q[i]; + const [xj, yj] = q[j]; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} + +interface Placement { + fwd(v: Vec3): Vec3; + inv(v: Vec3): Vec3; +} + +/** + * Where later History steps put this body: moves, scales and mirrors that + * act on it (not copies). `inv` undoes them, to store edits in the cage's own place. + */ +function placementOf(features: readonly Feature[], id: string): Placement { + const i = features.findIndex((f) => f.id === id); + const steps = features + .slice(i + 1) + .filter((f): f is TransformFeature => f.type === "transform" && !f.suppressed && !f.copy && f.bodies.includes(id) && ["move", "scale", "mirror"].includes(f.op.kind)); + const turn = (p: Vec3, o: Vec3, axis: Vec3, deg: number): Vec3 => { + const k = norm(axis); + const v = sub(p, o); + const t = (deg * Math.PI) / 180; + return add(o, add(add(scale(v, Math.cos(t)), scale(cross(k, v), Math.sin(t))), scale(k, dot(k, v) * (1 - Math.cos(t))))); + }; + const reflect = (p: Vec3, o: Vec3, n: Vec3): Vec3 => { + const k = norm(n); + return sub(p, scale(k, 2 * dot(sub(p, o), k))); + }; + const apply = (op: TransformFeature["op"], p: Vec3, back: boolean): Vec3 => { + if (op.kind === "move") { + const r = op.rotate; + if (!back) return add(r && r.angle ? turn(p, r.origin, r.axis, r.angle) : p, op.translate); + const q = sub(p, op.translate); + return r && r.angle ? turn(q, r.origin, r.axis, -r.angle) : q; + } + if (op.kind === "scale") return add(op.center, scale(sub(p, op.center), back ? 1 / op.factor : op.factor)); + if (op.kind === "mirror") return reflect(p, op.plane.origin, op.plane.normal); + return p; + }; + return { + fwd: (v) => steps.reduce((p, f) => apply(f.op, p, false), v), + inv: (v) => [...steps].reverse().reduce((p, f) => apply(f.op, p, true), v), + }; +} diff --git a/src/tools/gimbal.ts b/src/tools/gimbal.ts new file mode 100644 index 0000000..4d55a1a --- /dev/null +++ b/src/tools/gimbal.ts @@ -0,0 +1,213 @@ +// Move/rotate gimbal: three axis arrows, three plane squares, three rotation +// arcs and a centre ball. Drawn at constant screen size; hit-tested on screen. + +import { BoxGeometry, BufferGeometry, ConeGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SphereGeometry, Vector3 } from "three"; +import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js"; +import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js"; +import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js"; +import type { Vec3 } from "../doc/types"; +import type { ToolPointer } from "../view/input"; +import type { Viewport } from "../view/viewport"; + +export type GimbalPart = { kind: "axis" | "plane" | "ring"; i: 0 | 1 | 2 } | { kind: "center" }; + +const AXES: Vec3[] = [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], +]; +const COLORS = [0xe0584f, 0x5fbf5a, 0x4f8ce0]; +const SIZE_PX = 85; +const ARC_FROM = 0.25; +const ARC_TO = 1.32; + +/** Points of the rotation arc around axis i, in unit gimbal space. */ +function arcPoints(axes: Vec3[], i: number, n = 24): Vector3[] { + const u = new Vector3(...axes[(i + 1) % 3]); + const v = new Vector3(...axes[(i + 2) % 3]); + return Array.from({ length: n + 1 }, (_, k) => { + const t = ARC_FROM + ((ARC_TO - ARC_FROM) * k) / n; + return u.clone().multiplyScalar(Math.cos(t) * 1.1).addScaledVector(v, Math.sin(t) * 1.1); + }); +} + +export interface GimbalOptions { + /** The three axes (default world X, Y, Z). For a sketch: plane x, plane y, normal. */ + axes?: Vec3[]; + /** Which parts exist (e.g. a sketch gimbal has no out-of-plane arrow). */ + parts?: (p: GimbalPart) => boolean; + /** Cube ends instead of arrow heads: the scale gimbal. */ + cubes?: boolean; +} + +/** Scale gimbal: the three axis handles (cube ends) and the centre (uniform). */ +export const SCALE_PARTS = (p: GimbalPart) => p.kind === "axis" || p.kind === "center"; + +/** Parts of a gimbal that keep things in a plane whose normal is axis 2. */ +export const IN_PLANE = (p: GimbalPart) => p.kind === "center" || (p.kind === "axis" && p.i < 2) || (p.kind !== "axis" && p.i === 2); + +export class Gimbal { + private group = new Group(); + private center = new Vector3(); + private parts: { part: GimbalPart; obj: Group | Mesh | LineSegments2; color: number }[] = []; + private hook = () => this.layout(); + private hot: GimbalPart | null = null; + readonly axes: Vec3[]; + private allow: (p: GimbalPart) => boolean; + + constructor( + private view: Viewport, + opts: GimbalOptions = {}, + ) { + this.axes = opts.axes ?? AXES; + this.allow = opts.parts ?? (() => true); + const AX = this.axes; + AX.forEach((a, i) => { + const dir = new Vector3(...a); + const color = COLORS[i]; + // Axis arrow + const arrow = new Group(); + const shaft = new LineSegments2(new LineSegmentsGeometry().setPositions([...dir.clone().multiplyScalar(0.18).toArray(), ...dir.clone().multiplyScalar(0.82).toArray()]), view.lineMaterial(color, 3.5)); + const head = new Mesh(opts.cubes ? new BoxGeometry(0.15, 0.15, 0.15) : new ConeGeometry(0.07, 0.22, 16), new MeshBasicMaterial({ color, depthTest: false })); + head.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), dir); + head.position.copy(dir).multiplyScalar(0.9); + arrow.add(shaft, head); + this.add({ kind: "axis", i: i as 0 | 1 | 2 }, arrow, color); + // Plane square (moves in the plane perpendicular to this axis) + const u = new Vector3(...AX[(i + 1) % 3]); + const v = new Vector3(...AX[(i + 2) % 3]); + const sq = new Mesh(new PlaneGeometry(0.17, 0.17), new MeshBasicMaterial({ color, transparent: true, opacity: 0.55, side: DoubleSide, depthTest: false })); + sq.position.copy(u.clone().add(v).multiplyScalar(0.33)); + sq.quaternion.setFromUnitVectors(new Vector3(0, 0, 1), dir); + this.add({ kind: "plane", i: i as 0 | 1 | 2 }, sq, color); + // Rotation arc + const pts = arcPoints(AX, i); + const seg: number[] = []; + for (let k = 0; k < pts.length - 1; k++) seg.push(...pts[k].toArray(), ...pts[k + 1].toArray()); + const arc = new LineSegments2(new LineSegmentsGeometry().setPositions(seg), view.lineMaterial(color, 3)); + this.add({ kind: "ring", i: i as 0 | 1 | 2 }, arc, color); + }); + const ball = new Mesh(new SphereGeometry(0.075, 16, 12), new MeshBasicMaterial({ color: 0xffffff, depthTest: false })); + this.add({ kind: "center" }, ball, 0xffffff); + // Over everything, selection highlights included (see Handle). + this.group.traverse((o) => { + o.renderOrder = 50; + const m = (o as Mesh).material as MeshBasicMaterial | undefined; + if (m && "transparent" in m) m.transparent = true; + }); + view.overlay.add(this.group); + view.frameHooks.add(this.hook); + view.helpers.add(this); + } + + private add(part: GimbalPart, obj: Group | Mesh | LineSegments2, color: number): void { + obj.visible = this.allow(part); + this.parts.push({ part, obj, color }); + this.group.add(obj); + } + + setCenter(c: Vec3): void { + this.center.set(...c); + this.layout(); + this.view.requestRender(); + } + + get origin(): Vec3 { + return this.center.toArray() as Vec3; + } + + private scale(): number { + return this.view.cam.worldPerPixel(this.view.height) * SIZE_PX; + } + + private layout(): void { + this.group.position.copy(this.center); + this.group.scale.setScalar(this.scale()); + } + + private screen(local: Vector3): [number, number] | null { + return this.view.toScreen(local.clone().multiplyScalar(this.scale()).add(this.center)); + } + + /** Which part is under the pointer (centre, planes, arrows, arcs — in that order). */ + hit(p: ToolPointer): GimbalPart | null { + const tol = Math.max(10, p.tol * 1.2); + const c = this.screen(new Vector3()); + if (c && this.allow({ kind: "center" }) && Math.hypot(c[0] - p.x, c[1] - p.y) < tol) return { kind: "center" }; + for (let i = 0; i < 3; i++) { + if (!this.allow({ kind: "plane", i: i as 0 | 1 | 2 })) continue; + const u = new Vector3(...this.axes[(i + 1) % 3]); + const v = new Vector3(...this.axes[(i + 2) % 3]); + const m = u.clone().add(v).multiplyScalar(0.33); + const quad = [m.clone().addScaledVector(u, -0.085).addScaledVector(v, -0.085), m.clone().addScaledVector(u, 0.085).addScaledVector(v, -0.085), m.clone().addScaledVector(u, 0.085).addScaledVector(v, 0.085), m.clone().addScaledVector(u, -0.085).addScaledVector(v, 0.085)] + .map((q) => this.screen(q)) + .filter((q): q is [number, number] => !!q); + if (quad.length === 4 && inPoly(p.x, p.y, quad)) return { kind: "plane", i: i as 0 | 1 | 2 }; + } + let best: { part: GimbalPart; d: number } | null = null; + for (let i = 0; i < 3; i++) { + const dir = new Vector3(...this.axes[i]); + const a = this.screen(dir.clone().multiplyScalar(0.18)); + const b = this.screen(dir.clone().multiplyScalar(1.02)); + if (a && b && this.allow({ kind: "axis", i: i as 0 | 1 | 2 })) { + const d = segDist(p.x, p.y, a, b); + if (d < tol && (!best || d < best.d)) best = { part: { kind: "axis", i: i as 0 | 1 | 2 }, d }; + } + const pts = this.allow({ kind: "ring", i: i as 0 | 1 | 2 }) ? arcPoints(this.axes, i, 16).map((q) => this.screen(q)) : []; + for (let k = 0; k < pts.length - 1; k++) { + const s0 = pts[k]; + const s1 = pts[k + 1]; + if (!s0 || !s1) continue; + const d = segDist(p.x, p.y, s0, s1); + if (d < tol && (!best || d < best.d)) best = { part: { kind: "ring", i: i as 0 | 1 | 2 }, d }; + } + } + return best?.part ?? null; + } + + /** Brighten the part under the pointer / being dragged. */ + setHot(part: GimbalPart | null): void { + if (JSON.stringify(part) === JSON.stringify(this.hot)) return; + this.hot = part; + for (const { part: q, obj, color } of this.parts) { + const on = !!part && JSON.stringify(part) === JSON.stringify(q); + obj.traverse((o) => { + const m = (o as Mesh).material as MeshBasicMaterial & { color?: { setHex(n: number): void } }; + if (m?.color) m.color.setHex(on ? 0xffd34d : color); + }); + } + this.view.requestRender(); + } + + dispose(): void { + this.view.helpers.delete(this); + this.view.frameHooks.delete(this.hook); + this.view.overlay.remove(this.group); + this.group.traverse((o) => { + const m = o as Mesh; + if (m.geometry instanceof BufferGeometry) m.geometry.dispose(); + if (m.material instanceof LineMaterial) this.view.releaseLineMaterial(m.material); + }); + this.view.requestRender(); + } +} + +export const GIMBAL_AXES = AXES; + +function segDist(x: number, y: number, a: [number, number], b: [number, number]): number { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const l2 = dx * dx + dy * dy || 1; + const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l2)); + return Math.hypot(a[0] + dx * t - x, a[1] + dy * t - y); +} + +function inPoly(x: number, y: number, poly: [number, number][]): boolean { + let inside = false; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { + const [xi, yi] = poly[i]; + const [xj, yj] = poly[j]; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} diff --git a/src/tools/handles.ts b/src/tools/handles.ts new file mode 100644 index 0000000..09396fd --- /dev/null +++ b/src/tools/handles.ts @@ -0,0 +1,131 @@ +import { ConeGeometry, Group, Mesh, MeshBasicMaterial, SphereGeometry, Vector3 } from "three"; +import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js"; +import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js"; +import type { Vec3 } from "../doc/types"; +import type { Viewport } from "../view/viewport"; +import type { ToolPointer } from "../view/input"; + +// Amber, so a handle never disappears against the blue of a selection. +const COLOR = 0xffa31a; +const HOT = 0xffd27a; +const ARROW_PX = 84; + +/** + * A drag handle drawn at constant screen size: an arrow along a direction, or a + * dot. `hit` tests in screen space so it's easy to grab with a finger. + */ +export class Handle { + private group = new Group(); + private base = new Vector3(); + private dir = new Vector3(0, 0, 1); + // Transparent (at full opacity) so it's drawn in the last pass, over see-through + // selection highlights — three.js draws all opaque things before those. + private mat = new MeshBasicMaterial({ color: COLOR, depthTest: false, transparent: true }); + private head: Mesh; + private shaft: LineSegments2 | null = null; + private lineMat; + private onFrame = () => this.layout(); + + constructor(private view: Viewport, readonly shape: "arrow" | "dot") { + this.lineMat = view.lineMaterial(COLOR, 4); + this.lineMat.transparent = true; + this.head = new Mesh(shape === "arrow" ? new ConeGeometry(0.11, 0.3, 20) : new SphereGeometry(0.12, 20, 12), this.mat); + this.head.renderOrder = 50; + this.group.add(this.head); + if (shape === "arrow") { + this.shaft = new LineSegments2(new LineSegmentsGeometry(), this.lineMat); + this.shaft.renderOrder = 50; + this.group.add(this.shaft); + } + view.overlay.add(this.group); + view.frameHooks.add(this.onFrame); + view.helpers.add(this); + } + + private hot = false; + + /** Highlight while the pointer is over it (brighter and a bit bigger). */ + setHot(on: boolean): void { + if (on === this.hot) return; + this.hot = on; + this.mat.color.setHex(on ? HOT : COLOR); + if (this.shaft) { + this.view.releaseLineMaterial(this.lineMat); + this.lineMat = this.view.lineMaterial(on ? HOT : COLOR, on ? 6 : 4); + this.lineMat.transparent = true; + this.shaft.material = this.lineMat; + } + this.layout(); + this.view.requestRender(); + } + + set(base: Vec3, dir?: Vec3): void { + this.base.set(...base); + if (dir) this.dir.set(...dir).normalize(); + this.layout(); + this.view.requestRender(); + } + + /** Screen position of the grabbable part. */ + grabPoint(): [number, number] | null { + return this.view.toScreen(this.tip()); + } + + hit(p: ToolPointer): boolean { + const s = this.grabPoint(); + return !!s && Math.hypot(s[0] - p.x, s[1] - p.y) < Math.max(30, p.tol * 1.8); + } + + dispose(): void { + this.view.helpers.delete(this); + this.view.frameHooks.delete(this.onFrame); + this.view.overlay.remove(this.group); + this.head.geometry.dispose(); + this.shaft?.geometry.dispose(); + this.view.releaseLineMaterial(this.lineMat); + this.view.requestRender(); + } + + private size(): number { + return this.view.cam.worldPerPixel(this.view.height) * ARROW_PX; + } + + private headScale(): number { + return this.size() * (this.hot ? 1.45 : 1); + } + + private tip(): Vector3 { + return this.shape === "arrow" ? this.base.clone().addScaledVector(this.dir, this.size()) : this.base.clone(); + } + + private layout(): void { + const s = this.size(); + this.head.scale.setScalar(this.headScale()); + if (this.shape === "arrow") { + const tip = this.tip(); + this.head.position.copy(tip); + this.head.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), this.dir); + const start = this.base.clone().addScaledVector(this.dir, s * 0.12); + (this.shaft!.geometry as LineSegmentsGeometry).setPositions([...start.toArray(), ...tip.toArray()]); + } else { + this.head.position.copy(this.base); + } + } +} + +/** Screen-space drag along a world axis → signed world distance. */ +export function axisDrag(view: Viewport, origin: Vec3, dir: Vec3, from: ToolPointer, to: ToolPointer): number { + const o = new Vector3(...origin); + const a = view.toScreen(o); + const b = view.toScreen(o.clone().addScaledVector(new Vector3(...dir), 1)); + const dx = to.x - from.x; + const dy = to.y - from.y; + if (a && b) { + const vx = b[0] - a[0]; + const vy = b[1] - a[1]; + const l2 = vx * vx + vy * vy; + // Looking almost straight down the axis: fall back to vertical drag. + if (l2 > 0.25) return (dx * vx + dy * vy) / l2; + } + return -dy * view.cam.worldPerPixel(view.height); +} diff --git a/src/tools/measure.ts b/src/tools/measure.ts new file mode 100644 index 0000000..9ce1b46 --- /dev/null +++ b/src/tools/measure.ts @@ -0,0 +1,258 @@ +import type { PinDef, Vec3 } from "../doc/types"; +import { settings } from "../settings"; +import { cross, dist, dot, len, sub } from "../geom"; +import type { BodyMesh } from "../kernel/protocol"; +import { el } from "../ui/ui"; +import { fmtLen, trim, UNIT_MM, UNIT_LABEL, units } from "../units"; +import type { ToolPointer } from "../view/input"; +import { hitToSel, sameSel, type AppContext, type Sel, type Tool } from "./tool"; + +export interface MeasureHost extends AppContext { + readonly pins: PinDef[]; + setPins(p: PinDef[]): void; +} + +interface Row { + name: string; + value: string; + at: Vec3; + a?: Vec3; + b?: Vec3; +} + +/** + * Measure: tap faces, edges or bodies; a card lists what can be measured + * about them (and between two of them). Pin any value to keep it visible. + */ +export class MeasureTool implements Tool { + readonly id = "measure"; + private items: Sel[] = []; + private card: HTMLElement | null = null; + private deltas = false; + + constructor(private app: MeasureHost) {} + + enter(): void { + this.app.ui.setTools([{ id: "exit", label: "Exit Measure", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]); + this.app.ui.setBottom([]); + this.app.ui.setHint("Select objects to see their measurements. Double-tap for a whole body."); + this.card = el("div", "measure-card"); + document.body.append(this.card); + this.render(); + } + + exit(): void { + this.card?.remove(); + this.app.ui.setHint(null); + this.app.setSelection([]); + this.app.setHover(null); + } + + hover(p: ToolPointer | null): void { + this.app.setHover(p ? hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false })) : null); + } + + tap(p: ToolPointer, count: number): void { + let s = hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false })); + if (!s) { + // Empty space: first clears, second leaves Measure. + if (!this.items.length) return this.app.setTool(null); + this.items = []; + } else { + if (count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body }; + const i = this.items.findIndex((x) => sameSel(x, s!)); + if (i >= 0) this.items.splice(i, 1); + else this.items = [...this.items.slice(-1), s]; + } + this.app.setSelection(this.items); + this.render(); + } + + key(e: KeyboardEvent): boolean { + if (e.key === "Escape") { + if (this.items.length) { + this.items = []; + this.app.setSelection([]); + this.render(); + } else this.app.setTool(null); + return true; + } + return false; + } + + private render(): void { + if (!this.card) return; + this.card.innerHTML = ""; + const rows = this.measurements(); + const head = el("label", "measure-toggle"); + const box = document.createElement("input"); + box.type = "checkbox"; + box.checked = this.deltas; + box.addEventListener("change", () => ((this.deltas = box.checked), this.render())); + head.append(box, " Include X, Y, Z deltas"); + const show = el("label", "measure-toggle"); + const sbox = document.createElement("input"); + sbox.type = "checkbox"; + sbox.checked = settings.value.showPinned; + sbox.addEventListener("change", () => settings.set("showPinned", sbox.checked)); + show.append(sbox, " Show pinned measurements"); + this.card.append(head, show); + if (!rows.length) this.card.append(el("div", "measure-empty", "Nothing selected")); + for (const r of rows) { + const row = el("div", "measure-row"); + row.append(el("div", "measure-value", r.value), el("div", "measure-name", r.name)); + const pin = el("button", "icon-btn", "📌"); + pin.title = "Pin to always show"; + pin.addEventListener("click", () => (this.app.addPin({ text: r.value, at: r.at, a: r.a, b: r.b }), this.render())); + row.append(pin); + this.card.append(row); + } + if (this.app.pins.length) { + const clear = el("button", "text-btn", `Clear ${this.app.pins.length} pinned`); + clear.addEventListener("click", () => (this.app.setPins([]), this.render())); + this.card.append(clear); + } + } + + private measurements(): Row[] { + const out: Row[] = []; + const info = this.items.map((s) => this.describe(s)).filter((x): x is Described => !!x); + for (const d of info) out.push(...d.rows); + if (info.length === 2) { + const [a, b] = info; + const mid = (p: Vec3, q: Vec3): Vec3 => [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]; + out.push({ name: "Distance (centers)", value: fmtLen(dist(a.anchor, b.anchor)), at: mid(a.anchor, b.anchor), a: a.anchor, b: b.anchor }); + const m = closestPair(a.points, b.points); + out.push({ name: "Minimum distance", value: fmtLen(m.d), at: mid(m.p, m.q), a: m.p, b: m.q }); + if (this.deltas) { + const d = sub(b.anchor, a.anchor); + ["X", "Y", "Z"].forEach((n, i) => { + const end = [...a.anchor] as Vec3; + end[i] = b.anchor[i]; + out.push({ name: `Δ${n}`, value: fmtLen(Math.abs(d[i])), at: mid(a.anchor, end), a: a.anchor, b: end }); + }); + } + if (a.dir && b.dir) { + const ang = (Math.acos(Math.min(1, Math.abs(dot(a.dir, b.dir)))) * 180) / Math.PI; + out.push({ name: "Angle", value: `${trim(ang, 2)}°`, at: mid(a.anchor, b.anchor) }); + } + } + return out; + } + + private describe(s: Sel): Described | null { + if (s.kind !== "face" && s.kind !== "edge" && s.kind !== "body" && s.kind !== "vertex") return null; + const b = this.app.view.body(s.body); + if (!b) return null; + if (s.kind === "vertex") { + const v = this.app.view.vertexOf(s.body, s.vertex); + if (!v) return null; + const u = UNIT_MM[units()]; + return { rows: [{ name: "Point (X, Y, Z)", value: v.map((c) => trim(c / u, 3)).join(", "), at: v }], anchor: v, points: [v] }; + } + if (s.kind === "face") { + const f = b.faces[s.face]; + const pts = facePoints(b, s.face); + const rows = [{ name: `Surface area · ${niceType(f.type)}`, value: fmtArea(f.area), at: f.center }]; + return { rows, anchor: f.center, points: pts, dir: f.plane ? f.normal : undefined }; + } + if (s.kind === "edge") { + const e = b.edges[s.edge]; + const pts = edgePoints(b, s.edge); + const rows: Row[] = [{ name: `Length · ${niceType(e.type)}`, value: fmtLen(e.length), at: e.mid, ...(e.type === "LINE" ? { a: e.start, b: e.end } : {}) }]; + if (e.type === "CIRCLE" && pts.length >= 3) { + const r = circumradius(pts[0], pts[Math.floor(pts.length / 3)], pts[Math.floor((2 * pts.length) / 3)]); + if (r) rows.push({ name: "Diameter", value: fmtLen(2 * r), at: e.mid }, { name: "Radius", value: fmtLen(r), at: e.mid }); + } + return { rows, anchor: e.mid, points: pts, dir: e.type === "LINE" ? e.dir : undefined }; + } + const pts: Vec3[] = []; + for (let i = 0; i < b.positions.length; i += 3) pts.push([b.positions[i], b.positions[i + 1], b.positions[i + 2]]); + const min = [0, 1, 2].map((k) => Math.min(...pts.map((p) => p[k]))); + const max = [0, 1, 2].map((k) => Math.max(...pts.map((p) => p[k]))); + const center: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]; + const area = b.faces.reduce((s2, f) => s2 + f.area, 0); + return { + rows: [ + { name: "Size (X × Y × Z)", value: `${trim((max[0] - min[0]) / UNIT_MM[units()], 3)} × ${trim((max[1] - min[1]) / UNIT_MM[units()], 3)} × ${fmtLen(max[2] - min[2])}`, at: center }, + { name: "Surface area", value: fmtArea(area), at: center }, + { name: "Volume", value: fmtVolume(volume(b)), at: center }, + ], + anchor: center, + points: pts, + }; + } +} + +interface Described { + rows: Row[]; + anchor: Vec3; + points: Vec3[]; + dir?: Vec3; +} + +function facePoints(b: BodyMesh, face: number): Vec3[] { + const g = b.faceGroups.find((x) => x.face === face); + if (!g) return []; + const out: Vec3[] = []; + for (let i = g.start; i < g.start + g.count; i++) { + const v = b.indices[i] * 3; + out.push([b.positions[v], b.positions[v + 1], b.positions[v + 2]]); + } + return out; +} + +function edgePoints(b: BodyMesh, edge: number): Vec3[] { + const g = b.edgeGroups.find((x) => x.edge === edge); + if (!g) return []; + const out: Vec3[] = []; + for (let i = g.start; i < g.start + g.count; i++) out.push([b.edgePositions[i * 3], b.edgePositions[i * 3 + 1], b.edgePositions[i * 3 + 2]]); + return out; +} + +function closestPair(a: Vec3[], b: Vec3[]): { d: number; p: Vec3; q: Vec3 } { + let best = { d: Infinity, p: a[0], q: b[0] }; + const step = (n: number) => Math.max(1, Math.floor(n / 600)); + for (let i = 0; i < a.length; i += step(a.length)) { + for (let j = 0; j < b.length; j += step(b.length)) { + const d = dist(a[i], b[j]); + if (d < best.d) best = { d, p: a[i], q: b[j] }; + } + } + return best; +} + +function circumradius(a: Vec3, b: Vec3, c: Vec3): number | null { + const ab = len(sub(b, a)); + const bc = len(sub(c, b)); + const ca = len(sub(a, c)); + const area2 = len(cross(sub(b, a), sub(c, a))); + return area2 > 1e-12 ? (ab * bc * ca) / (2 * area2) : null; +} + +/** Signed-tetrahedron volume of the (closed) mesh. */ +function volume(b: BodyMesh): number { + let v = 0; + const p = b.positions; + for (let i = 0; i < b.indices.length; i += 3) { + const a = b.indices[i] * 3; + const c = b.indices[i + 1] * 3; + const d = b.indices[i + 2] * 3; + v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6; + } + return Math.abs(v); +} + +function fmtArea(mm2: number): string { + const k = UNIT_MM[units()]; + return `${trim(mm2 / (k * k), 3)} ${UNIT_LABEL[units()]}²`; +} + +function fmtVolume(mm3: number): string { + const k = UNIT_MM[units()]; + return `${trim(mm3 / (k * k * k), 3)} ${UNIT_LABEL[units()]}³`; +} + +function niceType(t: string): string { + return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form"); +} diff --git a/src/tools/ops.ts b/src/tools/ops.ts new file mode 100644 index 0000000..8f586c5 --- /dev/null +++ b/src/tools/ops.ts @@ -0,0 +1,1542 @@ +// Solid, transform and construction operations. Each is a FeatureOp: +// pick slots + values + live preview; see featureOp.ts. + +import type { + AxisFeature, + AxisRef, + EdgeFeature, + EdgeRef, + ExtrudeFeature, + ExtrudeSource, + FaceRef, + ImageFeature, + LoftFeature, + MoveFaceFeature, + PathRef, + ReplaceFaceFeature, + ScaleFaceFeature, + PlaneDef, + PlaneFeature, + RevolveFeature, + ShellFeature, + SplitFeature, + SweepFeature, + TransformFeature, + Vec3, +} from "../doc/types"; +import { add, cross, dot, len, norm, niceStep, scale, sub, xDirFor } from "../geom"; +import type { PanelItem } from "../ui/ui"; +import { evaluate, fmtLen } from "../units"; +import type { ToolPointer } from "../view/input"; +import { FeatureOp } from "./featureOp"; +import { axisDrag, Handle } from "./handles"; +import { axisSlot, directionSlot, facesSlot, pathSlot, planeSlot, pointSlot, sectionsSlot } from "./slots"; +import { faceIndexOf, oppositeFace, sourceFrame, targetOf, type AppContext, type Sel } from "./tool"; +import { DimWidget } from "./annotate"; +import { Gimbal, GIMBAL_AXES, IN_PLANE, SCALE_PARTS, type GimbalPart } from "./gimbal"; +import { DragTyping } from "./dragTyping"; +import { CopyToggle } from "./copyToggle"; + +type Mode = "auto" | "new" | "join" | "cut"; +const MODES = [ + { id: "auto", label: "Auto" }, + { id: "new", label: "New body" }, + { id: "join", label: "Add" }, + { id: "cut", label: "Cut" }, +]; + +function modeChoice(get: () => Mode, set: (m: Mode) => void, rerender: () => void): PanelItem { + return { type: "choice", options: MODES, value: get(), onChange: (m) => (set(m as Mode), rerender()) }; +} + +// ------------------------------------------------------------------ extrude + +export interface ExtrudeOptions { + /** Face push/pull: edit the total thickness or the offset. */ + measure?: "total" | "offset"; + distance?: number; + /** Text being typed when the tool took over (restored into the widget). */ + typed?: string; +} + +/** + * Extrude profiles or push/pull a flat face. Drag the arrow or type a value in + * the dimension next to it; for faces choose Total (thickness to the opposite + * face) or Offset (how far the face moves). Negative offsets cut. + */ +export class ExtrudeOp extends FeatureOp { + readonly id = "extrude"; + private handle: Handle; + private frame: { base: Vec3; normal: Vec3 }; + private dragging: { from: ToolPointer; d0: number } | null = null; + private dim: DimWidget | null = null; + private measure: "total" | "offset"; + private thick: { distance: number; point: Vec3 } | null = null; + + constructor(app: AppContext, source: ExtrudeSource, existing?: ExtrudeFeature, mode: Mode = "auto", private opts: ExtrudeOptions = {}) { + // Pushing a face of its own body is an Offset Face step in the history. + const label = source.kind === "face" && mode !== "new" ? "Offset Face" : undefined; + super(app, { ...app.store.newIdentity("extrude", label), type: "extrude", source, distance: opts.distance ?? 0, mode, target: targetOf(app, source) }, existing); + this.frame = sourceFrame(app, this.feature.source); + this.handle = new Handle(app.view, "arrow"); + if (source.kind === "face") { + const k = faceIndexOf(app, source.face); + if (k !== null) this.thick = oppositeFace(app, source.face.body, k); + } + this.measure = this.thick ? (opts.measure ?? "total") : "offset"; + } + + enter(): void { + super.enter(); + this.dim = new DimWidget(this.app.view, { + // Past the tip of the drag arrow (at the far end of the dimension). + boxAt: "beyond", + boxGap: 96, + dir: this.frame.normal, + value: this.shown(), + modes: this.thick ? [{ id: "total", label: "Total" }, { id: "offset", label: "Offset" }] : undefined, + mode: this.measure, + onMode: (m) => { + this.measure = m as "total" | "offset"; + this.dim?.setValue(this.shown()); + this.onDraftChanged(); + }, + onInput: (v) => this.setDistance(this.measure === "total" && this.thick ? v - this.thick.distance : v), + onCommit: () => this.done(), + onPin: () => this.pin(), + typed: this.opts.typed, + focus: this.opts.typed !== undefined, + }); + this.onDraftChanged(); + } + + /** The value the widget shows: total thickness or offset. */ + private shown(): number { + return this.measure === "total" && this.thick ? this.thick.distance + this.feature.distance : this.feature.distance; + } + + private dimEnds(): [Vec3, Vec3] { + const { base, normal } = this.frame; + const top = add(base, scale(normal, this.feature.distance)); + return this.measure === "total" && this.thick ? [this.thick.point, top] : [base, top]; + } + + private pin(): void { + const [a, b] = this.dimEnds(); + this.app.addPin({ text: fmtLen(Math.abs(this.shown())), a, b, at: scale(add(a, b), 0.5) }); + } + + get activeSketch(): string | undefined { + return this.feature.source.kind === "profile" ? this.feature.source.sketch : undefined; + } + + protected hint(): string { + return "Drag the arrow or type a distance. Negative values cut."; + } + + protected items(): PanelItem[] { + return [ + this.num("Distance", "distance", "length", { onInput: (v) => this.setDistance(v) }), + modeChoice(() => this.feature.mode, (m) => ((this.feature.mode = m), this.update()), () => this.render()), + ]; + } + + protected ready(): boolean { + return this.feature.distance !== 0; + } + + exit(): void { + this.handle.dispose(); + this.dim?.dispose(); + super.exit(); + } + + hover(p: ToolPointer | null): void { + const on = !!p && (!!this.dragging || this.handle.hit(p)); + this.handle.setHot(on); + this.app.view.canvas.style.cursor = on ? "grab" : ""; + if (!on) super.hover(p); + } + + down(p: ToolPointer): boolean { + if (!this.handle.hit(p)) return false; + this.dragging = { from: p, d0: this.feature.distance }; + this.handle.setHot(true); + return true; + } + + drag(p: ToolPointer): void { + if (!this.dragging) return; + this.typing.track(p); + if (this.typing.active) return; // a typed value wins over the pointer + const { d0, from } = this.dragging; + const raw = d0 + axisDrag(this.app.view, add(this.frame.base, scale(this.frame.normal, d0)), this.frame.normal, from, p); + const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4); + this.setDistance(Math.round(raw / step) * step); + this.app.ui.setLabel(p.x, p.y, `${this.measure === "total" && this.thick ? "Total " : ""}${fmtLen(this.shown())} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.handle.setHot(false); + } + + private typing = new DragTyping(this.app); + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "length", + apply: (v) => this.setDistance(this.measure === "total" && this.thick ? v - this.thick.distance : v), + commit: () => ((this.dragging = null), this.done()), + cancel: () => this.setDistance(dr.d0), + }); + } + + private setDistance(d: number): void { + this.feature.distance = d; + this.app.ui.updatePanelValues([d]); + this.dim?.setValue(this.shown()); + this.update(); + } + + protected onDraftChanged(): void { + this.handle.set(add(this.frame.base, scale(this.frame.normal, this.feature.distance)), this.frame.normal); + const [a, b] = this.dimEnds(); + this.dim?.set(a, b); + } + + protected done(): void { + if (this.feature.distance === 0) return this.app.setTool(null); + super.done(); + } +} + +// ---------------------------------------------------------- fillet/chamfer + +export class EdgeOp extends FeatureOp { + readonly id: string; + private handle: Handle; + private origin: Vec3; + private axis: Vec3; + private dragging: { from: ToolPointer; r0: number } | null = null; + + constructor(app: AppContext, kind: "fillet" | "chamfer", edges: EdgeRef[], existing?: EdgeFeature, variable?: string) { + // Started from a variable: the size is that variable (and follows it when it changes). + const v = variable ? evaluate(variable, "length") : null; + super(app, { ...app.store.newIdentity(kind), type: kind, edges, radius: v ?? 1, ...(variable && v !== null ? { exprs: { radius: variable } } : {}) }, existing); + this.id = kind; + this.names = { fillet: existing?.type === "fillet" ? existing.name : app.store.newIdentity("fillet").name, chamfer: existing?.type === "chamfer" ? existing.name : app.store.newIdentity("chamfer").name }; + const e = this.feature.edges[0]; + this.origin = e.mid; + this.axis = outwardOf(app, e) ?? (() => { + const view = app.view.camera.position.clone().sub(app.view.cam.target).normalize().toArray() as Vec3; + const perp = norm(cross(cross(e.dir, view), e.dir)); + return dot(perp, view) < 0 ? scale(perp, -1) : perp; + })(); + this.handle = new Handle(app.view, "dot"); + } + + private names: { fillet: string; chamfer: string }; + + /** Fillets sit outside the edge (+), chamfers inside (−): dragging across the edge switches. */ + private signed(): number { + return this.feature.type === "fillet" ? this.feature.radius : -this.feature.radius; + } + + protected hint(): string { + return `Drag the dot or type a ${this.feature.type === "fillet" ? "radius" : "distance"}. Tap more edges to add them.`; + } + + protected items(): PanelItem[] { + return [this.num(this.feature.type === "fillet" ? "Radius" : "Distance", "radius", "length", { min: 0.0001, onInput: (v) => this.setRadius(v) })]; + } + + enter(): void { + super.enter(); + this.app.setSelection(this.edgeSels()); + } + + exit(): void { + this.handle.dispose(); + super.exit(); + } + + /** Tapping edges while filleting adds/removes them. */ + tap(p: ToolPointer): void { + const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false, axes: false, vertices: false }); + if (!hit) return this.done(); + if (hit.kind !== "edge") return; + const info = this.app.view.body(hit.body)?.edges[hit.edge]; + if (!info) return; + const i = this.feature.edges.findIndex((e) => e.body === hit.body && Math.hypot(...sub(e.mid, info.mid)) < 1e-6); + if (i >= 0) this.feature.edges.splice(i, 1); + else this.feature.edges.push({ body: hit.body, mid: info.mid, dir: info.dir, length: info.length }); + this.app.setSelection(this.edgeSels()); + this.update(); + } + + hover(): void {} + + private edgeSels(): Sel[] { + return this.feature.edges.flatMap((e) => { + const b = this.app.view.body(e.body); + const k = b?.edges.findIndex((x) => Math.hypot(...sub(x.mid, e.mid)) < 1e-6) ?? -1; + return k >= 0 ? [{ kind: "edge", body: e.body, edge: k } as Sel] : []; + }); + } + + protected ready(): boolean { + return this.feature.edges.length > 0; + } + + /** Started by dragging the dot on the edge itself: the size grows from the edge. */ + private fromEdge = false; + + /** The next press (the one that opened this from the edge's dot) drags from zero. */ + grabFromEdge(): this { + this.fromEdge = true; + return this; + } + + down(p: ToolPointer): boolean { + const first = this.fromEdge && !this.existing; + this.fromEdge = false; + if (first) { + this.dragging = { from: p, r0: 0 }; + return true; + } + if (!this.handle.hit(p)) return false; + this.dragging = { from: p, r0: this.signed() }; + return true; + } + + drag(p: ToolPointer): void { + if (!this.dragging) return; + this.typing.track(p); + if (this.typing.active) return; + const { r0, from } = this.dragging; + const raw = r0 + axisDrag(this.app.view, add(this.origin, scale(this.axis, r0)), this.axis, from, p); + const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 3); + // Outward: a fillet; pulled in past the edge: a chamfer. + const kind = raw >= 0 ? "fillet" : "chamfer"; + if (kind !== this.feature.type) { + this.feature.type = kind; + this.feature.name = this.names[kind]; + this.render(); + } + this.setRadius(Math.max(step, Math.round(Math.abs(raw) / step) * step)); + this.app.ui.setLabel(p.x, p.y, `${kind === "fillet" ? "Fillet" : "Chamfer"} ${fmtLen(this.feature.radius)} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + } + + private typing = new DragTyping(this.app); + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "length", + apply: (v) => v > 0 && this.setRadius(v), + commit: () => ((this.dragging = null), this.done()), + cancel: () => this.setRadius(dr.r0), + }); + } + + private setRadius(r: number): void { + this.feature.radius = r; + this.app.ui.updatePanelValues([r]); + this.update(); + } + + protected onDraftChanged(): void { + this.handle.set(add(this.origin, scale(this.axis, this.signed()))); + } +} + +/** Away from the material at an edge: between the normals of the two flat faces it joins. */ +function outwardOf(app: AppContext, e: EdgeRef): Vec3 | null { + const b = app.view.body(e.body); + if (!b) return null; + const tol = Math.max(1e-6, e.length * 1e-4); + const ns = b.faces.filter((f) => f.plane && Math.abs(dot(f.normal, e.dir)) < 1e-4 && Math.abs(dot(f.normal, sub(e.mid, f.center))) < tol).map((f) => f.normal); + if (ns.length < 2) return null; + const sum = add(ns[0], ns[1]); + return len(sum) < 1e-6 ? null : norm(sum); +} + +// ----------------------------------------------------------------- revolve + +export class RevolveOp extends FeatureOp { + readonly id = "revolve"; + private axisSet = false; + + constructor(app: AppContext, source: ExtrudeSource, existing?: RevolveFeature) { + super(app, { ...app.store.newIdentity("revolve"), type: "revolve", source, axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "auto", target: targetOf(app, source) }, existing); + this.axisSet = !!existing; + this.slots = [axisSlot(app, "Axis", () => (this.axisSet ? this.feature.axis : null), (a) => ((this.feature.axis = a), (this.axisSet = true)))]; + } + + get activeSketch(): string | undefined { + return this.feature.source.kind === "profile" ? this.feature.source.sketch : undefined; + } + + private handle: Handle | null = null; + private dim: DimWidget | null = null; + private dragging: { from: ToolPointer; t0: number } | null = null; + private typing = new DragTyping(this.app); + + protected hint(): string { + return "Set the angle (360° is a full turn). Drag the arrow on the axis to move along it while turning — with more than 360° that makes a thread or a spring."; + } + + protected items(): PanelItem[] { + return [ + this.num("Angle", "angle", "angle"), + this.num("Travel", "travel", "length", { onInput: (v) => this.setTravel(v) }), + modeChoice(() => this.feature.mode, (m) => ((this.feature.mode = m), this.update()), () => this.render()), + ]; + } + + enter(): void { + super.enter(); + this.onDraftChanged(); + } + + exit(): void { + this.handle?.dispose(); + this.dim?.dispose(); + super.exit(); + } + + /** Where the profile sits on the axis (the arrow starts there). */ + private axisBase(): Vec3 { + const { origin, dir } = this.feature.axis; + const d = norm(dir); + const c = sourceFrame(this.app, this.feature.source).base; + return add(origin, scale(d, dot(sub(c, origin), d))); + } + + protected onDraftChanged(): void { + if (!this.axisSet) return; + const d = norm(this.feature.axis.dir); + const base = this.axisBase(); + const travel = this.feature.travel ?? 0; + if (!this.handle) { + this.handle = new Handle(this.app.view, "arrow"); + this.dim = new DimWidget(this.app.view, { boxAt: "beyond", boxGap: 96, dir: d, value: travel, onInput: (v) => this.setTravel(v), onCommit: () => this.done() }); + } + const tip = add(base, scale(d, travel)); + this.handle.set(tip, travel < 0 ? scale(d, -1) : d); + this.dim!.set(base, tip); + } + + private setTravel(v: number): void { + this.feature.travel = v || undefined; + // Travelling with just a part of a turn is fine; a full turn is the usual start for a thread. + this.app.ui.updatePanelValues([this.feature.angle, v]); + this.dim?.setValue(v); + this.update(); + } + + hover(p: ToolPointer | null): void { + const on = !!p && !!this.handle && (!!this.dragging || this.handle.hit(p)); + this.handle?.setHot(on); + if (!on) super.hover(p); + } + + down(p: ToolPointer): boolean { + if (!this.handle?.hit(p)) return false; + this.dragging = { from: p, t0: this.feature.travel ?? 0 }; + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + if (!dr) return; + this.typing.track(p); + if (this.typing.active) return; + const d = norm(this.feature.axis.dir); + const raw = dr.t0 + axisDrag(this.app.view, add(this.axisBase(), scale(d, dr.t0)), d, dr.from, p); + const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4); + this.setTravel(Math.round(raw / step) * step); + this.app.ui.setLabel(p.x, p.y, `Travel ${fmtLen(this.feature.travel ?? 0)} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.handle?.setHot(false); + } + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "length", + apply: (v) => this.setTravel(v), + commit: () => ((this.dragging = null), this.done()), + cancel: () => this.setTravel(dr.t0), + }); + } +} + +// ------------------------------------------------------------------- sweep + +export class SweepOp extends FeatureOp { + readonly id = "sweep"; + private path: PathRef | null = null; + + constructor(app: AppContext, source: ExtrudeSource, existing?: SweepFeature) { + super(app, { ...app.store.newIdentity("sweep"), type: "sweep", source, path: { kind: "sketch", sketch: "", entities: [] }, mode: "auto", target: targetOf(app, source) }, existing); + if (existing) this.path = existing.path; + this.slots = [pathSlot(app, () => this.path, (p) => ((this.path = p), (this.feature.path = p)))]; + } + + protected hint(): string { + return "Tap more curves to extend the path. Done when ready."; + } + + protected items(): PanelItem[] { + return [modeChoice(() => this.feature.mode, (m) => ((this.feature.mode = m), this.update()), () => this.render())]; + } +} + +// -------------------------------------------------------------------- loft + +export class LoftOp extends FeatureOp { + readonly id = "loft"; + + constructor(app: AppContext, sections: ExtrudeSource[], initial: Sel[], existing?: LoftFeature) { + super(app, { ...app.store.newIdentity("loft"), type: "loft", sections, ruled: false, mode: "new" }, existing); + this.slots = [sectionsSlot(app, () => this.feature.sections, (s) => (this.feature.sections = s), initial)]; + } + + protected hint(): string { + return "Tap profiles in the order the shape should pass through them."; + } + + protected items(): PanelItem[] { + return [ + { type: "toggle", label: "Straight sides", value: this.feature.ruled, onChange: (v) => ((this.feature.ruled = v), this.render(), this.update()) }, + modeChoice(() => this.feature.mode, (m) => ((this.feature.mode = m), this.update()), () => this.render()), + ]; + } +} + +// ------------------------------------------------------------------- shell + +export class ShellOp extends FeatureOp { + readonly id = "shell"; + + constructor(app: AppContext, body: string, faces: FaceRef[], existing?: ShellFeature) { + super(app, { ...app.store.newIdentity("shell"), type: "shell", body, faces, thickness: 1 }, existing); + this.slots = [facesSlot(app, "Open faces", () => this.feature.faces, (f) => (this.feature.faces = f), true)]; + this.active = 0; + } + + enter(): void { + super.enter(); + this.active = 0; + this.render(); + } + + protected hint(): string { + return "Tap faces to remove (open). Set the wall thickness."; + } + + protected items(): PanelItem[] { + return [this.num("Thickness", "thickness", "length", { min: 0.0001 })]; + } +} + +// --------------------------------------------------------------- transforms + +type TransformKind = "move" | "translate" | "rotate" | "scale" | "mirror" | "linear" | "circular"; +const TITLES: Record = { + move: "Move/Rotate", + translate: "Translate", + rotate: "Rotate Around Axis", + scale: "Scale", + mirror: "Mirror", + linear: "Pattern – Linear", + circular: "Pattern – Circular", +}; + +/** Move/rotate, translate, rotate around axis, scale, mirror and patterns of bodies. */ +export class TransformOp extends FeatureOp { + readonly id = "transform"; + private dir: Vec3 | null = null; + private axis: AxisRef | null = null; + private plane: PlaneDef | null = null; + private distance = 10; + private gimbal: Gimbal | null = null; + private dragging: { from: ToolPointer; part: GimbalPart; t0: Vec3; a0: number; center: Vec3 } | null = null; + /** Body centre before this move (rotation pivot; the gimbal sits at centre + translate). */ + private center: Vec3; + + constructor( + app: AppContext, + private kind: TransformKind, + bodies: string[], + existing?: TransformFeature, + /** Gimbal/rotation pivot (e.g. a selected vertex); default the bodies' centre. */ + pivot?: Vec3, + /** Move makes a copy (the gimbal's Copy switch). */ + copy = false, + ) { + const center = pivot ?? bodyCenter(app, bodies); + const op: TransformFeature["op"] = + kind === "scale" + ? { kind: "scale", center, factor: 1 } + : kind === "mirror" + ? { kind: "mirror", plane: { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } } + : kind === "linear" + ? { kind: "linear", dir: [1, 0, 0], spacing: 20, count: 3 } + : kind === "circular" + ? { kind: "circular", axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, count: 6, angle: 360 } + : { kind: "move", translate: [0, 0, 0], rotate: { origin: center, axis: [0, 0, 1], angle: 0 } }; + const label = kind === "linear" || kind === "circular" ? "Pattern" : TITLES[kind].split(" ")[0].replace("/Rotate", ""); + super(app, { ...app.store.newIdentity("transform", copy ? "Copy" : label), type: "transform", bodies, copy: kind === "mirror" || copy, op }, existing); + const o = this.feature.op; + if (existing) { + if (o.kind === "mirror") this.plane = o.plane; + if (o.kind === "linear") this.dir = o.dir; + if (o.kind === "circular") this.axis = o.axis; + if (o.kind === "move" && o.rotate) this.axis = { origin: o.rotate.origin, dir: o.rotate.axis }; + } + if (kind === "mirror") this.slots = [planeSlot(app, "Mirror plane", () => this.plane, (p) => ((this.plane = p), ((this.feature.op as { plane: PlaneDef }).plane = p)))]; + if (kind === "linear") + this.slots = [directionSlot(app, "Direction", () => this.dir, (d) => ((this.dir = norm(d)), this.applyDir()))]; + // Translate: from a point on it to where that point should go (size unchanged). + if (kind === "translate") + this.slots = [ + pointSlot(app, "From point", () => this.from, (p) => ((this.from = p), this.applyPoints())), + pointSlot(app, "To point", () => this.to, (p) => ((this.to = p), this.applyPoints())), + ]; + if (kind === "circular" || kind === "rotate") + this.slots = [axisSlot(app, "Axis", () => this.axis, (a) => ((this.axis = a), this.applyAxis()))]; + this.center = o.kind === "move" && o.rotate ? o.rotate.origin : center; + if (kind === "move") { + this.gimbal = new Gimbal(app.view); + const g = this.gimbal; + this.copyToggle = new CopyToggle(app.view, () => g.origin, (on) => ((this.feature.copy = on), this.render(), this.update())); + } + } + + private copyToggle: CopyToggle | null = null; + private from: Vec3 | null = null; + private to: Vec3 | null = null; + + private applyPoints(): void { + const o = this.feature.op; + if (o.kind === "move" && this.from && this.to) { + o.translate = sub(this.to, this.from); + o.rotate = undefined; + } + } + + /** A finished copy is selected, gimbal and all, so the next drag copies it again. */ + protected done(): void { + const f = this.feature; + const copied = this.kind === "move" && f.copy && this.ready() && !this.existing; + super.done(); + if (copied) this.app.setSelection(f.bodies.map((b) => ({ kind: "body" as const, body: `${f.id}:${b}:0` }))); + } + + protected hint(): string { + switch (this.kind) { + case "move": + return "Drag an arrow, square or arc of the gimbal — or type exact values. Tap empty space when done."; + case "mirror": + return "Mirror creates a copy unless you turn Copy off."; + case "translate": + return "Tap a point on the body (a corner, edge or face), then the point it should move to."; + default: + return `${TITLES[this.kind]}: set the values, then Done.`; + } + } + + private applyDir(): void { + const o = this.feature.op; + if (o.kind === "linear" && this.dir) o.dir = this.dir; + if (this.kind === "translate" && o.kind === "move" && this.dir) o.translate = scale(this.dir, this.distance); + } + + private applyAxis(): void { + const o = this.feature.op; + if (o.kind === "circular" && this.axis) o.axis = this.axis; + if (o.kind === "move" && this.axis) o.rotate = { origin: this.axis.origin, axis: this.axis.dir, angle: o.rotate?.angle ?? 90 }; + } + + protected items(): PanelItem[] { + const o = this.feature.op; + const up = () => this.update(); + const copy: PanelItem = { type: "toggle", label: "Copy", value: this.feature.copy, onChange: (v) => ((this.feature.copy = v), this.render(), up()) }; + switch (o.kind) { + case "scaleXYZ": + return []; + case "move": + if (this.kind === "translate") return [...(["X", "Y", "Z"] as const).map((l, i): PanelItem => this.num(`Δ${l}`, `op.translate.${i}`, "length")), copy]; + if (this.kind === "rotate") return [{ type: "number", label: "Angle", value: o.rotate?.angle ?? 0, kind: "angle", onInput: (v) => ((o.rotate = { ...(o.rotate ?? { origin: [0, 0, 0], axis: [0, 0, 1] }), angle: v }), up()) }, copy]; + return [ + ...(["X", "Y", "Z"] as const).map((l, i): PanelItem => this.num(`Δ${l}`, `op.translate.${i}`, "length")), + o.rotate + ? this.num(`Rotate ${axisName(o.rotate.axis)}`, "op.rotate.angle", "angle") + : { type: "number", label: "Rotate Z", value: 0, kind: "angle", onInput: (v) => ((o.rotate = { origin: this.center, axis: [0, 0, 1], angle: v }), up()) }, + copy, + ]; + case "scale": + return [this.num("Factor", "op.factor", "number", { min: 0.0001 }), copy]; + case "mirror": + return [copy]; + case "linear": + return [ + this.num("Count", "op.count", "int", { min: 2 }), + this.num("Spacing", "op.spacing", "length"), + ]; + case "circular": + return [ + this.num("Count", "op.count", "int", { min: 2 }), + this.num("Angle", "op.angle", "angle"), + ]; + } + } + + protected ready(): boolean { + const o = this.feature.op; + // An untouched move is not worth a history step. + if (this.kind === "move" && o.kind === "move" && len(o.translate) < 1e-9 && !o.rotate?.angle && !this.feature.copy) return false; + return super.ready() && this.feature.bodies.length > 0; + } + + exit(): void { + this.gimbal?.dispose(); + this.copyToggle?.dispose(); + super.exit(); + } + + protected onDraftChanged(): void { + const o = this.feature.op; + if (this.gimbal && o.kind === "move") this.gimbal.setCenter(add(this.center, o.translate)); + } + + hover(p: ToolPointer | null): void { + if (this.gimbal) this.gimbal.setHot(p && !this.dragging ? this.gimbal.hit(p) : this.dragging?.part ?? null); + else super.hover(p); + } + + down(p: ToolPointer): boolean { + const o = this.feature.op; + const part = this.gimbal?.hit(p); + if (!part || o.kind !== "move") return false; + // A different rotation axis than the one already used: start from the current angle 0 on that axis. + if (part.kind === "ring" && o.rotate && o.rotate.angle && axisIndex(o.rotate.axis) !== part.i) { + this.app.ui.toast("One rotation axis per move — press Done, then rotate around the next axis"); + return true; + } + this.dragging = { from: p, part, t0: [...o.translate] as Vec3, a0: o.rotate?.angle ?? 0, center: add(this.center, o.translate) }; + this.gimbal!.setHot(part); + return true; + } + + drag(p: ToolPointer): void { + const o = this.feature.op; + const dr = this.dragging; + if (!dr || o.kind !== "move") return; + this.typing.track(p); + if (this.typing.active) return; + const view = this.app.view; + const step = niceStep(view.cam.worldPerPixel(view.height) * 4); + const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step); + const part = dr.part; + if (part.kind === "axis") { + const dir = GIMBAL_AXES[part.i]; + const d = snap(axisDrag(view, dr.center, dir, dr.from, p)); + o.translate = add(dr.t0, scale(dir, d)); + this.app.ui.setLabel(p.x, p.y, fmtLen(d)); + } else if (part.kind === "plane" || part.kind === "center") { + // Move in the plane of the square (or the screen plane for the centre). + const n: Vec3 = part.kind === "plane" ? GIMBAL_AXES[part.i] : (view.cam.viewDir().toArray() as Vec3); + const plane = { origin: dr.center, normal: n, xDir: xDirFor(n) }; + const a = view.rayToPlane(dr.from.x, dr.from.y, plane); + const b = view.rayToPlane(p.x, p.y, plane); + if (!a || !b) return; + const d = sub(b, a); + o.translate = add(dr.t0, [snap(d[0]), snap(d[1]), snap(d[2])]); + this.app.ui.setLabel(p.x, p.y, fmtLen(len(sub(o.translate, dr.t0)))); + } else { + const axis = GIMBAL_AXES[part.i]; + const c = view.toScreen(dr.center); + if (!c) return; + const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]); + // Screen y points down, so a visual counter-clockwise turn is a negative atan2 change. + const facing = dot(axis, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1; + let deg = (-(ang(p) - ang(dr.from)) * 180) / Math.PI * facing; + deg = ((deg + 540) % 360) - 180; + const total = p.shift ? dr.a0 + deg : Math.round((dr.a0 + deg) / 5) * 5; + o.rotate = { origin: this.center, axis, angle: total }; + this.app.ui.setLabel(p.x, p.y, `${Math.round(total * 10) / 10}°`); + } + this.app.ui.updatePanelValues([o.translate[0], o.translate[1], o.translate[2], o.rotate?.angle ?? 0]); + this.update(); + } + + up(): void { + const dragged = !!this.dragging; + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.gimbal?.setHot(null); + // Copy on: letting go makes the copy (and selects it), so the next drag copies again. + if (dragged && this.kind === "move" && this.feature.copy && !this.existing && this.ready()) return this.done(); + // The rotate field's label names the axis just used. + this.render(); + } + + private typing = new DragTyping(this.app); + + /** Typed while dragging: distance for arrows/squares/centre, angle for arcs. */ + dragKey(e: KeyboardEvent): boolean { + const o = this.feature.op; + const dr = this.dragging; + if (!dr || o.kind !== "move") return false; + const part = dr.part; + const refresh = () => { + this.app.ui.updatePanelValues([o.translate[0], o.translate[1], o.translate[2], o.rotate?.angle ?? 0]); + this.update(); + }; + // Squares/centre: along the direction dragged so far. + const dragDir = norm(sub(o.translate, dr.t0)); + return this.typing.key(e, { + kind: part.kind === "ring" ? "angle" : "length", + apply: (v) => { + if (part.kind === "ring") o.rotate = { origin: this.center, axis: GIMBAL_AXES[part.i], angle: dr.a0 + v }; + else if (part.kind === "axis") o.translate = add(dr.t0, scale(GIMBAL_AXES[part.i], v)); + else if (len(dragDir) > 0.5) o.translate = add(dr.t0, scale(dragDir, v)); + refresh(); + }, + commit: () => ((this.dragging = null), this.gimbal?.setHot(null), this.done()), + cancel: () => ((o.translate = [...dr.t0] as Vec3), o.rotate && (o.rotate.angle = dr.a0), refresh()), + }); + } +} + +// --------------------------------------------------------- move face/edge + +/** + * Move/rotate just one flat face or one straight edge: the gimbal sits on it, + * the rest of the body stretches to follow. Only the parts that change the + * geometry are shown (a face can't slide within its own plane). + */ +export class MoveFaceOp extends FeatureOp { + readonly id = "moveFace"; + private gimbal: Gimbal; + private axes: Vec3[]; + private center: Vec3; + private dragging: { from: ToolPointer; part: GimbalPart; t0: Vec3; a0: number; center: Vec3 } | null = null; + + constructor(app: AppContext, target: { face: FaceRef; plane: PlaneDef } | { edge: EdgeRef } | { vertex: { body: string; at: Vec3 } }, existing?: MoveFaceFeature) { + const isFace = "face" in target; + const isVertex = "vertex" in target; + const center = isFace ? target.face.center : isVertex ? target.vertex.at : target.edge.mid; + super( + app, + { + ...app.store.newIdentity("moveFace", isFace ? "Move Face" : isVertex ? "Move Vertex" : "Move Edge"), + type: "moveFace", + ...(isFace ? { face: target.face } : isVertex ? { vertex: target.vertex } : { edge: target.edge }), + translate: [0, 0, 0], + }, + existing, + ); + if (isVertex) { + // A point just moves (turning it about itself would do nothing). + this.axes = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + this.gimbal = new Gimbal(app.view, { parts: (p) => p.kind !== "ring" }); + this.center = center; + return; + } + if (isFace) { + const n = norm(target.plane.normal); + const x = norm(target.plane.xDir); + this.axes = [x, cross(n, x), n]; + } else { + const d = norm(target.edge.dir); + const u = xDirFor(d); + this.axes = [d, u, cross(d, u)]; + } + // Face: push along the normal, tilt about the in-plane axes. Edge: move across it, tilt it. + const parts = isFace + ? (p: GimbalPart) => (p.kind === "axis" && p.i === 2) || (p.kind === "ring" && p.i < 2) + : (p: GimbalPart) => (p.kind === "axis" && p.i > 0) || (p.kind === "plane" && p.i === 0) || (p.kind === "ring" && p.i > 0); + this.gimbal = new Gimbal(app.view, { axes: this.axes, parts }); + this.center = this.feature.rotate?.origin ?? center; + } + + protected hint(): string { + return "Drag an arrow to move it, an arc to tilt it — or type a value while dragging."; + } + + protected items(): PanelItem[] { + const f = this.feature; + const xyz = (["X", "Y", "Z"] as const).map((l, i): PanelItem => this.num(`Δ${l}`, `translate.${i}`, "length")); + if (f.vertex) return xyz; + return [ + ...xyz, + f.rotate ? this.num("Tilt", "rotate.angle", "angle") : { type: "number", label: "Tilt", value: 0, kind: "angle", onInput: (v) => ((f.rotate = { origin: this.center, axis: this.axes[0], angle: v }), this.update()) }, + ]; + } + + protected ready(): boolean { + return len(this.feature.translate) > 1e-9 || Math.abs(this.feature.rotate?.angle ?? 0) > 1e-9; + } + + exit(): void { + this.gimbal.dispose(); + super.exit(); + } + + protected onDraftChanged(): void { + this.gimbal.setCenter(add(this.center, this.feature.translate)); + } + + hover(p: ToolPointer | null): void { + this.gimbal.setHot(p && !this.dragging ? this.gimbal.hit(p) : (this.dragging?.part ?? null)); + } + + down(p: ToolPointer): boolean { + const part = this.gimbal.hit(p); + if (!part) return false; + const r = this.feature.rotate; + if (part.kind === "ring" && r && r.angle && dot(r.axis, this.axes[part.i]) < 0.999) { + this.app.ui.toast("One tilt axis per move — press Done, then tilt around the next axis"); + return true; + } + this.dragging = { from: p, part, t0: [...this.feature.translate] as Vec3, a0: r?.angle ?? 0, center: add(this.center, this.feature.translate) }; + this.gimbal.setHot(part); + return true; + } + + drag(p: ToolPointer): void { + const f = this.feature; + const dr = this.dragging; + if (!dr) return; + this.typing.track(p); + if (this.typing.active) return; + const view = this.app.view; + const step = niceStep(view.cam.worldPerPixel(view.height) * 4); + const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step); + const part = dr.part; + if (part.kind === "axis") { + const dir = this.axes[part.i]; + const d = snap(axisDrag(view, dr.center, dir, dr.from, p)); + f.translate = add(dr.t0, scale(dir, d)); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(d)} · type a value`); + } else if (part.kind === "center") { + // Free move in the screen plane. + const n = view.cam.viewDir().toArray() as Vec3; + const plane = { origin: dr.center, normal: n, xDir: xDirFor(n) }; + const a = view.rayToPlane(dr.from.x, dr.from.y, plane); + const b = view.rayToPlane(p.x, p.y, plane); + if (!a || !b) return; + const d = sub(b, a); + f.translate = add(dr.t0, [snap(d[0]), snap(d[1]), snap(d[2])]); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(len(sub(f.translate, dr.t0)))} · type a value`); } else if (part.kind === "plane") { + const n = this.axes[part.i]; + const plane = { origin: dr.center, normal: n, xDir: xDirFor(n) }; + const a = view.rayToPlane(dr.from.x, dr.from.y, plane); + const b = view.rayToPlane(p.x, p.y, plane); + if (!a || !b) return; + const d = sub(b, a); + f.translate = add(dr.t0, [snap(d[0]), snap(d[1]), snap(d[2])]); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(len(sub(f.translate, dr.t0)))} · type a value`); + } else if (part.kind === "ring") { + const axis = this.axes[part.i]; + const c = view.toScreen(dr.center); + if (!c) return; + const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]); + const facing = dot(axis, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1; + let deg = ((-(ang(p) - ang(dr.from)) * 180) / Math.PI) * facing; + deg = ((deg + 540) % 360) - 180; + const total = p.shift ? dr.a0 + deg : Math.round(dr.a0 + deg); + f.rotate = { origin: this.center, axis, angle: total }; + this.app.ui.setLabel(p.x, p.y, `${Math.round(total * 10) / 10}° · type a value`); + } + this.app.ui.updatePanelValues([f.translate[0], f.translate[1], f.translate[2], f.rotate?.angle ?? 0]); + this.update(); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.gimbal.setHot(null); + this.render(); + } + + private typing = new DragTyping(this.app); + + dragKey(e: KeyboardEvent): boolean { + const f = this.feature; + const dr = this.dragging; + if (!dr) return false; + const part = dr.part; + const refresh = () => { + this.app.ui.updatePanelValues([f.translate[0], f.translate[1], f.translate[2], f.rotate?.angle ?? 0]); + this.update(); + }; + const dragDir = norm(sub(f.translate, dr.t0)); + return this.typing.key(e, { + kind: part.kind === "ring" ? "angle" : "length", + apply: (v) => { + if (part.kind === "ring") f.rotate = { origin: this.center, axis: this.axes[part.i], angle: dr.a0 + v }; + else if (part.kind === "axis") f.translate = add(dr.t0, scale(this.axes[part.i], v)); + else if (len(dragDir) > 0.5) f.translate = add(dr.t0, scale(dragDir, v)); + refresh(); + }, + commit: () => ((this.dragging = null), this.gimbal.setHot(null), this.done()), + cancel: () => ((f.translate = [...dr.t0] as Vec3), f.rotate && (f.rotate.angle = dr.a0), refresh()), + }); + } +} + +// ------------------------------------------------------------------ scale + +/** + * Scale bodies with the cube-ended scale gimbal: drag the centre (or type) for + * a uniform factor; in XYZ mode drag one axis to stretch along it. + * The factor follows the drag: the handle's distance from the centre, relative + * to where it started. + */ +export class ScaleOp extends FeatureOp { + readonly id = "scale"; + private gimbal: Gimbal; + private dragging: { part: GimbalPart; from: ToolPointer; k0: Vec3; r0: number } | null = null; + private typing = new DragTyping(this.app); + + constructor( + app: AppContext, + private xyz: boolean, + bodies: string[], + existing?: TransformFeature, + ) { + const center = bodyCenter(app, bodies); + const op: TransformFeature["op"] = xyz ? { kind: "scaleXYZ", center, factors: [1, 1, 1] } : { kind: "scale", center, factor: 1 }; + super(app, { ...app.store.newIdentity("transform", xyz ? "Scale XYZ" : "Scale"), type: "transform", bodies, copy: false, op }, existing); + this.xyz = this.feature.op.kind === "scaleXYZ"; + this.gimbal = new Gimbal(app.view, { cubes: true, parts: this.xyz ? SCALE_PARTS : (p) => p.kind === "center" || p.kind === "axis" }); + this.gimbal.setCenter((this.feature.op as { center: Vec3 }).center); + } + + private get factors(): Vec3 { + const o = this.feature.op; + return o.kind === "scaleXYZ" ? o.factors : o.kind === "scale" ? [o.factor, o.factor, o.factor] : [1, 1, 1]; + } + + private setFactors(k: Vec3): void { + const o = this.feature.op; + if (o.kind === "scaleXYZ") o.factors = k; + else if (o.kind === "scale") o.factor = k[0]; + this.app.ui.updatePanelValues(this.xyz ? k : [k[0]]); + this.update(); + } + + protected hint(): string { + return this.xyz + ? "Drag an axis handle to stretch along it, or the centre for all three — type a factor while dragging. Works on freeform bodies." + : "Drag a handle (or the centre) to scale — type a factor while dragging (e.g. 2 doubles the size)."; + } + + protected items(): PanelItem[] { + if (this.xyz) return (["X", "Y", "Z"] as const).map((l, i): PanelItem => this.num(`Scale ${l}`, `op.factors.${i}`, "number", { min: 0.0001 })); + return [this.num("Factor", "op.factor", "number", { min: 0.0001 }), { type: "toggle", label: "Copy", value: this.feature.copy, onChange: (v) => ((this.feature.copy = v), this.render(), this.update()) }]; + } + + protected ready(): boolean { + return this.factors.some((k) => Math.abs(k - 1) > 1e-9) || this.feature.copy; + } + + exit(): void { + this.gimbal.dispose(); + super.exit(); + } + + hover(p: ToolPointer | null): void { + this.gimbal.setHot(p && !this.dragging ? this.gimbal.hit(p) : (this.dragging?.part ?? null)); + } + + down(p: ToolPointer): boolean { + const part = this.gimbal.hit(p); + if (!part) return false; + const c = this.app.view.toScreen(this.gimbal.origin); + // Distance of the press from the centre on screen = "factor 1" for this drag. + const r0 = c ? Math.max(24, Math.hypot(p.x - c[0], p.y - c[1])) : 60; + this.dragging = { part, from: p, k0: [...this.factors] as Vec3, r0 }; + this.gimbal.setHot(part); + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + if (!dr) return; + this.typing.track(p); + if (this.typing.active) return; + const view = this.app.view; + const c = view.toScreen(this.gimbal.origin); + if (!c) return; + let f: number; + if (dr.part.kind === "axis") { + // Along the axis on screen: how far the handle has been pulled out or pushed in. + const pxPerUnit = view.cam.worldPerPixel(view.height); + const along = axisDrag(view, this.gimbal.origin, GIMBAL_AXES[dr.part.i], dr.from, p) / pxPerUnit; + f = (dr.r0 + along) / dr.r0; + } else f = Math.hypot(p.x - c[0], p.y - c[1]) / dr.r0; + f = Math.max(0.01, p.shift ? f : Math.round(f * 100) / 100); + const k = [...dr.k0] as Vec3; + if (dr.part.kind === "axis" && this.xyz) k[dr.part.i] = dr.k0[dr.part.i] * f; + else for (let i = 0; i < 3; i++) k[i] = dr.k0[i] * f; + this.setFactors(k); + this.app.ui.setLabel(p.x, p.y, `×${(dr.part.kind === "axis" && this.xyz ? k[dr.part.i] : k[0]).toFixed(2)} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.gimbal.setHot(null); + } + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "number", + apply: (v) => { + if (v <= 0) return; + const k = [...dr.k0] as Vec3; + if (dr.part.kind === "axis" && this.xyz) k[dr.part.i] = v; + else k.fill(v); + this.setFactors(k); + }, + commit: () => ((this.dragging = null), this.gimbal.setHot(null), this.done()), + cancel: () => this.setFactors(dr.k0), + }); + } +} + +/** + * Scale a flat face within its plane: two in-plane handles (along the face's + * own axes) and the centre for both at once. The sides tilt to follow. + */ +export class ScaleFaceOp extends FeatureOp { + readonly id = "scaleFace"; + private gimbal: Gimbal; + private axes: Vec3[]; + private dragging: { part: GimbalPart; from: ToolPointer; k0: [number, number]; r0: number } | null = null; + private typing = new DragTyping(this.app); + + constructor(app: AppContext, face: FaceRef, plane: PlaneDef, existing?: ScaleFaceFeature) { + const n = norm(plane.normal); + const u = norm(plane.xDir); + super(app, { ...app.store.newIdentity("scaleFace"), type: "scaleFace", face, u, factors: [1, 1] }, existing); + const uu = norm(this.feature.u); + this.axes = [uu, cross(n, uu), n]; + this.gimbal = new Gimbal(app.view, { axes: this.axes, cubes: true, parts: (p) => p.kind === "center" || (p.kind === "axis" && p.i < 2) }); + this.gimbal.setCenter(face.center); + } + + protected hint(): string { + return "Drag a handle to scale the face along it, or the centre for both — type a factor while dragging. The sides tilt to follow."; + } + + protected items(): PanelItem[] { + return [this.num("Scale U", "factors.0", "number", { min: 0.0001 }), this.num("Scale V", "factors.1", "number", { min: 0.0001 })]; + } + + protected ready(): boolean { + return this.feature.factors.some((k) => Math.abs(k - 1) > 1e-9); + } + + exit(): void { + this.gimbal.dispose(); + super.exit(); + } + + hover(p: ToolPointer | null): void { + this.gimbal.setHot(p && !this.dragging ? this.gimbal.hit(p) : (this.dragging?.part ?? null)); + } + + down(p: ToolPointer): boolean { + const part = this.gimbal.hit(p); + if (!part) return false; + const c = this.app.view.toScreen(this.gimbal.origin); + const r0 = c ? Math.max(24, Math.hypot(p.x - c[0], p.y - c[1])) : 60; + this.dragging = { part, from: p, k0: [...this.feature.factors] as [number, number], r0 }; + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + if (!dr) return; + this.typing.track(p); + if (this.typing.active) return; + const view = this.app.view; + const c = view.toScreen(this.gimbal.origin); + if (!c) return; + let f: number; + if (dr.part.kind === "axis") f = (dr.r0 + axisDrag(view, this.gimbal.origin, this.axes[dr.part.i], dr.from, p) / view.cam.worldPerPixel(view.height)) / dr.r0; + else f = Math.hypot(p.x - c[0], p.y - c[1]) / dr.r0; + f = Math.max(0.01, p.shift ? f : Math.round(f * 100) / 100); + const k: [number, number] = [...dr.k0]; + if (dr.part.kind === "axis") k[dr.part.i as 0 | 1] = dr.k0[dr.part.i as 0 | 1] * f; + else ((k[0] = dr.k0[0] * f), (k[1] = dr.k0[1] * f)); + this.feature.factors = k; + this.app.ui.updatePanelValues(k); + this.update(); + this.app.ui.setLabel(p.x, p.y, `×${(dr.part.kind === "axis" ? k[dr.part.i as 0 | 1] : k[0]).toFixed(2)} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + } + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "number", + apply: (v) => { + if (v <= 0) return; + const k: [number, number] = [...dr.k0]; + if (dr.part.kind === "axis") k[dr.part.i as 0 | 1] = v; + else ((k[0] = v), (k[1] = v)); + this.feature.factors = k; + this.app.ui.updatePanelValues(k); + this.update(); + }, + commit: () => ((this.dragging = null), this.done()), + cancel: () => ((this.feature.factors = dr.k0), this.update()), + }); + } +} + +/** Replace a flat face: it moves onto another flat face or plane, the rest follows. */ +export class ReplaceFaceOp extends FeatureOp { + readonly id = "replaceFace"; + protected finishWhenPicked = true; + + constructor(app: AppContext, face: FaceRef, existing?: ReplaceFaceFeature) { + super(app, { ...app.store.newIdentity("replaceFace"), type: "replaceFace", face, plane: { origin: face.center, normal: face.normal, xDir: xDirFor(face.normal) } }, existing); + let picked = !!existing; + this.slots = [ + planeSlot(app, "Replace with", () => (picked ? this.feature.plane : null), (pl, target) => { + picked = true; + this.feature.plane = pl; + this.feature.target = target; + }), + ]; + } + + protected hint(): string { + return "Tap the face or plane it should move onto."; + } + + protected items(): PanelItem[] { + return []; + } +} + +function axisIndex(a: Vec3): number { + return a.findIndex((v) => Math.abs(v) > 0.99); +} + +function axisName(a?: Vec3): string { + return ["X", "Y", "Z"][a ? Math.max(0, axisIndex(a)) : 2]; +} + +export function bodyCenter(app: AppContext, bodies: string[]): Vec3 { + const pts = bodies.flatMap((id) => app.view.body(id)?.faces.map((f) => f.center) ?? []); + if (!pts.length) return [0, 0, 0]; + return scale(pts.reduce((a, b) => add(a, b), [0, 0, 0] as Vec3), 1 / pts.length); +} + +// ------------------------------------------------------------------- image + +/** Move / rotate (gimbal), scale and fade a reference image. */ +export class ImageOp extends FeatureOp { + readonly id = "image"; + private gimbal: Gimbal; + private dragging: { from: ToolPointer; part: GimbalPart; origin: Vec3; xDir: Vec3 } | null = null; + private aspect: number; + + constructor(app: AppContext, existing: ImageFeature) { + super(app, existing, existing); + this.aspect = existing.height / existing.width; + const p = existing.plane; + this.gimbal = new Gimbal(app.view, { axes: [p.xDir, cross(p.normal, p.xDir), p.normal], parts: IN_PLANE }); + } + + protected hint(): string { + return "Drag the gimbal to move or rotate the image; set its width and opacity."; + } + + protected items(): PanelItem[] { + return [ + this.num("Width", "width", "length", { min: 0.001, onInput: (v) => ((this.feature.height = v * this.aspect), this.update()) }), + { type: "number", label: "Opacity", value: this.feature.opacity, kind: "number", min: 0.05, onInput: (v) => ((this.feature.opacity = Math.min(1, v)), this.update()) }, + ]; + } + + protected onDraftChanged(): void { + this.gimbal.setCenter(this.feature.plane.origin); + } + + exit(): void { + this.gimbal.dispose(); + super.exit(); + } + + hover(p: ToolPointer | null): void { + this.gimbal.setHot(p && !this.dragging ? this.gimbal.hit(p) : null); + } + + down(p: ToolPointer): boolean { + const part = this.gimbal.hit(p); + if (!part) return false; + this.dragging = { from: p, part, origin: [...this.feature.plane.origin] as Vec3, xDir: [...this.feature.plane.xDir] as Vec3 }; + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + if (!dr) return; + const view = this.app.view; + const pl = { ...this.feature.plane, origin: dr.origin }; + if (dr.part.kind === "ring") { + const c = view.toScreen(dr.origin); + if (!c) return; + const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]); + const facing = dot(pl.normal, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1; + const a = -(ang(p) - ang(dr.from)) * facing; + const y = cross(pl.normal, dr.xDir); + this.feature.plane = { ...this.feature.plane, xDir: norm(add(scale(dr.xDir, Math.cos(a)), scale(y, Math.sin(a)))) }; + } else { + const a = view.rayToPlane(dr.from.x, dr.from.y, pl); + const b = view.rayToPlane(p.x, p.y, pl); + if (!a || !b) return; + let d = sub(b, a); + if (dr.part.kind === "axis") { + const ax = this.gimbal.axes[dr.part.i]; + d = scale(ax, dot(d, ax)); + } + this.feature.plane = { ...this.feature.plane, origin: add(dr.origin, d) }; + } + this.update(); + } + + up(): void { + this.dragging = null; + this.gimbal.setHot(null); + } +} + +// ------------------------------------------------------------------- split + +export class SplitOp extends FeatureOp { + readonly id = "split"; + private plane: PlaneDef | null = null; + + constructor(app: AppContext, body: string, existing?: SplitFeature, plane?: PlaneDef) { + super(app, { ...app.store.newIdentity("split"), type: "split", body, plane: plane ?? { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] } }, existing); + this.plane = existing?.plane ?? plane ?? null; + this.slots = [planeSlot(app, "Split with", () => this.plane, (p) => ((this.plane = p), (this.feature.plane = p)))]; + } + + protected hint(): string { + return "The body is cut in two along the plane."; + } + + protected items(): PanelItem[] { + return []; + } +} + +// ------------------------------------------------------------ construction + +export class PlaneOp extends FeatureOp { + readonly id = "plane"; + private base: PlaneDef | null = null; + + constructor(app: AppContext, base: PlaneDef | null, face: FaceRef | undefined, existing?: PlaneFeature) { + super(app, { ...app.store.newIdentity("plane"), type: "plane", plane: base ?? { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }, face, offset: 10 }, existing); + this.base = existing ? existing.plane : base; + this.slots = [planeSlot(app, "From", () => this.base, (p, f) => ((this.base = p), (this.feature.plane = p), (this.feature.face = f)))]; + } + + private handle: Handle | null = null; + private dim: DimWidget | null = null; + private dragging: { from: ToolPointer; d0: number } | null = null; + private typing = new DragTyping(this.app); + + protected hint(): string { + return this.base ? "Drag the arrow or type the offset (negative goes the other way)." : "Offset the new plane from a face or plane."; + } + + protected items(): PanelItem[] { + return [this.num("Offset", "offset", "length", { onInput: (v) => this.setOffset(v) })]; + } + + enter(): void { + super.enter(); + this.onDraftChanged(); + } + + exit(): void { + this.handle?.dispose(); + this.dim?.dispose(); + super.exit(); + } + + /** The arrow and value box come out once there's a face or plane to offset from. */ + protected onDraftChanged(): void { + const b = this.base; + if (!b) return; + if (!this.handle) { + this.handle = new Handle(this.app.view, "arrow"); + this.dim = new DimWidget(this.app.view, { + boxAt: "beyond", + boxGap: 96, + dir: b.normal, + value: this.feature.offset, + onInput: (v) => this.setOffset(v), + onCommit: () => this.done(), + }); + } + const top = add(b.origin, scale(b.normal, this.feature.offset)); + // The arrow keeps pointing out of the face; the value's sign says which side. + this.handle.set(top, b.normal); + this.dim!.set(b.origin, top); + } + + private setOffset(v: number): void { + this.feature.offset = v; + this.app.ui.updatePanelValues([v]); + this.dim?.setValue(v); + this.update(); + } + + hover(p: ToolPointer | null): void { + const on = !!p && !!this.handle && (!!this.dragging || this.handle.hit(p)); + this.handle?.setHot(on); + if (!on) super.hover(p); + } + + down(p: ToolPointer): boolean { + if (!this.handle?.hit(p)) return false; + this.dragging = { from: p, d0: this.feature.offset }; + return true; + } + + drag(p: ToolPointer): void { + const dr = this.dragging; + const b = this.base; + if (!dr || !b) return; + this.typing.track(p); + if (this.typing.active) return; + const raw = dr.d0 + axisDrag(this.app.view, add(b.origin, scale(b.normal, dr.d0)), b.normal, dr.from, p); + const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4); + this.setOffset(Math.round(raw / step) * step); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(this.feature.offset)} · type a value`); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.handle?.setHot(false); + } + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "length", + apply: (v) => this.setOffset(v), + commit: () => ((this.dragging = null), this.done()), + cancel: () => this.setOffset(dr.d0), + }); + } +} + +/** Midplane between two parallel planes/faces. */ +export function midplane(a: PlaneDef, b: PlaneDef): PlaneDef | null { + if (Math.abs(dot(a.normal, b.normal)) < 0.999) return null; + return { ...a, origin: scale(add(a.origin, b.origin), 0.5) }; +} + +export class MidplaneOp extends FeatureOp { + readonly id = "plane"; + private a: PlaneDef | null = null; + private b: PlaneDef | null = null; + + constructor(app: AppContext) { + super(app, { ...app.store.newIdentity("plane", "Midplane"), type: "plane", plane: { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }, offset: 0 }); + const apply = () => { + const m = this.a && this.b ? midplane(this.a, this.b) : null; + if (m) this.feature.plane = m; + else if (this.a && this.b) this.app.ui.toast("The two planes must be parallel"); + }; + this.slots = [ + planeSlot(app, "First", () => this.a, (p) => ((this.a = p), apply())), + planeSlot(app, "Second", () => this.b, (p) => ((this.b = p), apply())), + ]; + } + + protected ready(): boolean { + return !!(this.a && this.b && midplane(this.a, this.b)); + } + + protected hint(): string { + return "A plane halfway between two parallel planes or faces."; + } + + protected items(): PanelItem[] { + return []; + } +} + +export class AxisOp extends FeatureOp { + readonly id = "axis"; + + constructor(app: AppContext, origin: Vec3, dir: Vec3, existing?: AxisFeature) { + super(app, { ...app.store.newIdentity("axis"), type: "axis", origin, dir }, existing); + } + + protected hint(): string { + return "Construction axis. Done to keep it."; + } + + protected items(): PanelItem[] { + return []; + } + + enter(): void { + super.enter(); + // Nothing to adjust: commit right away (it stays editable from History). + this.done(); + } +} + +export const planeFromNormal = (origin: Vec3, normal: Vec3): PlaneDef => ({ origin, normal: norm(normal), xDir: xDirFor(norm(normal)) }); diff --git a/src/tools/patternBox.ts b/src/tools/patternBox.ts new file mode 100644 index 0000000..e4c60cb --- /dev/null +++ b/src/tools/patternBox.ts @@ -0,0 +1,85 @@ +// A small floating box beside a pattern's drag arrow: how many copies, and how +// far apart (between neighbours, or the whole run from the first to the last). + +import { Vector3 } from "three"; +import type { Vec3 } from "../doc/types"; +import { el } from "../ui/ui"; +import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units"; +import type { Viewport } from "../view/viewport"; + +export interface PatternBoxOptions { + count: number; + spacing: number; + /** "between": spacing is from one copy to the next; "total": from the first to the last. */ + measure: "between" | "total"; + onChange(v: { count: number; spacing: number; measure: "between" | "total" }): void; + onCommit(): void; +} + +export class PatternBox { + private box = el("div", "dim-widget pattern-box"); + private count = document.createElement("input"); + private dist = document.createElement("input"); + private sel = document.createElement("select"); + private at = new Vector3(); + private hook = () => this.layout(); + + constructor( + private view: Viewport, + opts: PatternBoxOptions, + ) { + for (const [id, label] of [["between", "Between"], ["total", "Total"]]) { + const o = document.createElement("option"); + o.value = id; + o.textContent = label; + this.sel.append(o); + } + this.sel.value = opts.measure; + this.count.inputMode = "numeric"; + this.count.value = String(opts.count); + this.count.title = "Count (the original included)"; + this.dist.inputMode = "decimal"; + this.dist.value = trim(toDisplay(opts.spacing), 3); + const changed = () => { + const n = Math.round(Number(this.count.value)); + const d = evaluate(this.dist.value, "length"); + const ok = Number.isFinite(n) && n >= 2 && d !== null; + this.box.classList.toggle("invalid", !ok); + if (ok) opts.onChange({ count: n, spacing: d!, measure: this.sel.value as "between" | "total" }); + }; + for (const i of [this.count, this.dist]) { + i.spellcheck = false; + i.addEventListener("input", changed); + i.addEventListener("keydown", (e) => { + e.stopPropagation(); + if (e.key === "Enter") opts.onCommit(); + if (e.key === "Escape") i.blur(); + }); + } + this.sel.addEventListener("change", changed); + this.box.append(el("span", "dim-unit", "×"), this.count, this.sel, this.dist, el("span", "dim-unit", UNIT_LABEL[units()])); + this.box.addEventListener("pointerdown", (e) => e.stopPropagation()); + document.body.append(this.box); + view.frameHooks.add(this.hook); + view.helpers.add(this); + setTimeout(() => (this.count.focus(), this.count.select()), 0); + } + + /** Where the box sits (a world point, e.g. the arrow's tip). */ + place(p: Vec3): void { + this.at.set(...p); + this.layout(); + } + + private layout(): void { + const s = this.view.toScreen(this.at); + this.box.hidden = !s; + if (s) this.box.style.transform = `translate(${Math.round(s[0] + 24)}px, ${Math.round(s[1] - 24)}px) translate(0, -50%)`; + } + + dispose(): void { + this.view.helpers.delete(this); + this.view.frameHooks.delete(this.hook); + this.box.remove(); + } +} diff --git a/src/tools/section.ts b/src/tools/section.ts new file mode 100644 index 0000000..994146b --- /dev/null +++ b/src/tools/section.ts @@ -0,0 +1,158 @@ +import type { PlaneDef, Vec3 } from "../doc/types"; +import { add, niceStep, scale } from "../geom"; +import { fmtLen } from "../units"; +import type { ToolPointer } from "../view/input"; +import { DragTyping } from "./dragTyping"; +import { axisDrag, Handle } from "./handles"; +import { hitToSel, type AppContext, type Tool } from "./tool"; + +export interface SectionState { + plane: PlaneDef; + offset: number; + flipped: boolean; +} + +export interface SectionHost extends AppContext { + section: SectionState | null; + setSection(s: SectionState | null): void; +} + +/** The plane the view is cut with (offset and flip applied). */ +export function sectionPlane(s: SectionState): PlaneDef { + const n: Vec3 = s.flipped ? scale(s.plane.normal, -1) : s.plane.normal; + return { origin: add(s.plane.origin, scale(s.plane.normal, s.offset)), normal: n, xDir: s.plane.xDir }; +} + +/** Section view: pick a plane or flat face, then drag the cut along its normal. */ +export class SectionTool implements Tool { + readonly id = "section"; + private handle: Handle | null = null; + private dragging: { from: ToolPointer; o0: number } | null = null; + + constructor(private app: SectionHost) {} + + enter(): void { + this.app.ui.setTools([{ id: "exit", label: "Exit Section", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]); + this.app.ui.setBottom([]); + if (this.app.section) this.showControls(); + else this.askForPlane(); + } + + exit(): void { + this.handle?.dispose(); + this.handle = null; + this.app.view.setOriginPlanesVisible(false); + this.app.ui.showPanel(null); + this.app.ui.setHint(null); + this.app.ui.setLabel(0, 0, null); + } + + private askForPlane(): void { + this.app.view.setOriginPlanesVisible(true); + this.app.ui.showPanel(null); + this.app.ui.setHint("Select a plane or a flat face to cut the view with."); + } + + hover(p: ToolPointer | null): void { + if (!p || this.app.section) return this.app.setHover(null); + const hit = this.app.view.pick(p.x, p.y, { edges: false, vertices: false, profiles: false, planes: true, planesFirst: true }); + const ok = hit && (hit.kind === "plane" || (hit.kind === "face" && !!this.app.view.body(hit.body)?.faces[hit.face]?.plane)); + this.app.setHover(ok ? hitToSel(hit) : null); + } + + tap(p: ToolPointer): void { + // With a section set, tapping empty space leaves the tool (the section stays on). + if (this.app.section) { + if (!this.app.view.pick(p.x, p.y, { profiles: false })) this.app.setTool(null); + return; + } + const hit = this.app.view.pick(p.x, p.y, { edges: false, profiles: false, planes: true, planesFirst: true }); + if (!hit) return this.app.setTool(null); + let plane: PlaneDef | undefined; + if (hit?.kind === "plane") plane = this.app.view.planeOf(hit.id); + if (hit?.kind === "face") plane = this.app.view.body(hit.body)?.faces[hit.face]?.plane; + if (!plane) return; + this.app.view.setOriginPlanesVisible(false); + // A face is cut slightly inside so the face itself shows the section. + this.app.setSection({ plane, offset: hit?.kind === "face" ? -this.app.view.cam.worldPerPixel(this.app.view.height) : 0, flipped: false }); + this.showControls(); + } + + private showControls(): void { + const s = this.app.section!; + this.handle ??= new Handle(this.app.view, "arrow"); + this.placeHandle(); + this.app.ui.setHint("Drag the arrow to move the cut. Section View stays on until you delete it."); + this.app.ui.showPanel({ + title: "Section View", + items: [ + { type: "number", label: "Offset", value: s.offset, kind: "length", onInput: (v) => this.setOffset(v) }, + { type: "button", label: "Flip", icon: "flip", onClick: () => (this.app.setSection({ ...s, flipped: !this.app.section!.flipped }), this.showControls()) }, + ], + actions: [{ id: "delete", label: "Delete Section", icon: "trash", run: () => (this.app.setSection(null), this.handle?.dispose(), (this.handle = null), this.askForPlane()) }], + onDone: () => this.app.setTool(null), + }); + } + + private setOffset(v: number): void { + const s = this.app.section; + if (!s) return; + this.app.setSection({ ...s, offset: v }); + this.app.ui.updatePanelValues([v]); + this.placeHandle(); + } + + private placeHandle(): void { + const s = this.app.section; + if (!s || !this.handle) return; + this.handle.set(add(s.plane.origin, scale(s.plane.normal, s.offset)), s.plane.normal); + } + + down(p: ToolPointer): boolean { + if (!this.handle?.hit(p) || !this.app.section) return false; + this.dragging = { from: p, o0: this.app.section.offset }; + return true; + } + + private get typing(): DragTyping { + return (this._typing ??= new DragTyping(this.app)); + } + private _typing: DragTyping | null = null; + + dragKey(e: KeyboardEvent): boolean { + const dr = this.dragging; + if (!dr) return false; + return this.typing.key(e, { + kind: "length", + apply: (v) => this.setOffset(v), + commit: () => ((this.dragging = null), this.app.setTool(null)), + cancel: () => this.setOffset(dr.o0), + }); + } + + drag(p: ToolPointer): void { + const s = this.app.section; + if (!this.dragging || !s) return; + this.typing.track(p); + if (this.typing.active) return; + const base = add(s.plane.origin, scale(s.plane.normal, this.dragging.o0)); + const raw = this.dragging.o0 + axisDrag(this.app.view, base, s.plane.normal, this.dragging.from, p); + const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4); + this.setOffset(Math.round(raw / step) * step); + this.app.ui.setLabel(p.x, p.y, fmtLen(this.app.section!.offset)); + } + + up(): void { + this.dragging = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + } + + key(e: KeyboardEvent): boolean { + if (e.key === "Escape" || e.key === "Enter") { + this.app.setTool(null); + return true; + } + return false; + } +} diff --git a/src/tools/select.ts b/src/tools/select.ts new file mode 100644 index 0000000..22f8010 --- /dev/null +++ b/src/tools/select.ts @@ -0,0 +1,744 @@ +import { BODY_COLORS } from "../doc/types"; +import type { DeleteGeomFeature, FreeformFeature, EdgeRef, ExtrudeSource, FaceRef, ImageFeature, PlaneDef, SketchFeature, Vec3 } from "../doc/types"; +import { arrangement } from "../sketch/regions"; +import { projectPolyline } from "../sketch/edit"; +import type { ToolItem } from "../ui/ui"; +import type { ToolPointer } from "../view/input"; +import { add, dot, len, planeY, scale, sub } from "../geom"; +import { fmtLen } from "../units"; +import { DimWidget } from "./annotate"; +import { Gimbal, IN_PLANE } from "./gimbal"; +import { Handle } from "./handles"; +import { CopyToggle, copyMode } from "./copyToggle"; +import { FreeformTool } from "./freeform"; +import { AxisOp, bodyCenter as centerOf, EdgeOp, ExtrudeOp, ImageOp, LoftOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./ops"; +import { SketchTool, type SketchKind } from "./sketch"; +import { bodiesOf, edgeRefOf, faceRefOf, hitToSel, oppositeFace, sameSel, sourceFrame, sourcesOf, type AppContext, type Sel, type Tool } from "./tool"; + +const SOON = "Coming soon"; + +/** + * The default tool. Tap things to select them; the selection decides which + * tools are listed, and the most likely one gets a handle you can drag right away. + */ +export class SelectTool implements Tool { + readonly id = "select"; + private handle: Handle | null = null; + private handleAction: (() => Tool) | null = null; + private gimbal: Gimbal | null = null; + private copyToggle: CopyToggle | null = null; + private dim: DimWidget | null = null; + /** A tool chosen with nothing selected waits for the selection. */ + private pending: { label: string; accepts: Sel["kind"][]; run: () => void } | null = null; + + constructor(private app: AppContext) {} + + enter(): void { + this.refresh(); + } + + exit(): void { + this.clearHandle(); + this.app.ui.setHint(null); + this.app.setHover(null); + } + + hover(p: ToolPointer | null): void { + if (!p) return this.app.setHover(null); + const g = this.gimbal?.hit(p) ?? null; + this.gimbal?.setHot(g); + const onHandle = !!this.handle?.hit(p); + this.handle?.setHot(onHandle); + if (g || onHandle) { + this.app.view.canvas.style.cursor = "grab"; + return this.app.setHover(null); + } + this.app.view.canvas.style.cursor = ""; + const hit = this.pickAt(p); + this.lastHover = { x: p.x, y: p.y, hit }; + this.app.setHover(hitToSel(hit)); + } + + /** What the last hover highlighted, and where: tapping there selects exactly that. */ + private lastHover: { x: number; y: number; hit: ReturnType } | null = null; + + private tapHit(p: ToolPointer) { + const h = this.lastHover; + if (h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6) return h.hit; + return this.pickAt(p); + } + + /** + * The gimbal and the extrude arrow take over only once the pointer moves + * (dragStart): a click or double-click on top of them still selects what's + * under it — e.g. double-clicking a face seen straight on, where the arrow + * points at you and sits right on the face. + */ + down(): boolean { + return false; + } + + dragStart(p: ToolPointer): boolean { + if (this.gimbal?.hit(p)) { + const s = this.app.selection[0]; + const img = s?.kind === "image" ? this.app.store.find(s.id) : undefined; + // A vertex: its gimbal moves just that corner (the faces around it follow). + const at = s?.kind === "vertex" ? this.app.view.vertexOf(s.body, s.vertex) : undefined; + const op = img + ? new ImageOp(this.app, img) + : s?.kind === "vertex" && at + ? new MoveFaceOp(this.app, { vertex: { body: s.body, at } }) + : new TransformOp(this.app, "move", bodiesOf(this.app.selection), undefined, undefined, s?.kind === "body" && copyMode.on); + this.app.setTool(op); + return op.down(p); + } + if (!this.handle?.hit(p) || !this.handleAction) return false; + const op = this.handleAction(); + this.app.setTool(op); + return op.down?.(p) ?? false; + } + + /** Sketch curves win near them; a face outline copied into a sketch ("bnd-…") is the body's edge. */ + private pickAt(p: ToolPointer) { + const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, curves: true }); + if (hit?.kind !== "curve" && hit?.kind !== "point") return hit; + const under = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol }); + if (hit.entity.startsWith("bnd-")) return under; + // A sketch curve behind a body (seen through it) doesn't win over the body in front. + if (under && (under.kind === "face" || under.kind === "edge" || under.kind === "vertex")) { + const eye = this.app.view.cam.camera.position.toArray() as Vec3; + const far = (q: Vec3) => Math.hypot(q[0] - eye[0], q[1] - eye[1], q[2] - eye[2]); + if (far(under.point) < far(hit.point) - this.app.view.cam.worldPerPixel(this.app.view.height) * 2) return under; + } + return hit; + } + + tap(p: ToolPointer, count: number): void { + const hit = this.tapHit(p); + // Tapping a line/curve/point of a finished sketch opens it for editing, with that piece selected. + if ((hit?.kind === "curve" || hit?.kind === "point") && !this.pending) { + const tool = new SketchTool(this.app, { sketchId: hit.sketch }); + this.app.setSelection([]); + this.app.setTool(tool); + if (hit.kind === "curve") tool.preselect([hit.entity]); + else tool.preselect([], [{ e: hit.entity, p: hit.p }]); + return; + } + // Where the tap was: Edit Freeform picks the cage element there. + this.lastTap = p; + let s = hitToSel(hit); + const sel = this.app.selection; + if (!s) return this.app.setSelection([]); + // Double tap selects the whole body. + if (count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body }; + // With bodies selected, tapping another body adds it (Union/Subtract need two). + if (sel[0]?.kind === "body" && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex") && (p.add || !sel.some((x) => x.kind === "body" && x.body === (s as { body: string }).body))) { + s = { kind: "body", body: s.body }; + } + if (sel.length && sel[0].kind === s.kind) { + const i = sel.findIndex((x) => sameSel(x, s!)); + if (i >= 0 && count < 2) this.app.setSelection(sel.filter((_, j) => j !== i)); + else if (i < 0) this.app.setSelection(p.add || sel[0].kind !== "vertex" ? [...sel, s] : [s]); + } else { + this.app.setSelection([s]); + } + if (this.pending && this.pending.accepts.includes(s.kind)) { + const run = this.pending.run; + this.pending = null; + run(); + } + } + + /** Window selection: bodies entirely inside the box. */ + box(a: { x: number; y: number }, b: { x: number; y: number }, final: boolean, add: boolean): void { + if (!final) return; + const x0 = Math.min(a.x, b.x); + const x1 = Math.max(a.x, b.x); + const y0 = Math.min(a.y, b.y); + const y1 = Math.max(a.y, b.y); + const inside = this.app.view.bodyList.filter((body) => { + if (this.app.view.isHidden(body.id)) return false; + for (let i = 0; i < body.positions.length; i += 3 * Math.max(1, Math.floor(body.positions.length / 3 / 400))) { + const s = this.app.view.toScreen([body.positions[i], body.positions[i + 1], body.positions[i + 2]]); + if (!s || s[0] < x0 || s[0] > x1 || s[1] < y0 || s[1] > y1) return false; + } + return true; + }); + const picked: Sel[] = inside.map((body) => ({ kind: "body", body: body.id })); + const base = add ? this.app.selection.filter((s) => s.kind === "body") : []; + this.app.setSelection([...base, ...picked.filter((s) => !base.some((x) => sameSel(x, s)))]); + } + + key(e: KeyboardEvent): boolean { + const k = e.key.toLowerCase(); + if (k === "escape" && (this.app.selection.length || this.pending)) { + this.pending = null; + this.app.setSelection([]); + return true; + } + if (e.ctrlKey || e.metaKey) return false; + const want = k === "delete" || k === "backspace" ? "DEL" : k.toUpperCase(); + const action = flatten(this.actions()).find((a) => a.shortcut?.toUpperCase() === want && !a.disabled && a.run); + if (action) { + action.run!(); + return true; + } + return false; + } + + /** Re-derive tools and handle from the current selection. */ + refresh(): void { + this.clearHandle(); + // Whatever an earlier tool left on screen goes too (no ghost arrows or dots). + this.app.view.clearHelpers([]); + const sel = this.app.selection; + this.app.ui.setTools(sel.length ? this.actions() : this.app.mainTools()); + this.app.ui.setBottom(this.app.bottomTools()); + this.app.ui.setHint( + this.pending + ? `${this.pending.label}: select ${this.pending.accepts.join(" or ")}` + : sel.length === 0 + ? null + : `${sel.length} ${label(sel[0], sel.length)} selected`, + ); + const first = sel[0]; + if (!first) return; + // The most likely next step gets a handle. + if (first.kind === "profile") { + const src = sourcesOf(this.app, sel)[0]; + if (src) this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src)); + } else if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type)) { + // Flat and round faces: drag the arrow to offset (round faces change radius). + const src = sourcesOf(this.app, sel)[0]; + if (src) { + this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src)); + if (this.app.view.body(first.body)?.faces[first.face]?.plane) this.showFaceDimension(first, src); + } + } else if (first.kind === "face" && sel.length === 2 && sel[1].kind === "face") { + this.showFacesDistance(first, sel[1]); + } else if (first.kind === "body") { + // Body: the Move/Rotate gimbal is ready to drag (with Copy beside it). + this.gimbal = new Gimbal(this.app.view); + this.gimbal.setCenter(centerOf(this.app, bodiesOf(sel))); + const g = this.gimbal; + this.copyToggle = new CopyToggle(this.app.view, () => g.origin); + } else if (first.kind === "vertex" && sel.length === 1) { + const v = this.app.view.vertexOf(first.body, first.vertex); + // A freeform's points are moved in Edit Freeform, so no gimbal here. + if (v && this.app.store.find(first.body)?.type !== "freeform") { + this.gimbal = new Gimbal(this.app.view); + this.gimbal.setCenter(v); + } + } else if (first.kind === "image") { + const img = this.app.store.find(first.id); + if (img) { + const pl = img.plane; + this.gimbal = new Gimbal(this.app.view, { axes: [pl.xDir, planeY(pl), pl.normal], parts: IN_PLANE }); + this.gimbal.setCenter(pl.origin); + } + } else if (first.kind === "edge") { + const e = this.edgeRefs()[0]; + if (e) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", this.edgeRefs()).grabFromEdge()); + } + } + + /** Called by the app when a top-level tool needs a selection first. */ + waitFor(label: string, accepts: Sel["kind"][], run: () => void): void { + this.pending = { label, accepts, run }; + this.app.setSelection([]); + } + + // --------------------------------------------------------------- menus + + private actions(): ToolItem[] { + const sel = this.app.selection; + if (!sel.length) return []; + const head: ToolItem[] = [{ id: "deselect", label: "Deselect All", icon: "deselect", shortcut: "Esc", sub: `${sel.length} ${label(sel[0], sel.length)}`, run: () => this.app.setSelection([]) }]; + // A freeform body (or a face/edge/point of one): open its cage, picking the spot that was tapped. + const first = sel[0]; + const ff = "body" in first ? this.app.store.find(first.body) : undefined; + if (ff?.type === "freeform") head.push({ id: "editFreeform", label: "Edit Freeform", icon: "freeform", shortcut: "F2", run: () => this.editFreeform(ff) }); + switch (sel[0].kind) { + case "profile": + return [...head, ...this.profileActions()]; + case "face": + return [...head, ...this.faceActions()]; + case "edge": + return [...head, ...this.edgeActions()]; + case "body": + return [...head, ...this.bodyActions()]; + case "plane": + return [...head, ...this.planeActions()]; + case "axis": + return [...head, ...this.axisActions()]; + case "vertex": { + const bodies = bodiesOf(sel); + const s = sel[0] as Extract; + const pivot = this.app.view.vertexOf(s.body, s.vertex); + const at = sel.flatMap((x) => (x.kind === "vertex" && x.body === s.body ? [this.app.view.vertexOf(x.body, x.vertex)!].filter(Boolean) : [])); + // A freeform's points move in Edit Freeform (at the top of this list), not here. + const isFreeform = !!ff && ff.type === "freeform"; + return [ + ...head, + ...(isFreeform ? [] : [{ id: "moveVertex", label: "Move Vertex", icon: "move" as const, shortcut: "M", active: true, disabled: !pivot, run: () => pivot && this.app.setTool(new MoveFaceOp(this.app, { vertex: { body: s.body, at: pivot } })) }]), + { id: "move", label: "Move/Rotate Body", icon: "move", run: () => this.app.setTool(new TransformOp(this.app, "move", bodies, undefined, pivot)) }, + { id: "delete", label: "Delete Vertex", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { vertices: at }) }, + ]; + } + case "image": { + const img = this.app.store.find((sel[0] as Extract).id); + if (!img) return head; + return [ + ...head, + { id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", active: true, run: () => this.app.setTool(new ImageOp(this.app, img)) }, + { id: "scale", label: "Scale / Opacity", icon: "scale", shortcut: "S", run: () => this.app.setTool(new ImageOp(this.app, img)) }, + { id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => (this.app.store.remove(img.id), this.app.setSelection([])) }, + ]; + } + default: + return head; + } + } + + private profileActions(): ToolItem[] { + const app = this.app; + const sel = app.selection; + const src = sourcesOf(app, sel)[0] as Extract | undefined; + const sketchId = (sel[0] as Extract).sketch; + const plane = app.sketchPlane(sketchId); + const inSketch = (kind: string) => () => this.openSketch(sketchId, kind); + const frame = src ? sourceFrame(app, src) : null; + return [ + { id: "sketch", label: "Sketch", icon: "sketch", run: inSketch("line") }, + { id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", run: inSketch("move") }, + { id: "scale", label: "Scale Sketch", icon: "scale", run: inSketch("scale") }, + { id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: inSketch("patternLinear") }, + { id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: inSketch("patternCircular") }, + { id: "extrude", label: "Extrude", icon: "extrude", shortcut: "E", active: true, run: () => src && app.setTool(new ExtrudeOp(app, src)) }, + { id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => frame && app.setTool(new AxisOp(app, frame.base, frame.normal)) }, + { id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) }, + { id: "text", label: "Text", icon: "text", run: inSketch("text") }, + { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: inSketch("rotate") }, + { id: "mirror", label: "Mirror", icon: "mirror", run: inSketch("mirror") }, + { id: "loft", label: "Loft", icon: "loft", run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) }, + { id: "split", label: "Split Body", icon: "split", disabled: !app.view.bodyList.length || !plane, why: "Needs a body", run: () => this.splitWith(plane!) }, + { id: "revolve", label: "Revolve", icon: "revolve", shortcut: "R", run: () => src && app.setTool(new RevolveOp(app, src)) }, + { id: "sweep", label: "Sweep", icon: "sweep", shortcut: "W", run: () => src && app.setTool(new SweepOp(app, src)) }, + { id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON }, + { id: "offset", label: "Offset Edge", icon: "offset", shortcut: "O", run: inSketch("offset") }, + { id: "projs", label: "Project as Sketch", icon: "project", disabled: true, why: SOON }, + { id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON }, + { id: "wrap", label: "Wrap & Emboss", icon: "wrap", disabled: true, why: SOON }, + { id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => this.deleteProfiles() }, + ]; + } + + private faceActions(): ToolItem[] { + const app = this.app; + const sel = app.selection; + const s = sel[0] as Extract; + const info = app.view.body(s.body)?.faces[s.face]; + const flat = !!info?.plane; + const one = sel.length === 1; + const src = sourcesOf(app, sel)[0]; + const bodies = bodiesOf(sel); + const faceRefs = sel.flatMap((x) => (x.kind === "face" ? [faceRefOf(app, x)!] : [])); + const needFlat = { disabled: !flat || !one, why: "Needs one flat face" }; + const ref = faceRefOf(app, s); + return [ + { id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", ...needFlat, run: () => this.sketchOnFace() }, + // Moves just this face; the rest of the body stretches to follow. + { id: "move", label: "Move/Rotate Face", icon: "move", shortcut: "M", ...needFlat, run: () => ref && info?.plane && app.setTool(new MoveFaceOp(app, { face: ref, plane: info.plane })) }, + // Scales just this face, within its plane; the sides tilt to follow. + { id: "scale", label: "Scale Face", icon: "scale", ...needFlat, run: () => ref && info?.plane && app.setTool(new ScaleFaceOp(app, ref, info.plane)) }, + { id: "align", label: "Align", icon: "align", disabled: true, why: SOON }, + { id: "offsetFace", label: "Offset Face", icon: "offsetFace", shortcut: "E", active: true, disabled: !one || !offsettable(info?.type), why: "Needs one flat or round face", run: () => src && app.setTool(new ExtrudeOp(app, src)) }, + { id: "fillet", label: "Fillet", icon: "fillet", shortcut: "F", run: () => this.edgesOfFaces("fillet") }, + { id: "chamfer", label: "Chamfer", icon: "chamfer", run: () => this.edgesOfFaces("chamfer") }, + { id: "extrude", label: "Extrude", icon: "extrude", ...needFlat, run: () => src && app.setTool(new ExtrudeOp(app, src, undefined, "new")) }, + { id: "shell", label: "Shell", icon: "shell", run: () => app.setTool(new ShellOp(app, s.body, faceRefs)) }, + { id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => info && app.setTool(new AxisOp(app, info.center, info.normal)) }, + { id: "plane", label: "Plane – Offset", icon: "plane", ...needFlat, run: () => info?.plane && app.setTool(new PlaneOp(app, info.plane, faceRefOf(app, s)!)) }, + { id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: () => app.setTool(new TransformOp(app, "linear", bodies)) }, + { id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: () => app.setTool(new TransformOp(app, "circular", bodies)) }, + { id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) }, + { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) }, + { id: "mirror", label: "Mirror", icon: "mirror", run: () => app.setTool(new TransformOp(app, "mirror", bodies)) }, + { id: "loft", label: "Loft", icon: "loft", ...needFlat, run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) }, + { id: "split", label: "Split Body", icon: "split", disabled: !flat || app.view.bodyList.length < 2, why: "Needs another body to split", run: () => this.splitWith(info!.plane!, s.body) }, + { id: "revolve", label: "Revolve", icon: "revolve", ...needFlat, run: () => src && app.setTool(new RevolveOp(app, src)) }, + { id: "sweep", label: "Sweep", icon: "sweep", ...needFlat, run: () => src && app.setTool(new SweepOp(app, src)) }, + { id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON }, + { + id: "more", + label: "More", + icon: "more", + children: [ + { id: "replace", label: "Replace Face", icon: "replaceFace", ...needFlat, run: () => ref && app.setTool(new ReplaceFaceOp(app, ref)) }, + { id: "offsetEdge", label: "Offset Edge", icon: "offset", ...needFlat, run: () => this.projectFace("offset") }, + { id: "projs", label: "Project as Sketch", icon: "project", ...needFlat, run: () => this.projectFace("select") }, + { id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON }, + { id: "text", label: "Text", icon: "text", ...needFlat, run: () => this.sketchOnFace("text") }, + { id: "moveBody", label: "Move/Rotate Body", icon: "move", run: () => app.setTool(new TransformOp(app, "move", bodies)) }, + { id: "deleteBody", label: "Delete Body", icon: "trash", run: () => this.deleteBodies(bodies) }, + ], + }, + // The neighbours extend to close the gap (fillets, chamfers, holes). + { id: "delete", label: "Delete Face", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { faces: faceRefs.filter((f) => f.body === s.body) }) }, + ]; + } + + private edgeActions(): ToolItem[] { + const app = this.app; + const sel = app.selection; + const s = sel[0] as Extract; + const info = app.view.body(s.body)?.edges[s.edge]; + const bodies = bodiesOf(sel); + const straight = info?.type === "LINE"; + const ref = this.edgeRefs()[0]; + // With variables defined, Fillet/Chamfer open a list: a free size, or one of the variables. + const vars = app.store.doc.variables ?? []; + const sized = (kind: "fillet" | "chamfer"): Partial => + vars.length + ? { + sub: "Pick a size", + children: [ + { id: `${kind}-free`, label: "Drag / type", icon: kind, run: () => app.setTool(new EdgeOp(app, kind, this.edgeRefs())) }, + ...vars.map((v) => ({ id: `${kind}-var-${v.name}`, label: `${v.name} = ${v.expr}`, icon: "variable" as const, run: () => app.setTool(new EdgeOp(app, kind, this.edgeRefs(), undefined, v.name)) })), + ], + } + : {}; + return [ + { id: "fillet", label: "Fillet", icon: "fillet", shortcut: "F", active: true, run: () => app.setTool(new EdgeOp(app, "fillet", this.edgeRefs())), ...sized("fillet") }, + { id: "chamfer", label: "Chamfer", icon: "chamfer", shortcut: "C", run: () => app.setTool(new EdgeOp(app, "chamfer", this.edgeRefs())), ...sized("chamfer") }, + // Moves just this edge: the faces on it tilt to follow. + { id: "move", label: "Move/Rotate Edge", icon: "move", shortcut: "M", disabled: !straight || sel.length !== 1, why: "Needs one straight edge", run: () => ref && app.setTool(new MoveFaceOp(app, { edge: ref })) }, + { id: "moveBody", label: "Move/Rotate Body", icon: "move", run: () => app.setTool(new TransformOp(app, "move", bodies)) }, + { id: "axis", label: "Axis – Along Edge", icon: "axis", disabled: !straight, why: "Needs a straight edge", run: () => info && app.setTool(new AxisOp(app, info.start, info.dir)) }, + { id: "planePerp", label: "Plane – Perp. to Edge", icon: "plane", run: () => info && app.setTool(new PlaneOp(app, { origin: info.mid, normal: info.dir, xDir: perpTo(info.dir) }, undefined)) }, + { id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) }, + { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) }, + { id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON }, + { id: "delete", label: "Delete Edge", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { edges: this.edgeRefs().filter((e) => e.body === s.body) }) }, + ]; + } + + private bodyActions(): ToolItem[] { + const app = this.app; + const bodies = bodiesOf(app.selection); + const multi = bodies.length >= 2; + const boolean = (op: "union" | "subtract" | "intersect") => () => { + app.store.add({ ...app.store.newIdentity("boolean", cap(op)), type: "boolean", op, target: bodies[0], tools: bodies.slice(1) }); + app.setSelection([{ kind: "body", body: bodies[0] }]); + }; + return [ + { id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", active: true, run: () => app.setTool(new TransformOp(app, "move", bodies)) }, + { + id: "scale", + label: "Scale", + icon: "scale", + // Starts the kind used last. + sub: lastScale.xyz ? "X / Y / Z" : "Uniform", + run: () => app.setTool(new ScaleOp(app, lastScale.xyz, bodies)), + children: [ + { id: "scaleUniform", label: "Uniform", icon: "scale", active: !lastScale.xyz, run: () => ((lastScale.xyz = false), app.setTool(new ScaleOp(app, false, bodies))) }, + { id: "scaleXYZ", label: "X / Y / Z", icon: "scale", sub: "freeform bodies", active: lastScale.xyz, run: () => ((lastScale.xyz = true), app.setTool(new ScaleOp(app, true, bodies))) }, + ], + }, + { id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) }, + { id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: () => app.setTool(new TransformOp(app, "linear", bodies)) }, + { id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: () => app.setTool(new TransformOp(app, "circular", bodies)) }, + { id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) }, + { id: "mirror", label: "Mirror", icon: "mirror", run: () => app.setTool(new TransformOp(app, "mirror", bodies)) }, + { id: "union", label: "Union", icon: "union", shortcut: "U", disabled: !multi, why: "Select 2+ bodies", run: boolean("union") }, + { id: "subtract", label: "Subtract", icon: "subtract", disabled: !multi, why: "Select 2+ bodies (first is kept)", run: boolean("subtract") }, + { id: "intersect", label: "Intersect", icon: "intersect", disabled: !multi, why: "Select 2+ bodies", run: boolean("intersect") }, + { id: "split", label: "Split Body", icon: "split", run: () => app.setTool(new SplitOp(app, bodies[0])) }, + { id: "shell", label: "Shell", icon: "shell", run: () => app.setTool(new ShellOp(app, bodies[0], [])) }, + { + id: "color", + label: "Color", + icon: "color", + sub: BODY_COLORS.find((c) => c.hex === (app.store.doc.colors ?? {})[bodies[0]])?.name ?? "Grey", + children: BODY_COLORS.map((c, i) => ({ + id: `color-${i}`, + label: c.name, + icon: "color", + swatch: c.hex, + active: ((app.store.doc.colors ?? {})[bodies[0]] ?? BODY_COLORS[0].hex) === c.hex, + run: () => + app.store.commit((d) => { + const colors = { ...(d.colors ?? {}) }; + for (const b of bodies) if (i === 0) delete colors[b]; + else colors[b] = c.hex; + d.colors = colors; + }), + })), + }, + { id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => this.deleteBodies(bodies) }, + ]; + } + + private planeActions(): ToolItem[] { + const app = this.app; + const s = app.selection[0] as Extract; + const plane = app.view.planeOf(s.id); + const isFeature = !!app.store.find(s.id); + return [ + { id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", run: () => plane && (app.setSelection([]), app.setTool(new SketchTool(app, { plane }))) }, + { id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) }, + { id: "split", label: "Split Body", icon: "split", disabled: !app.view.bodyList.length, why: "Needs a body", run: () => plane && this.splitWith(plane) }, + { id: "delete", label: "Delete", icon: "trash", shortcut: "Del", disabled: !isFeature, why: "Origin planes can't be deleted", run: () => (app.store.remove(s.id), app.setSelection([])) }, + ]; + } + + private axisActions(): ToolItem[] { + const app = this.app; + const s = app.selection[0] as Extract; + return [{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => (app.store.remove(s.id), app.setSelection([])) }]; + } + + // ------------------------------------------------------------- helpers + + private showHandle(frame: { base: Vec3; normal: Vec3 }, shape: "arrow" | "dot", action: () => Tool): void { + this.handle = new Handle(this.app.view, shape); + this.handle.set(frame.base, shape === "arrow" ? frame.normal : undefined); + this.handleAction = action; + } + + private clearHandle(): void { + this.handle?.dispose(); + this.handle = null; + this.handleAction = null; + this.gimbal?.dispose(); + this.gimbal = null; + this.copyToggle?.dispose(); + this.copyToggle = null; + clearTimeout(this.dimTimer); + this.dim?.dispose(); + this.dim = null; + } + + /** + * A selected flat face shows its thickness to the opposite face (Total); + * typing a value or switching to Offset starts Offset Face right away. + */ + private showFaceDimension(s: Extract, src: ExtrudeSource): void { + const f = this.app.view.body(s.body)!.faces[s.face]; + const opp = oppositeFace(this.app, s.body, s.face); + if (!opp) return; + const start = (measure: "total" | "offset", distance: number, typed?: string) => + this.app.setTool(new ExtrudeOp(this.app, src, undefined, "auto", { measure, distance, typed })); + // Shown a moment later, beside the face — never under the pointer while you double-click for the body. + this.dimTimer = window.setTimeout(() => { + this.dim = new DimWidget(this.app.view, { + value: opp.distance, + // Past the tip of the extrude arrow, which starts at the face. + boxAt: "beyond", + boxGap: 96, + dir: f.normal, + modes: [{ id: "total", label: "Total" }, { id: "offset", label: "Offset" }], + mode: "total", + onMode: (m) => start(m as "total" | "offset", 0), + onInput: (v) => start("total", v - opp.distance, this.dim?.text), + onPin: () => this.app.addPin({ text: fmtLen(opp.distance), a: opp.point, b: f.center, at: scale(add(opp.point, f.center), 0.5) }), + }); + this.dim.set(opp.point, f.center); + }, 400); + } + + private dimTimer = 0; + + /** + * Two faces: their distance as a dimension with a pin. Parallel flat faces: + * the gap between them; otherwise centre to centre. + */ + private showFacesDistance(a: Extract, b: Extract): void { + const fa = this.app.view.body(a.body)?.faces[a.face]; + const fb = this.app.view.body(b.body)?.faces[b.face]; + if (!fa || !fb) return; + const n = fa.normal; + const parallel = !!fa.plane && !!fb.plane && Math.abs(dot(n, fb.normal)) > 0.9999; + const p0 = fa.center; + const p1 = parallel ? add(p0, scale(n, dot(sub(fb.center, p0), n))) : fb.center; + const d = len(sub(p1, p0)); + this.dim = new DimWidget(this.app.view, { + value: d, + boxAt: "side", + onPin: () => this.app.addPin({ text: fmtLen(d), a: p0, b: p1, at: scale(add(p0, p1), 0.5) }), + }); + this.dim.set(p0, p1); + this.app.ui.setHint(`${parallel ? "Distance between the faces" : "Centre to centre"}: ${fmtLen(d)}`); + } + + private edgeRefs(): EdgeRef[] { + return this.app.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this.app, s)!].filter(Boolean) : [])); + } + + /** Fillet/chamfer every edge lying on the selected flat faces. */ + private edgesOfFaces(kind: "fillet" | "chamfer"): void { + const refs: EdgeRef[] = []; + for (const s of this.app.selection) { + if (s.kind !== "face") continue; + const b = this.app.view.body(s.body); + const f = b?.faces[s.face]; + if (!b || !f?.plane) continue; + b.edges.forEach((e, i) => { + const on = [e.start, e.end, e.mid].every((p) => Math.abs((p[0] - f.center[0]) * f.normal[0] + (p[1] - f.center[1]) * f.normal[1] + (p[2] - f.center[2]) * f.normal[2]) < 1e-5); + if (on) refs.push(edgeRefOf(this.app, { body: s.body, edge: i })!); + }); + } + if (!refs.length) return this.app.ui.toast("Select flat faces, or tap the edges directly"); + this.app.setTool(new EdgeOp(this.app, kind, refs)); + } + + private sketchOnFace(kind?: string): void { + const s = this.app.selection[0] as Extract; + const info = this.app.view.body(s.body)?.faces[s.face]; + if (!info?.plane) return; + const ref = faceRefOf(this.app, s)!; + this.app.setSelection([]); + const tool = new SketchTool(this.app, { plane: info.plane, attachedTo: ref }); + this.app.setTool(tool); + if (kind) tool.setKind(kind as SketchKind); + } + + /** Project the face outline into a new sketch on that face. */ + private projectFace(then: string): void { + const s = this.app.selection[0] as Extract; + const b = this.app.view.body(s.body); + const f = b?.faces[s.face]; + if (!b || !f?.plane) return; + const plane = f.plane; + const entities = b.edges.flatMap((e, i) => { + const on = [e.start, e.end, e.mid].every((p) => Math.abs((p[0] - f.center[0]) * f.normal[0] + (p[1] - f.center[1]) * f.normal[1] + (p[2] - f.center[2]) * f.normal[2]) < 1e-5); + if (!on) return []; + const g = b.edgeGroups.find((x) => x.edge === i)!; + const pts: Vec3[] = []; + for (let k = g.start; k < g.start + g.count; k++) if ((k - g.start) % 2 === 0 || k === g.start + g.count - 1) pts.push([b.edgePositions[k * 3], b.edgePositions[k * 3 + 1], b.edgePositions[k * 3 + 2]]); + const ent = projectPolyline(pts, plane, e.type); + return ent ? [ent] : []; + }); + const sk: SketchFeature = { ...this.app.store.newIdentity("sketch"), type: "sketch", plane, attachedTo: faceRefOf(this.app, s)!, entities }; + this.app.store.add(sk); + this.openSketch(sk.id, then); + } + + private openSketch(sketchId: string, kind: string): void { + // Preselect the curves bounding the selected regions for sketch-level edits. + const sk = this.app.store.find(sketchId); + const regions = this.app.selection.filter((s): s is Extract => s.kind === "profile" && s.sketch === sketchId).map((s) => s.region); + const ids = new Set(); + if (sk) { + const arr = arrangement(this.app.sketchCurves(sketchId)); + for (const ri of regions) { + const r = arr.regions[ri]; + for (const loop of [r?.outer, ...(r?.holes ?? [])]) + for (const ref of loop?.pieces ?? []) { + const src = arr.prims[arr.pieces[ref.piece].prim].src; + if (!src.startsWith("bnd-")) ids.add(src); + } + } + } + this.app.setSelection([]); + const tool = new SketchTool(this.app, { sketchId }); + this.app.setTool(tool); + tool.setKind(kind as SketchKind); + if (ids.size && kind !== "line" && kind !== "text") tool.preselect(ids); + } + + private splitWith(plane: PlaneDef, exceptBody?: string): void { + const body = this.app.view.bodyList.find((b) => b.id !== exceptBody)?.id; + if (body) this.app.setTool(new SplitOp(this.app, body, undefined, plane)); + } + + private deleteProfiles(): void { + const sel = this.app.selection.filter((s): s is Extract => s.kind === "profile"); + const sk = sel[0] && this.app.store.find(sel[0].sketch); + if (!sk) return; + const arr = arrangement(this.app.sketchCurves(sk.id)); + // Remove curves that only bound the selected regions (face outline curves aren't the sketch's). + const used = new Map>(); + arr.regions.forEach((r) => { + for (const loop of [r.outer, ...r.holes]) for (const ref of loop.pieces) { + const src = arr.prims[arr.pieces[ref.piece].prim].src; + used.set(src, (used.get(src) ?? new Set()).add(r.index)); + } + }); + const chosen = new Set(sel.map((s) => s.region)); + const doomed = [...used].filter(([, rs]) => [...rs].every((r) => chosen.has(r))).map(([id]) => id); + this.app.store.update(sk.id, { entities: sk.entities.filter((e) => !doomed.includes(e.id)) }); + this.app.setSelection([]); + } + + private lastTap: ToolPointer | null = null; + + private editFreeform(ff: FreeformFeature): void { + const at = this.lastTap; + const tool = new FreeformTool(this.app, { feature: ff }); + this.app.setTool(tool); + if (at) tool.selectAt(at); + } + + /** Delete faces/edges/vertices of one body; tells the user when it can't heal. */ + private deleteGeom(body: string, what: { faces?: FaceRef[]; edges?: EdgeRef[]; vertices?: Vec3[] }): void { + // A freeform body: the cage loses the faces there, and stays open for a thickness. + const ff = this.app.store.find(body); + if (ff?.type === "freeform") { + const tool = new FreeformTool(this.app, { feature: ff }); + this.app.setTool(tool); + if (what.faces?.length) tool.deleteAt(what.faces.map((f) => f.center), "face"); + else if (what.edges?.length) tool.deleteAt(what.edges.map((e) => e.mid), "edge"); + else if (what.vertices?.length) tool.deleteAt(what.vertices, "vertex"); + return; + } + const f: DeleteGeomFeature = { ...this.app.store.newIdentity("deleteGeom"), type: "deleteGeom", body, faces: what.faces ?? [], edges: what.edges ?? [], vertices: what.vertices ?? [] }; + this.app.setSelection([]); + this.app.preview([...this.app.store.features, f]).then((r) => { + const err = r?.errors.find((e) => e.featureId === f.id); + if (err) { + this.app.ui.toast(err.message); + this.app.preview([...this.app.store.features]); + } else this.app.store.add(f); + }); + } + + private deleteBodies(bodies: string[]): void { + this.app.store.add({ ...this.app.store.newIdentity("delete"), type: "delete", bodies }); + this.app.setSelection([]); + } +} + +/** Loft wants one profile per section. */ +function splitRegions(s: ExtrudeSource): ExtrudeSource[] { + return s.kind === "profile" ? s.regions.map((r) => ({ ...s, regions: [r] })) : [s]; +} + +/** Faces Offset Face can push: flat ones and round (cylindrical) ones. */ +function offsettable(type: string | undefined): boolean { + return type === "PLANE" || type === "CYLINDRE"; +} + +function flatten(items: ToolItem[]): ToolItem[] { + return items.flatMap((i) => [i, ...flatten(i.children ?? [])]); +} + +function perpTo(d: Vec3): Vec3 { + const a: Vec3 = Math.abs(d[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0]; + const x: Vec3 = [a[1] * d[2] - a[2] * d[1], a[2] * d[0] - a[0] * d[2], a[0] * d[1] - a[1] * d[0]]; + const l = Math.hypot(...x) || 1; + return [x[0] / l, x[1] / l, x[2] / l]; +} + +function label(s: Sel, n: number): string { + const base = { face: "face", edge: "edge", vertex: "vertex", body: "body", profile: "profile", curve: "curve", point: "point", image: "image", plane: "plane", axis: "axis" }[s.kind]; + if (base === "vertex") return n === 1 ? "vertex" : "vertices"; + return n === 1 ? base : base === "body" ? "bodies" : base === "axis" ? "axes" : `${base}s`; +} + +function cap(s: string): string { + return s[0].toUpperCase() + s.slice(1); +} + +/** Which Scale was used last (the button starts that one). */ +const lastScale = { xyz: false }; diff --git a/src/tools/sketch.ts b/src/tools/sketch.ts new file mode 100644 index 0000000..bbe5d17 --- /dev/null +++ b/src/tools/sketch.ts @@ -0,0 +1,2556 @@ +import { BufferGeometry, Line, LineBasicMaterial, LineDashedMaterial, Points, PointsMaterial, Vector3 } from "three"; +import type { FaceRef, PlaneDef, PointRef, SketchConstraint, SketchEntity, SketchFeature, Vec2, Vec3 } from "../doc/types"; +import { dot, GROUND, niceStep as niceStepOf, planeY, toPlane } from "../geom"; +import { pointOf, pointsOf, refsOf, sizeOf as sizeOfFn, solve } from "../sketch/constraints"; +import { isExpression } from "../ui/ui"; +import { Gimbal, IN_PLANE, type GimbalPart } from "./gimbal"; +import { buildConstraints, buttonEnabled, CONSTRAINT_BUTTONS, ConstraintGlyphs, dimOf, distanceOf, existingConstraints, setDim } from "./sketchConstraints"; +import { settings } from "../settings"; +import { arcFrom3, entityPolylines } from "../sketch/curves"; +import { + offsetChain, + connectedChain, + angleLines, + explode, + alignLine, + endNear, + joinCollinear, + extend, + joinEnds, + splitEntity, + filletConstraints, + filletEnds, + filletCorner, + guidePoints, + mirrorXf, + offsetEntity, + projectPolyline, + rotateXf, + scaleXf, + transformEntity, + translateXf, + trim, + uid, +} from "../sketch/edit"; +import { textEntities } from "../sketch/text"; +import { DragTyping } from "./dragTyping"; +import { DimWidget } from "./annotate"; +import { PatternBox } from "./patternBox"; +import { axisDrag } from "./handles"; +import { CopyToggle, copyMode } from "./copyToggle"; +import type { PanelItem, ToolItem } from "../ui/ui"; +import { fmtLen, trim as trimNum } from "../units"; +import type { ToolPointer } from "../view/input"; +import { dotMaterial, sketchToWorld } from "../view/viewport"; +import { hitToSel, type AppContext, type Tool } from "./tool"; + +export type SketchKind = Kind; +type Kind = + | "split" + | "select" + | "line" + | "arc" + | "spline" + | "rect" + | "circle" + | "ellipse" + | "polygon" + | "text" + | "project" + | "offset" + | "fillet" + | "move" + | "scale" + | "patternLinear" + | "patternCircular" + | "rotate" + | "mirror" + | "trim" + | "extend" + | "align" + | "delete"; + +const HINTS: Record = { + select: "Tap curves to select them and edit their size. Double-tap selects a whole shape.", + line: "Tap points to draw lines. Tap the first point to close; double-tap or Enter to stop.", + arc: "Tap the arc's two endpoints, then a third point to bend it.", + spline: "Tap points the curve passes through. Tap the first point to close; double-tap or Enter to finish.", + rect: "Tap (or drag) two opposite corners.", + circle: "Tap the center, then the radius.", + ellipse: "Tap the center, the end of the long axis, then the width.", + polygon: "Tap the center, then a corner.", + text: "Tap where the text should start.", + project: "Tap body edges or curves of other sketches to project them here (double-tap: the whole sketch).", + offset: "Tap a curve to offset it.", + fillet: "Tap a corner where two lines meet.", + move: "Tap curves to select, then type the offset and Apply.", + scale: "Tap curves to select, then set the factor and Apply.", + patternLinear: "Tap curves to select, then set count and spacing.", + patternCircular: "Tap curves to select (double-tap for a whole shape), then tap the centre to turn them around.", + rotate: "Tap curves to select, set the pivot and angle.", + mirror: "Tap a shape to select it (Shift+tap: single curves), then tap the line to mirror it across — any line, even one of its own edges.", + trim: "Tap the part of a curve to cut away (between crossings). Join mode: tap a line to merge it with the line on the same axis it touches.", + align: "Tap the line to move, then the line it should line up with (the first one moves onto the second one's axis).", + extend: "Tap the half of a line or arc whose end should move, then the half of the curve it should meet. Tap the same half twice to extend to the next curve.", + delete: "Tap curves to delete them.", + split: "Tap a line or arc to cut it in two at its midpoint (or at a point you tap on it while holding Shift).", +}; + +const memory = { trim: "cut" as "cut" | "join", offsetMode: "chain" as "edge" | "chain", pattern: "patternLinear" as "patternLinear" | "patternCircular", rect: "diagonal" as "diagonal" | "center" | "3pt", spline: "fit" as "fit" | "control", sides: 6, fillet: 2, offset: 2, textSize: 10 }; + +interface Snap { + uv: Vec2; + label?: string; + guides?: [Vec2, Vec2][]; + /** Snapped onto an existing sketch point (drawing then adds a Coincident constraint). */ + ref?: PointRef; +} + +/** A point being dragged and where it started. */ +interface DragRef { + ref: PointRef; + at: Vec2; +} + +const refKey = (r: PointRef) => `${r.e}:${r.p}`; + +/** + * Sketching. First pick a plane (origin planes, a flat face, a construction + * plane or an existing sketch); the camera then looks straight at it in + * orthographic and Line is active. Every finished shape commits right away. + */ +export class SketchTool implements Tool { + readonly id = "sketch"; + private phase: "plane" | "draw"; + private kind: Kind = "line"; + private sketchId: string | null; + private plane: PlaneDef | null; + private attachedTo?: FaceRef; + private pts: Vec2[] = []; + private cursor: Snap | null = null; + private dragging = false; + private locks: Record = {}; + private selected = new Set(); + private construction = false; + private edit: { + pivot?: Vec2; + mirrorLine?: [Vec2, Vec2]; + picking?: "pivot" | "mirror"; + offsetOf?: string; + /** Extend: the first curve half picked (its nearer end will meet the second pick). */ + extendFrom?: { id: string; at: Vec2 }; + /** Align: the line that will move. */ + alignFrom?: string; + /** Fillet: first line half picked (two-tap fillet, like Extend). */ + filletFrom?: { id: string; at: Vec2 }; + dx: number; + dy: number; + /** Move/Rotate's rotation, Rotate Around Axis's angle, Pattern's total angle (degrees). */ + moveRot: number; + angle: number; + patAngle: number; + factor: number; + count: number; + copy: boolean; + /** Mirror keeps the original by default (its own switch, not Move's Copy). */ + mirrorCopy: boolean; + } = { dx: 10, dy: 0, moveRot: 0, angle: 90, patAngle: 360, factor: 2, count: 3, copy: false, mirrorCopy: true }; + private text = "Text"; + private overlays: (Line | Points)[] = []; + private prevOrtho = false; + /** Selected sketch points (curves are in `selected`). */ + private selPts: PointRef[] = []; + private gimbal: Gimbal | null = null; + private copyToggle: CopyToggle | null = null; + private glyphs: ConstraintGlyphs | null = null; + private bar: HTMLElement | null = null; + private selConstraint: string | null = null; + /** Live edit of geometry: dragging points/curves, or the sketch gimbal. */ + private sdrag: + | { kind: "points"; from: Vec2; refs: DragRef[] } + | { kind: "gimbal"; part: GimbalPart; from: ToolPointer; refs: DragRef[]; center: Vec2; last: { d: Vec2; ang: number } } + | { kind: "pivot"; line: string } + | null = null; + /** + * One line selected: where its rotation pivot sits along it (0 = start, + * 0.5 = middle, 1 = end). Drag the gimbal's centre to move it. + */ + private pivotT: { line: string; t: number } | null = null; + /** Where the current line chain started (for Coincident constraints). */ + private startRef: PointRef | null = null; + + private get constraints(): SketchConstraint[] { + return this.sketch?.constraints ?? []; + } + + constructor( + private app: AppContext, + opts: { sketchId?: string; plane?: PlaneDef; attachedTo?: FaceRef } = {}, + ) { + this.sketchId = opts.sketchId ?? null; + this.plane = opts.sketchId ? (app.sketchPlane(opts.sketchId) ?? null) : (opts.plane ?? null); + this.attachedTo = opts.attachedTo; + this.phase = this.plane ? "draw" : "plane"; + if (opts.sketchId) this.kind = "select"; + } + + get activeSketch(): string | undefined { + return this.sketchId ?? undefined; + } + get editingId(): string | undefined { + return this.sketchId ?? undefined; + } + + private get sketch(): SketchFeature | undefined { + return this.sketchId ? this.app.store.find(this.sketchId) : undefined; + } + private get entities(): SketchEntity[] { + return this.sketch?.entities ?? []; + } + /** Outline of the face this sketch sits on (snaps, trims against; not editable). */ + private get boundary(): SketchEntity[] { + return this.sketchId ? this.app.sketchCurves(this.sketchId).filter((e) => e.id.startsWith("bnd-")) : []; + } + private withoutBoundary(es: SketchEntity[]): SketchEntity[] { + return es.filter((e) => !e.id.startsWith("bnd-")); + } + + // ------------------------------------------------------------ lifecycle + + enter(): void { + this.prevOrtho = this.app.view.cam.ortho; + // Already looking straight at the model along an axis (Top, Front, Right, …): + // sketch on that origin plane, facing the camera, without asking. + if (this.phase === "plane") { + const cam = this.app.view.cam; + const d = cam.viewDir().toArray() as Vec3; + const k = d.findIndex((x) => Math.abs(x) > 0.9999); + if (k >= 0) { + const normal: Vec3 = [0, 0, 0]; + normal[k] = -Math.sign(d[k]); + const right = new Vector3().setFromMatrixColumn(cam.camera.matrixWorld, 0).toArray() as Vec3; + const r = right.findIndex((x, i) => i !== k && Math.abs(x) > 0.9); + const xDir: Vec3 = [0, 0, 0]; + if (r >= 0) xDir[r] = Math.sign(right[r]); + else xDir[(k + 1) % 3] = 1; + this.plane = { origin: [0, 0, 0], normal, xDir }; + this.phase = "draw"; + } + } + if (this.phase === "plane") { + this.app.view.setOriginPlanesVisible(true); + this.app.ui.setHint("Select a plane or a flat face to sketch on."); + this.updateMenu(); + } else this.beginDrawing(); + } + + exit(): void { + // A fillet being sized is kept (before the constraint UI goes away). + this.finishFillet(); + this.clearOverlays(); + this.gimbal?.dispose(); + this.gimbal = null; + this.patGimbal?.dispose(); + this.patGimbal = null; + this.patBox?.dispose(); + this.patBox = null; + this.copyToggle?.dispose(); + this.copyToggle = null; + this.glyphs?.dispose(); + this.glyphs = null; + this.bar?.remove(); + this.bar = null; + window.removeEventListener("resize", this.placeBar); + this.hideLineDim(); + this.clearPreviewJoin(); + this.distDim?.dispose(); + this.distDim = null; + settings.offChange(this.onSettings); + this.listening = false; + document.body.classList.remove("sketching"); + this.app.view.setOriginPlanesVisible(false); + this.app.view.grid.setPlane(GROUND); + this.app.view.cam.setOrtho(this.prevOrtho); + this.app.ui.showPanel(null); + this.app.ui.setLabel(0, 0, null); + this.app.ui.setHint(null); + this.app.setSelection([]); + } + + refresh(): void { + if (this.sketchId) this.plane = this.app.sketchPlane(this.sketchId) ?? this.plane; + for (const id of [...this.selected]) if (!this.entities.some((e) => e.id === id)) this.selected.delete(id); + this.selPts = this.selPts.filter((r) => this.entities.some((e) => e.id === r.e)); + if (this.selConstraint && !this.constraints.some((c) => c.id === this.selConstraint)) this.selConstraint = null; + this.showSelection(); + this.refreshConstraintUI(); + } + + private listening = false; + private onSettings = () => this.refreshConstraintUI(); + + /** + * The constraint column sits next to the right-hand bar with the same gap the + * tool column keeps from Items, its top level with the Constraints button. + */ + private placeBar = () => { + const bar = this.bar; + if (!bar) return; + const col = document.getElementById("right-col")!.getBoundingClientRect(); + const btn = document.querySelector(".right-btn.sketch-only")?.getBoundingClientRect(); + const GAP = 8; + // An open popover (snapping, units…) sits by the column too: go left of it. + const pop = document.getElementById("popover")!; + const left = pop.hidden ? col.left : Math.min(col.left, pop.getBoundingClientRect().left); + bar.style.right = `${window.innerWidth - left + GAP}px`; + const top = btn ? btn.top : col.top; + // Keep it on screen when the window is short. + bar.style.top = `${Math.max(8, Math.min(top, window.innerHeight - bar.offsetHeight - 8))}px`; + }; + + /** Constraint column (enabled per selection) and badges on the geometry. */ + private refreshConstraintUI(): void { + if (this.phase !== "draw" || !this.plane) return; + this.glyphs ??= new ConstraintGlyphs(this.app.view, (id) => this.selectConstraint(id)); + this.glyphs.selected = this.selConstraint; + this.glyphs.set(this.plane, this.entities, this.constraints); + this.glyphs.setVisible(settings.value.showConstraintGlyphs); + document.body.classList.add("sketching"); + if (!this.listening) { + this.listening = true; + settings.onChange(this.onSettings); + } + // The column is toggled from the right-hand bar (Constraints button). + if (!settings.value.showConstraints) { + this.bar?.remove(); + this.bar = null; + return; + } + if (!this.bar) { + this.bar = document.createElement("div"); + this.bar.id = "constraint-bar"; + this.bar.addEventListener("pointerdown", (e) => e.stopPropagation()); + document.body.append(this.bar); + window.addEventListener("resize", this.placeBar); + } + const curves = this.pickedCurves(); + this.bar.innerHTML = ""; + const auto = document.createElement("button"); + auto.className = `cbar-toggle${settings.value.autoConstrain ? " on" : ""}`; + auto.innerHTML = `Auto constrain`; + auto.title = "Add horizontal/vertical/coincident constraints automatically while drawing"; + auto.addEventListener("click", () => settings.set("autoConstrain", !settings.value.autoConstrain)); + const glyphs = document.createElement("button"); + glyphs.className = `cbar-toggle${settings.value.showConstraintGlyphs ? " on" : ""}`; + glyphs.innerHTML = `Show constraints`; + glyphs.title = "Show or hide the constraint badges and dimensions on the sketch"; + glyphs.addEventListener("click", () => settings.set("showConstraintGlyphs", !settings.value.showConstraintGlyphs)); + this.bar.append(auto, glyphs, document.createElement("hr")); + for (const b of CONSTRAINT_BUTTONS) { + const btn = document.createElement("button"); + // Already on the selection: shown as on; tapping removes it (Lock becomes Unlock). + const have = this.selected.size || this.selPts.length ? existingConstraints(b.type, this.constraints, this.selPts, curves) : []; + const label = have.length && b.type === "fix" ? "Unlock" : b.label; + btn.innerHTML = `${label} ⇧${b.key}${have.length && b.type === "fix" ? "🔓" : b.glyph}`; + btn.classList.toggle("on", have.length > 0); + btn.disabled = !have.length && !buttonEnabled(b.type, this.selPts, curves); + btn.title = have.length ? `Remove ${b.label.toLowerCase()} (${have.length})` : btn.disabled ? `${b.label}: select the right points/curves first` : b.label; + btn.addEventListener("click", () => (have.length ? this.removeConstraints(have) : this.addConstraint(b.type))); + this.bar.append(btn); + } + this.placeBar(); + } + + /** Angle (degrees, 0–180) of line 2 against line 1, measured as setLinesAngle sets it. */ + private angleBetween(id1: string, id2: string): number { + const r = angleLines(this.entities, id1, id2, 0); + const l1 = this.entities.find((e) => e.id === id1); + const l2 = this.entities.find((e) => e.id === id2); + if (!r || l1?.kind !== "line" || l2?.kind !== "line") return 0; + // Orientation as angleLines would set it: away from the meeting point. + const o1 = r.swapped.includes(id1) ? [l1.a[0] - l1.b[0], l1.a[1] - l1.b[1]] : [l1.b[0] - l1.a[0], l1.b[1] - l1.a[1]]; + const o2 = r.swapped.includes(id2) ? [l2.a[0] - l2.b[0], l2.a[1] - l2.b[1]] : [l2.b[0] - l2.a[0], l2.b[1] - l2.a[1]]; + const a = Math.abs(Math.atan2(o1[0] * o2[1] - o1[1] * o2[0], o1[0] * o2[0] + o1[1] * o2[1])); + return Math.round(((a * 180) / Math.PI) * 1e4) / 1e4; + } + + /** + * Turn the second picked line to `deg` against the first, about its end + * nearest the first line, and keep it there with an angle dimension. + */ + private setLinesAngle(id1: string, id2: string, deg: number): void { + const r = angleLines(this.entities, id1, id2, deg); + if (!r) return; + const swap = (p: string) => (p === "a" ? "b" : p === "b" ? "a" : p); + const remap = (c: SketchConstraint): SketchConstraint => (c.pts ? { ...c, pts: c.pts.map((q) => (r.swapped.includes(q.e) ? { ...q, p: swap(q.p) } : q)) } : c); + const same = (c: SketchConstraint) => c.type === "dim" && c.prop === "angle" && c.curves?.length === 2 && c.curves.includes(id1) && c.curves.includes(id2); + const cs = [...this.constraints.filter((c) => !same(c)).map(remap), { id: uid(), type: "dim" as const, curves: [id1, id2], prop: "angle", value: deg }]; + const solved = solve(r.entities, cs, { fixed: new Set([id1]) }); + this.commit(solved.ok ? solved.entities : r.entities, cs); + } + + private removeConstraints(list: SketchConstraint[]): void { + const ids = new Set(list.map((c) => c.id)); + this.commit(this.entities, this.constraints.filter((c) => !ids.has(c.id))); + this.refreshConstraintUI(); + this.updatePanel(); + } + + /** When each curve id / point key was picked (the earliest is the reference). */ + private pickSeq = new Map(); + private seq = 0; + + private firstPicked(): string | undefined { + const cands = [...[...this.selected].map((id) => ({ e: id, k: id })), ...this.selPts.map((r) => ({ e: r.e, k: refKey(r) }))]; + cands.sort((a, b) => (this.pickSeq.get(a.k) ?? 0) - (this.pickSeq.get(b.k) ?? 0)); + return cands[0]?.e; + } + + private distDim: DimWidget | null = null; + + /** + * Two points, or a point and a line, selected: show their distance in a box. + * Type a value + Enter (or just Enter) to make it a Distance constraint. + */ + private refreshDistanceDim(): void { + this.distDim?.dispose(); + this.distDim = null; + if (this.kind !== "select" || !this.plane) return; + const curves = this.pickedCurves(); + const pts = this.selPts; + const v = distanceOf(pts, curves, this.entities); + if (v === null) return; + const P = (r: PointRef) => pointOf(this.entities.find((x) => x.id === r.e)!, r.p)!; + const a = P(pts[0]); + let b: Vec2; + if (pts.length === 2) b = P(pts[1]); + else { + const l = curves[0] as Extract; + const d: Vec2 = [l.b[0] - l.a[0], l.b[1] - l.a[1]]; + const t = ((a[0] - l.a[0]) * d[0] + (a[1] - l.a[1]) * d[1]) / (d[0] * d[0] + d[1] * d[1] || 1); + b = [l.a[0] + d[0] * t, l.a[1] + d[1] * t]; + } + const existing = existingConstraints("distance", this.constraints, pts, curves)[0]; + const w = (q: Vec2) => sketchToWorld(this.plane!, q, 0.02).toArray() as Vec3; + let typed: number | null = null; + this.distDim = new DimWidget(this.app.view, { + value: existing?.value ?? v, + boxAt: "side", + onInput: (x) => (typed = x > 0 ? x : null), + onCommit: () => this.setDistance(typed ?? existing?.value ?? v), + }); + this.distDim.set(w(a), w(b)); + } + + /** Upsert the Distance constraint of the selection; the first-picked side stays put. */ + private setDistance(value: number): void { + const curves = this.pickedCurves(); + const pts = [...this.selPts]; + const old = new Set(existingConstraints("distance", this.constraints, pts, curves).map((c) => c.id)); + const c: SketchConstraint = { id: uid(), type: "distance", pts, ...(curves.length ? { curves: curves.map((e) => e.id) } : {}), value }; + const all = [...this.constraints.filter((x) => !old.has(x.id)), c]; + const first = this.firstPicked(); + const solved = solve(this.entities, all, first ? { fixed: new Set([first]) } : {}); + this.commit(solved.ok ? solved.entities : this.entities, all); + if (this.app.store.problems.length) this.app.ui.toast(this.app.store.problems[0], "error"); + this.refreshDistanceDim(); + } + + /** Selected curves in the order they were picked. */ + private pickedCurves(): SketchEntity[] { + return [...this.selected].flatMap((id) => this.entities.filter((e) => e.id === id)); + } + + private addConstraint(type: (typeof CONSTRAINT_BUTTONS)[number]["type"]): void { + const curves = this.pickedCurves(); + let cs = buildConstraints(type, this.selPts, curves); + // Lock holds points where they are now. + if (type === "fix") cs = cs.map((c) => (c.type === "fix" ? { ...c, at: pointOf(this.entities.find((e) => e.id === c.pts![0].e)!, c.pts![0].p) ?? [0, 0] } : c)); + if (!cs.length) return this.app.ui.toast("That constraint doesn't fit the selection"); + // The first thing picked is the reference: it stays, the others adapt to it. + const first = this.firstPicked(); + // Equal: a size dimension on the curves picked after the first would fight it — drop those. + const others = new Set(curves.slice(1).map((e) => e.id)); + const kept = type === "equal" ? this.constraints.filter((c) => !(c.type === "dim" && c.curves?.length === 1 && others.has(c.curves[0]) && ["length", "radius", "diameter"].includes(c.prop ?? ""))) : this.constraints; + const all = [...kept, ...cs]; + const solved = first && type !== "fix" ? solve(this.entities, all, { fixed: new Set([first]) }) : null; + this.commit(solved?.ok ? solved.entities : this.entities, all); + if (this.app.store.problems.length) this.app.ui.toast(this.app.store.problems[0], "error"); + this.clearSelection(); + } + + private selectConstraint(id: string): void { + this.selConstraint = id; + this.selected.clear(); + this.selPts = []; + this.showSelection(); + this.refreshConstraintUI(); + const c = this.constraints.find((x) => x.id === id); + if (!c) return; + const del = { id: "delete", label: "Delete", icon: "trash" as const, run: () => this.deleteConstraint(id) }; + if (c.type === "dim" || c.type === "distance") { + const kind = c.prop === "angle" ? "angle" : "length"; + this.app.ui.showPanel({ + title: `${c.prop ?? "distance"} dimension`, + items: [ + { + type: "number", + label: "Value", + value: c.value ?? 0, + kind, + expr: c.expr, + onExpr: (expr) => (this.pendingExpr = expr), + onInput: (v) => this.setConstraintValue(id, v), + }, + ], + actions: [del], + onDone: () => this.deselectConstraint(), + }); + this.app.ui.focusPanel(); + } else { + this.app.ui.showPanel({ title: `${c.type} constraint`, items: [], actions: [del], onDone: () => this.deselectConstraint() }); + } + } + + private pendingExpr: string | null = null; + + private setConstraintValue(id: string, v: number): void { + const expr = this.pendingExpr; + this.pendingExpr = null; + this.commit( + this.entities, + this.constraints.map((c) => (c.id === id ? { ...c, value: v, expr: expr ?? undefined } : c)), + ); + } + + private deleteConstraint(id: string): void { + this.commit(this.entities, this.constraints.filter((c) => c.id !== id)); + this.deselectConstraint(); + } + + private deselectConstraint(): void { + this.selConstraint = null; + this.app.ui.showPanel(null); + this.updatePanel(); + this.refreshConstraintUI(); + } + + private beginDrawing(): void { + this.phase = "draw"; + this.app.view.setOriginPlanesVisible(false); + const p = this.plane!; + this.app.view.grid.setPlane(p); + this.app.view.cam.setOrtho(true); + // Look straight at the plane, centred on where the camera already looked. + const uv = toPlane(p, this.app.view.cam.target.toArray() as [number, number, number]); + this.app.view.cam.lookAlong(p.normal, p.xDir, sketchToWorld(p, uv).toArray() as [number, number, number]); + this.updateMenu(); + this.updatePanel(); + this.setHint(); + this.refreshConstraintUI(); + } + + // ---------------------------------------------------------------- menu + + private updateMenu(): void { + const app = this.app; + const exit: ToolItem = { id: "exit", label: "Exit Sketch", icon: "exit", shortcut: "Esc", run: () => app.setTool(null) }; + if (this.phase === "plane") { + app.ui.setTools([exit]); + app.ui.setBottom([]); + return; + } + const t = (kind: Kind, label: string, icon: ToolItem["icon"], shortcut?: string, extra: Partial = {}): ToolItem => ({ + id: kind, + label, + icon, + shortcut, + active: this.kind === kind, + run: () => this.setKind(kind), + ...extra, + }); + const variant = (kind: Kind, key: "rect" | "spline" | "trim", options: [T, string][]): ToolItem[] => + options.map(([v, l]) => ({ id: `${kind}-${v}`, label: l, icon: kind === "rect" ? "rect" : kind === "trim" ? "trim" : "spline", active: memory[key] === v, run: () => (((memory as unknown as Record)[key] = v), this.setKind(kind)) })); + app.ui.setTools([ + exit, + { id: "---1", label: "", icon: "line" }, + t("line", "Line", "line", "L"), + t("arc", "Arc", "arc", "A"), + t("spline", "Spline", "spline", "I", { sub: memory.spline === "fit" ? "Fit" : "Control", children: variant("spline", "spline", [["fit", "Fit points"], ["control", "Control points"]]) }), + t("rect", "Rectangle", "rect", "R", { sub: { diagonal: "Diagonal", center: "Center", "3pt": "3 Points" }[memory.rect], children: variant("rect", "rect", [["center", "Center"], ["diagonal", "Diagonal"], ["3pt", "3 Points"]]) }), + t("circle", "Circle", "circle", "C"), + t("ellipse", "Ellipse", "ellipse"), + t("polygon", "Polygon", "polygon", "G", { sub: `${memory.sides} sides` }), + t("text", "Text", "text"), + t("project", "Project", "project", "P"), + t("offset", "Offset Edge", "offset", "O"), + // Modify tools. + t("fillet", "Fillet", "sketchFillet"), + t("mirror", "Mirror", "mirror"), + t("trim", "Trim", "trim", "T", { sub: memory.trim === "cut" ? "Cut" : "Join", children: variant("trim", "trim", [["cut", "Cut"], ["join", "Join lines"]]) }), + t("align", "Align", "alignLine"), + t("extend", "Extend", "extend", "E"), + t("split", "Split", "splitLine"), + t("move", "Move/Rotate", "move", "M"), + t("scale", "Scale", "scale", "S"), + { + ...t(memory.pattern, "Pattern", memory.pattern), + id: "pattern", + active: this.kind === "patternLinear" || this.kind === "patternCircular", + sub: memory.pattern === "patternLinear" ? "Linear" : "Circular", + children: (["patternLinear", "patternCircular"] as const).map((k) => ({ id: k, label: k === "patternLinear" ? "Linear" : "Circular", icon: k, active: this.kind === k, run: () => ((memory.pattern = k), this.setKind(k)) })), + }, + t("delete", "Delete", "trash", "Del"), + t("select", "Select", "pointer", "V"), + ]); + // With curves selected the button shows (and flips) their type; otherwise the type of new curves. + const sel = this.entities.filter((e) => this.selected.has(e.id)); + const isCons = sel.length ? sel.every((e) => e.construction) : this.construction; + const mixed = sel.length > 0 && !isCons && sel.some((e) => e.construction); + app.ui.setBottom([ + { + id: "construction", + label: sel.length ? (isCons ? "Construction" : "Regular") : "Construction", + icon: "construction", + sub: sel.length ? (mixed ? "Mixed · tap to switch" : "Tap to switch") : this.construction ? "On" : "Off", + active: isCons, + run: () => this.toggleConstruction(), + }, + { id: "look", label: "Normal to Sketch", icon: "normal", run: () => this.plane && app.view.cam.lookAlong(this.plane.normal, this.plane.xDir) }, + ]); + } + + /** Preselect curves (e.g. a profile's boundary when opening Move from a profile). */ + preselect(ids: Iterable, pts: PointRef[] = []): void { + this.selected = new Set(ids); + this.selPts = [...pts]; + this.showSelection(); + this.updatePanel(); + this.refreshPreview(); + } + + setKind(kind: Kind): void { + this.kind = kind; + this.pts = []; + this.locks = {}; + this.edit.picking = kind === "mirror" ? undefined : this.edit.picking; + this.edit.offsetOf = undefined; + this.edit.extendFrom = this.edit.alignFrom = undefined; + this.edit.filletFrom = undefined; + // A circular pattern always asks for its centre. + if (kind === "patternCircular") this.edit.pivot = undefined; + this.finishFillet(); + this.clearPreviewJoin(); + this.edit.mirrorLine = undefined; + // Editing tools keep the selection; drawing tools start clean. + if (!["move", "scale", "patternLinear", "patternCircular", "rotate", "mirror", "select", "delete"].includes(kind)) this.selected.clear(); + this.clearOverlays(); + this.hideLineDim(); + this.refreshDistanceDim(); + this.showSelection(); + this.updateMenu(); + this.updatePanel(); + this.setHint(); + } + + private setHint(extra?: string): void { + const hint = this.phase === "plane" ? "Select a plane or a flat face to sketch on." : extra ?? HINTS[this.kind]; + this.app.ui.setHint(hint); + } + + private toggleConstruction(): void { + if (this.selected.size) { + const ids = this.selected; + const anyOff = this.entities.some((e) => ids.has(e.id) && !e.construction); + this.commit(this.entities.map((e) => (ids.has(e.id) ? { ...e, construction: anyOff } : e))); + } else { + this.construction = !this.construction; + } + this.updateMenu(); + } + + // ---------------------------------------------------------------- panel + + private updatePanel(): void { + const ui = this.app.ui; + const items: PanelItem[] = []; + const k = this.kind; + const lock = (key: string, label: string, kind: "length" | "angle" | "int" = "length", value?: number): PanelItem => ({ + type: "number", + label, + value: this.locks[key] ?? value ?? 0, + kind, + onInput: (v) => { + this.locks[key] = v; + this.refreshPreview(); + }, + }); + const selCount = this.selected.size; + const apply = (label: string, fn: () => void): PanelItem => ({ type: "button", label, icon: "check", onClick: fn }); + switch (k) { + case "line": + if (this.pts.length) items.push(lock("len", "Length")); + break; + case "rect": + if (this.pts.length === 1 && memory.rect !== "3pt") items.push(lock("w", "Width"), lock("h", "Height")); + break; + case "circle": + if (this.pts.length === 1) items.push(lock("r", "Diameter")); + break; + case "polygon": + items.push({ type: "number", label: "Sides", value: memory.sides, kind: "int", min: 3, onInput: (v) => ((memory.sides = Math.max(3, Math.min(64, v))), this.refreshPreview(), this.updateMenu()) }); + if (this.pts.length === 1) items.push(lock("r", "Radius")); + break; + case "ellipse": + if (this.pts.length === 1) items.push(lock("rx", "Length")); + if (this.pts.length === 2) items.push(lock("ry", "Width")); + break; + case "text": + if (this.pts.length === 1) { + ui.showPanel({ + title: "Text", + items: [{ type: "number", label: "Size", value: memory.textSize, kind: "length", min: 0.001, onInput: (v) => (memory.textSize = v) }], + onDone: () => this.commitText(), + onCancel: () => this.setKind("text"), + }); + this.addTextInput(); + return; + } + break; + case "fillet": + items.push({ type: "number", label: "Radius", value: memory.fillet, kind: "length", min: 0.0001, onInput: (v) => (memory.fillet = v) }); + break; + case "offset": + // Edge: just the tapped curve. Chain: the whole connected outline, kept closed. + items.push({ type: "choice", options: [{ id: "edge", label: "Edge" }, { id: "chain", label: "Chain" }], value: memory.offsetMode, onChange: (m) => ((memory.offsetMode = m as "edge" | "chain"), this.updatePanel(), this.refreshPreview()) }); + if (this.edit.offsetOf) { + items.push({ type: "number", label: "Distance", value: memory.offset, kind: "length", onInput: (v) => ((memory.offset = v), this.refreshPreview()) }); + items.push({ type: "button", label: "Flip", icon: "flip", onClick: () => ((memory.offset = -memory.offset), this.updatePanel(), this.refreshPreview()) }); + items.push(apply("Apply", () => this.applyOffset())); + } + break; + case "move": + items.push( + { type: "number", label: "Δ X", value: this.edit.dx, kind: "length", onInput: (v) => ((this.edit.dx = v), this.refreshPreview()) }, + { type: "number", label: "Δ Y", value: this.edit.dy, kind: "length", onInput: (v) => ((this.edit.dy = v), this.refreshPreview()) }, + { type: "number", label: "Rotate", value: this.edit.moveRot, kind: "angle", onInput: (v) => ((this.edit.moveRot = v), this.refreshPreview()) }, + { type: "toggle", label: "Copy", value: this.edit.copy, onChange: (v) => ((this.edit.copy = v), this.updatePanel()) }, + apply(`Apply (${selCount})`, () => this.applyTransform()), + ); + break; + case "scale": + items.push({ type: "number", label: "Factor", value: this.edit.factor, kind: "number", min: 0.0001, onInput: (v) => ((this.edit.factor = v), this.refreshPreview()) }, { type: "toggle", label: "Copy", value: this.edit.copy, onChange: (v) => ((this.edit.copy = v), this.updatePanel()) }, apply(`Apply (${selCount})`, () => this.applyTransform())); + break; + case "patternLinear": { + // Count, spacing and the direction it runs (the arrows show it; drag one to set both). + const spacing = Math.hypot(this.edit.dx, this.edit.dy); + const dirDeg = spacing > 1e-12 ? (Math.atan2(this.edit.dy, this.edit.dx) * 180) / Math.PI : 0; + const setPolar = (sp: number, deg: number) => { + const a = (deg * Math.PI) / 180; + this.edit.dx = Math.cos(a) * sp; + this.edit.dy = Math.sin(a) * sp; + this.refreshPreview(); + }; + items.push( + { type: "number", label: "Count", value: this.edit.count, kind: "int", min: 2, onInput: (v) => ((this.edit.count = v), this.refreshPreview()) }, + { type: "number", label: "Spacing", value: spacing, kind: "length", onInput: (v) => setPolar(v, dirDeg) }, + { type: "number", label: "Direction", value: dirDeg, kind: "angle", onInput: (v) => setPolar(Math.hypot(this.edit.dx, this.edit.dy), v) }, + apply(`Apply (${selCount})`, () => this.applyTransform()), + ); + break; + } + case "patternCircular": + case "rotate": + items.push( + { type: "slot", label: "Center", value: this.edit.pivot ? `${trimNum(this.edit.pivot[0])}, ${trimNum(this.edit.pivot[1])}` : k === "patternCircular" ? "Tap the centre" : "Origin (tap to set)", active: this.edit.picking === "pivot", filled: !!this.edit.pivot, onClick: () => ((this.edit.picking = "pivot"), this.updatePanel()) }, + ...(k === "patternCircular" ? [{ type: "number", label: "Count", value: this.edit.count, kind: "int", min: 2, onInput: (v: number) => ((this.edit.count = v), this.refreshPreview()) } as PanelItem] : []), + k === "patternCircular" + ? { type: "number", label: "Angle", value: this.edit.patAngle, kind: "angle", onInput: (v) => ((this.edit.patAngle = v), this.refreshPreview()) } + : { type: "number", label: "Angle", value: this.edit.angle, kind: "angle", onInput: (v) => ((this.edit.angle = v), this.refreshPreview()) }, + ...(k === "rotate" ? [{ type: "toggle", label: "Copy", value: this.edit.copy, onChange: (v: boolean) => ((this.edit.copy = v), this.updatePanel()) } as PanelItem] : []), + apply(`Apply (${selCount})`, () => this.applyTransform()), + ); + break; + case "mirror": + items.push( + { type: "slot", label: "Mirror line", value: this.edit.mirrorLine ? "Line" : "Tap a line or axis", active: this.edit.picking === "mirror", filled: !!this.edit.mirrorLine, onClick: () => ((this.edit.picking = "mirror"), this.updatePanel()) }, + { type: "toggle", label: "Copy", value: this.edit.mirrorCopy, onChange: (v) => ((this.edit.mirrorCopy = v), this.updatePanel()) }, + apply(`Apply (${selCount})`, () => this.applyTransform()), + ); + break; + case "select": + if (selCount === 1) return this.showSizePanel(); + if (selCount > 1) { + // Two lines: the angle of the second picked against the first. + const [l1, l2] = this.pickedCurves(); + const angle: PanelItem[] = + selCount === 2 && l1?.kind === "line" && l2?.kind === "line" + ? [{ type: "number", label: "Angle", value: this.angleBetween(l1.id, l2.id), kind: "angle", onInput: (v) => this.setLinesAngle(l1.id, l2.id, v) }] + : []; + return ui.showPanel({ + title: `${selCount} curves`, + items: [ + ...angle, + { type: "button", label: "Construction", icon: "construction", onClick: () => this.toggleConstruction() }, + { type: "button", label: "Delete", icon: "trash", onClick: () => this.deleteSelected() }, + ], + }); + } + break; + } + // Every tool gets the panel: its values, and the step just done (undo is one tap away). + const lastLog = this.sketch?.log?.at(-1); + if (lastLog) items.push({ type: "slot", label: "Last step", value: `${lastLog.op}${lastLog.n > 1 ? ` ×${lastLog.n}` : ""}`, active: false, filled: true, onClick: () => {} }); + ui.showPanel(items.length ? { title: titleOf(k), items, onCancel: this.pts.length ? () => this.resetDrawing() : undefined } : null); + } + + private addTextInput(): void { + const panel = document.getElementById("panel")!; + const input = document.createElement("input"); + input.className = "text-input"; + input.value = this.text; + input.addEventListener("input", () => ((this.text = input.value), this.refreshPreview())); + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") this.commitText(); + if (e.key === "Escape") this.setKind("text"); + e.stopPropagation(); + }); + panel.querySelector(".panel-fields")?.prepend(input); + setTimeout(() => input.select(), 0); + } + + // -------------------------------------------------------------- pointer + + hover(p: ToolPointer | null): void { + if (p && this.phase === "plane") { + // Show which plane / face / sketch a tap would pick. + const hit = this.app.view.pick(p.x, p.y, { edges: false, vertices: false, planes: true, planesFirst: true, profiles: true, edgeTolPx: 0 }); + const ok = hit && (hit.kind === "plane" || hit.kind === "profile" || (hit.kind === "face" && !!this.app.view.body(hit.body)?.faces[hit.face]?.plane)); + this.app.setHover(ok ? hitToSel(hit) : null); + return; + } + if (!p || this.phase !== "draw" || this.dragging || this.sdrag) return; + if (this.kind === "patternLinear" && this.patGimbal) { + const g = this.patGimbal.hit(p); + this.patGimbal.setHot(g ?? (this.patDrag ? ({ kind: "axis", i: this.patDrag.axis as 0 | 1 }) : null)); + if (g) return this.app.setHover(null); + } + if (this.kind === "select") { + const g = this.gimbal?.hit(p) ?? null; + this.gimbal?.setHot(g); + if (g) return this.app.setHover(null); + const hit = this.app.view.pick(p.x, p.y, { curves: this.sketchId ?? true, profiles: false, bodies: false, planes: false, axes: false, images: false, edgeTolPx: p.tol }); + if (hit?.kind === "point" && hit.sketch === this.sketchId) this.app.setHover({ kind: "point", sketch: hit.sketch, entity: hit.entity, p: hit.p }); + else if (hit?.kind === "curve" && hit.sketch === this.sketchId) this.app.setHover({ kind: "curve", sketch: hit.sketch, entity: hit.entity }); + else this.app.setHover(null); + return; + } + if (["trim", "delete", "extend", "offset", "split", "fillet", "align"].includes(this.kind) || this.isSelectionTool()) { + const hit = this.app.view.pick(p.x, p.y, { curves: this.sketchId ?? true, profiles: false, bodies: false, planes: false, axes: false, edgeTolPx: p.tol }); + const onCurve = hit?.kind === "curve" && hit.sketch === this.sketchId; + this.app.setHover(onCurve ? { kind: "curve", sketch: hit.sketch, entity: hit.entity } : null); + // Second pick of Extend/Fillet: show the result as dashed lines before tapping. + this.previewJoin(onCurve ? this.curveAt(p) : null); + if (!this.edit.picking) return; + } + if (this.kind === "project") { + const hit = this.app.view.pick(p.x, p.y, { profiles: false, planes: false, axes: false, edgeTolPx: p.tol }); + this.app.setHover( + hit?.kind === "edge" ? { kind: "edge", body: hit.body, edge: hit.edge } : hit?.kind === "curve" && hit.sketch !== this.sketchId ? { kind: "curve", sketch: hit.sketch, entity: hit.entity } : null, + ); + return; + } + this.cursor = this.snap(p); + this.refreshPreview(p); + } + + down(p: ToolPointer): boolean { + if (this.phase !== "draw") return false; + if (this.kind === "patternLinear" && this.startPatternDrag(p)) return true; + // Only the gimbal grabs right away; geometry drags start once the pointer moves (dragStart). + if (this.kind === "select") return this.startGimbalDrag(p); + if (!["line", "rect", "circle", "polygon", "ellipse", "arc"].includes(this.kind) || this.pts.length) return false; + const s = this.snap(p); + if (!s) return false; + this.pts = [s.uv]; + this.cursor = s; + this.dragging = true; + this.updatePanel(); + return true; + } + + drag(p: ToolPointer): void { + if (this.patDrag) return this.dragPattern(p); + this.typing.track(p); + if (this.sdrag) return this.dragGeometry(p); + this.cursor = this.snap(p); + // Typed sizes stay locked; the pointer still sets the direction. + this.refreshPreview(this.typing.active ? undefined : p); + } + + private get typing(): DragTyping { + return (this._typing ??= new DragTyping(this.app)); + } + private _typing: DragTyping | null = null; + private lockIndex = 0; + private ignoreUp = false; + /** A value was typed for the shape being drawn (Enter then advances/places it). */ + private typedThisShape = false; + + /** Dimensions that can be typed while dragging the current shape. */ + private lockKeys(): string[] { + switch (this.kind) { + case "line": + return ["len"]; + case "rect": + return memory.rect === "3pt" ? [] : ["w", "h"]; + case "circle": + return ["r"]; + case "polygon": + // Tab: radius → number of sides. + return ["r", "sides"]; + case "ellipse": + return ["rx"]; + default: + return []; + } + } + + dragKey(e: KeyboardEvent): boolean { + if (this.sdrag?.kind === "gimbal") { + const dr = this.sdrag; + const ring = dr.part.kind === "ring"; + return this.typing.key(e, { + kind: ring ? "angle" : "length", + apply: (v) => { + // Arrow: along its axis; square/centre: along the direction dragged so far; arc: degrees. + let d: Vec2 = [0, 0]; + if (dr.part.kind === "axis") d = dr.part.i === 0 ? [v, 0] : [0, v]; + else if (!ring) { + const l = Math.hypot(...dr.last.d) || 1; + d = [(dr.last.d[0] / l) * v, (dr.last.d[1] / l) * v]; + } + this.applyGimbal(d, ring ? (v * Math.PI) / 180 : 0); + }, + commit: () => this.endGeometryDrag(), + cancel: () => this.applyGimbal([0, 0], 0), + }); + } + const keys = this.lockKeys(); + if (!this.dragging || !this.pts.length || !keys.length) return false; + const key = keys[this.lockIndex]; + return this.typing.key(e, { + kind: key === "ang" ? "angle" : key === "sides" ? "number" : "length", + show: this.kind === "line" ? (text, bad) => this.lineDim?.setText(text, bad) : undefined, + apply: (v) => this.applyLock(key, v), + commit: () => { + // Finish the shape at the typed size; the coming mouse-up must not add a point. + this.dragging = false; + this.ignoreUp = true; + this.lockIndex = 0; + if (this.cursor) this.addPoint(this.cursor.uv, 1); + }, + cancel: () => (delete this.locks[key], this.refreshPreview()), + next: () => (this.lockIndex < keys.length - 1 ? (this.lockIndex++, true) : false), + }); + } + + up(p: ToolPointer): void { + if (this.patDrag) return this.endPatternDrag(); + if (this.sdrag) return this.endGeometryDrag(); + this.dragging = false; + this.typing.reset(); + this.lockIndex = 0; + if (this.ignoreUp) { + this.ignoreUp = false; + return; + } + if (!this.pts.length || !this.cursor) return; + const a = this.app.view.toScreen(sketchToWorld(this.plane!, this.pts[0])); + // A drag places the second point; a tap waits for it. + if (a && Math.hypot(a[0] - p.x, a[1] - p.y) > 12) this.addPoint(this.cursor.uv, 1); + } + + // ------------------------------------------- drag points / curves / gimbal + + private uvAt(p: { x: number; y: number }): Vec2 | null { + const w = this.plane && this.app.view.rayToPlane(p.x, p.y, this.plane); + return w ? toPlane(this.plane!, w) : null; + } + + /** Points that move when these curves/points move (round shapes move by their centre). */ + private dragRefs(curveIds: Iterable, pts: PointRef[]): DragRef[] { + const out = new Map(); + for (const id of curveIds) { + const e = this.entities.find((x) => x.id === id); + if (!e) continue; + const own = e.kind === "circle" || e.kind === "ellipse" || e.kind === "rect" || e.kind === "polygon" ? pointsOf(e).filter((q) => q.p === "c") : pointsOf(e).filter((q) => q.p !== "c"); + for (const q of own) out.set(`${id}:${q.p}`, { ref: { e: id, p: q.p }, at: q.at }); + } + for (const r of pts) { + const e = this.entities.find((x) => x.id === r.e); + const at = e && pointOf(e, r.p); + if (at) out.set(refKey(r), { ref: r, at }); + } + return [...out.values()]; + } + + private startGimbalDrag(p: ToolPointer): boolean { + const part = this.gimbal?.hit(p); + if (!part || !this.gimbal) return false; + const line = this.singleLine(); + if (part.kind === "center" && line) { + this.sdrag = { kind: "pivot", line: line.id }; + this.gimbal.setHot(part); + return true; + } + const refs = this.dragRefs(this.selected, this.selPts); + if (!refs.length) return false; + const c = toPlane(this.plane!, this.gimbal.origin); + this.sdrag = { kind: "gimbal", part, from: p, refs, center: c, last: { d: [0, 0], ang: 0 } }; + this.gimbal.setHot(part); + return true; + } + + /** Press on a curve/point and move: drag it (a tap without moving selects it instead). */ + dragStart(p: ToolPointer): boolean { + if (this.phase !== "draw" || this.kind !== "select") return false; + const hit = this.app.view.pick(p.x, p.y, { curves: this.sketchId ?? true, profiles: false, bodies: false, planes: false, axes: false, images: false, edgeTolPx: p.tol }); + const from = this.uvAt(p); + if (!from || !hit || (hit.kind !== "point" && hit.kind !== "curve") || hit.sketch !== this.sketchId) return false; + // Dragging something unselected drags just that; a selected thing drags the whole selection. + const isSel = hit.kind === "curve" ? this.selected.has(hit.entity) : this.selPts.some((r) => r.e === hit.entity && r.p === hit.p); + const refs = isSel ? this.dragRefs(this.selected, this.selPts) : hit.kind === "curve" ? this.dragRefs([hit.entity], []) : this.dragRefs([], [{ e: hit.entity, p: hit.p }]); + if (!refs.length) return false; + this.sdrag = { kind: "points", from, refs }; + return true; + } + + /** The one selected line (no points selected), if that's the selection. */ + private singleLine(): Extract | null { + if (this.selected.size !== 1 || this.selPts.length) return null; + const e = this.entities.find((x) => this.selected.has(x.id)); + return e?.kind === "line" ? e : null; + } + + private dragGeometry(p: ToolPointer): void { + const dr = this.sdrag!; + if (dr.kind === "pivot") { + // Slide along the line; snaps to its ends and middle. + const e = this.entities.find((x) => x.id === dr.line); + const uv = this.uvAt(p); + if (e?.kind !== "line" || !uv) return; + const d: Vec2 = [e.b[0] - e.a[0], e.b[1] - e.a[1]]; + const L2 = d[0] * d[0] + d[1] * d[1] || 1; + let t = Math.max(0, Math.min(1, ((uv[0] - e.a[0]) * d[0] + (uv[1] - e.a[1]) * d[1]) / L2)); + const px = Math.sqrt(L2) / (this.app.view.cam.worldPerPixel(this.app.view.height) || 1); + for (const s of [0, 0.5, 1]) if (Math.abs(t - s) * px < 12) t = s; + this.pivotT = { line: dr.line, t }; + this.gimbal?.setCenter(sketchToWorld(this.plane!, [e.a[0] + d[0] * t, e.a[1] + d[1] * t]).toArray() as Vec3); + this.app.ui.setLabel(p.x, p.y, t === 0 ? "Pivot: start" : t === 1 ? "Pivot: end" : t === 0.5 ? "Pivot: midpoint" : "Pivot"); + return; + } + if (dr.kind === "points") { + const uv = this.uvAt(p); + if (!uv) return; + this.moveRefs(dr.refs, (q) => [q[0] + uv[0] - dr.from[0], q[1] + uv[1] - dr.from[1]]); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(Math.hypot(uv[0] - dr.from[0], uv[1] - dr.from[1]))}`); + return; + } + if (this.typing.active) return; + const view = this.app.view; + const plane = this.plane!; + const step = niceStepOf(view.cam.worldPerPixel(view.height) * 4); + const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step); + if (dr.part.kind === "ring") { + const c = view.toScreen(sketchToWorld(plane, dr.center)); + if (!c) return; + const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]); + const facing = dot(plane.normal, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1; + let deg = ((-(ang(p) - ang(dr.from)) * 180) / Math.PI) * facing; + deg = ((deg + 540) % 360) - 180; + const snapped = p.shift ? deg : Math.round(deg / 5) * 5; + this.applyGimbal([0, 0], (snapped * Math.PI) / 180); + this.app.ui.setLabel(p.x, p.y, `${snapped}° · type a value`); + return; + } + const a = this.uvAt(dr.from); + const b = this.uvAt(p); + if (!a || !b) return; + let d: Vec2 = [b[0] - a[0], b[1] - a[1]]; + if (dr.part.kind === "axis") d = dr.part.i === 0 ? [snap(d[0]), 0] : [0, snap(d[1])]; + else d = [snap(d[0]), snap(d[1])]; + this.applyGimbal(d, 0); + this.app.ui.setLabel(p.x, p.y, `${fmtLen(Math.hypot(...d))} · type a value`); + } + + /** Move the gimbal's selection by d (sketch units) and/or rotate it about its centre. */ + private applyGimbal(d: Vec2, ang: number): void { + const dr = this.sdrag; + if (dr?.kind !== "gimbal") return; + dr.last = { d, ang }; + const c = dr.center; + const cs = Math.cos(ang); + const sn = Math.sin(ang); + this.moveRefs(dr.refs, (q) => { + const x = q[0] - c[0]; + const y = q[1] - c[1]; + return [c[0] + x * cs - y * sn + d[0], c[1] + x * sn + y * cs + d[1]]; + }); + this.gimbal?.setCenter(sketchToWorld(this.plane!, [c[0] + d[0], c[1] + d[1]]).toArray() as Vec3); + // Copying: the originals stay where they were (drawn there while the copy moves). + if (copyMode.on && this.dragBase) { + this.clearOverlays(); + this.drawGhosts(this.dragBase.filter((e) => this.selected.has(e.id)), 0xc9d3e6); + } + } + + /** Live: pull the given points to new places; constraints keep the rest consistent. */ + private moveRefs(refs: DragRef[], to: (q: Vec2) => Vec2): void { + if (!this.sketchId) return; + const base = this.dragBase ?? this.entities; + this.dragBase ??= base; + const r = solve(base, this.constraints, { drag: refs.map((d) => ({ ref: d.ref, to: to(d.at) })) }); + const id = this.sketchId; + this.app.store.transient((doc) => { + const f = doc.features.find((x) => x.id === id); + if (f?.type === "sketch") f.entities = r.entities; + }); + } + + private dragBase: SketchEntity[] | null = null; + + private endGeometryDrag(): void { + // Copy on: the moved curves become copies; the originals go back where they were. + if (this.sdrag?.kind === "gimbal" && copyMode.on && this.dragBase) { + const base = this.dragBase; + const moved = this.entities.filter((e) => this.selected.has(e.id)); + const copies = moved.map((e) => ({ ...e, id: uid() })); + this.sdrag = null; + this.dragBase = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + this.commit([...base, ...copies]); + // The copies are selected: the next drag copies them again. + this.selected = new Set(copies.map((e) => e.id)); + this.selPts = []; + this.gimbal?.setHot(null); + return this.selectionChanged(); + } + if (this.sdrag?.kind === "pivot") { + this.sdrag = null; + this.app.ui.setLabel(0, 0, null); + this.gimbal?.setHot(null); + return this.refreshGimbal(); + } + this.sdrag = null; + this.dragBase = null; + this.typing.reset(); + this.app.ui.setLabel(0, 0, null); + // One undo step for the whole drag. + this.commit(this.entities); + this.gimbal?.setHot(null); + this.refreshGimbal(); + } + + /** The sketch gimbal sits at the centre of the selection (Select tool only). */ + private refreshGimbal(): void { + const show = this.kind === "select" && this.phase === "draw" && (this.selected.size > 0 || this.selPts.length > 0) && !this.sdrag; + if (!show) { + this.gimbal?.dispose(); + this.gimbal = null; + // Hidden while dragging too, so it doesn't jump around. + this.copyToggle?.dispose(); + this.copyToggle = null; + return; + } + const refs = this.dragRefs(this.selected, this.selPts); + if (!refs.length) return; + let c: Vec2 = [refs.reduce((s, r) => s + r.at[0], 0) / refs.length, refs.reduce((s, r) => s + r.at[1], 0) / refs.length]; + // A single line rotates about its chosen pivot (middle by default). + const line = this.singleLine(); + if (line) { + const t = this.pivotT?.line === line.id ? this.pivotT.t : 0.5; + c = [line.a[0] + (line.b[0] - line.a[0]) * t, line.a[1] + (line.b[1] - line.a[1]) * t]; + } + const plane = this.plane!; + this.gimbal ??= new Gimbal(this.app.view, { axes: [plane.xDir, planeY(plane), plane.normal], parts: IN_PLANE }); + const g = this.gimbal; + this.copyToggle ??= new CopyToggle(this.app.view, () => g.origin); + this.gimbal.setCenter(sketchToWorld(plane, c).toArray() as Vec3); + } + + /** + * Left-drag on empty space: window selection of the curves entirely inside + * the box (a drag never orbits in a sketch — that's the right button). + */ + box(a: { x: number; y: number }, b: { x: number; y: number }, final: boolean, add: boolean): void { + if (!final || this.phase !== "draw" || !this.plane || this.pts.length) return; + if (this.kind !== "select" && !this.isSelectionTool()) return; + const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)]; + const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)]; + const inside = (q: Vec2) => { + const s = this.app.view.toScreen(sketchToWorld(this.plane!, q)); + return !!s && s[0] >= x0 && s[0] <= x1 && s[1] >= y0 && s[1] <= y1; + }; + const picked = this.entities.filter((e) => entityPolylines(e).every((poly) => poly.every(inside))).map((e) => e.id); + if (!add) { + this.selected.clear(); + this.selPts = []; + } + for (const id of picked) this.selected.add(id); + this.selectionChanged(); + } + + /** Right-click: end the current chain/shape (and keep what's drawn). */ + context(): void { + if (this.kind === "spline" && this.pts.length >= 2) return this.finishSpline(false); + if (this.pts.length) return this.resetDrawing(); + if (this.selected.size || this.selPts.length) this.clearSelection(); + } + + tap(p: ToolPointer, count: number): void { + if (this.phase === "plane") return this.pickPlane(p); + if (this.edit.picking) return this.pickForEdit(p); + if (this.kind === "select" && this.tapSurfaceIn3D(p)) return; + switch (this.kind) { + case "select": + case "move": + case "scale": + case "patternLinear": + case "patternCircular": + // With curves selected and no centre yet, the tap places the centre (snapping to points). + if (this.selected.size && !this.edit.pivot && !p.shift) { + const s = this.snap(p); + if (s) this.edit.pivot = s.uv; + this.updatePanel(); + this.refreshPreview(); + return this.setHint("Set the count and angle, then Apply. Tap the Center field to move the centre."); + } + return this.tapSelect(p, count); + case "rotate": + case "mirror": + return this.tapSelect(p, count); + case "delete": + return this.tapCurve(p, (id) => this.commit(this.entities.filter((e) => e.id !== id))); + case "trim": + if (memory.trim === "join") return this.tapCurve(p, (id, uv) => this.tapJoin(id, uv)); + return this.tapCurve(p, (id, uv) => this.commit(this.withoutBoundary(trim([...this.entities, ...this.boundary], id, uv)))); + case "align": + return this.tapCurve(p, (id) => this.tapAlign(id)); + case "extend": + return this.tapCurve(p, (id, uv) => this.tapExtend(id, uv)); + case "split": + return this.tapCurve(p, (id, uv) => this.tapSplit(id, uv, p.shift)); + case "offset": + return this.tapCurve(p, (id) => ((this.edit.offsetOf = id), this.updatePanel(), this.refreshPreview())); + case "fillet": + return this.tapFillet(p); + case "project": + return this.tapProject(p); + } + const s = this.snap(p); + if (!s) return; + this.cursor = s; + this.addPoint(s.uv, count); + } + + key(e: KeyboardEvent): boolean { + if (e.ctrlKey || e.metaKey) return false; + const k = e.key.toLowerCase(); + // Shift+letter: constraints. + if (e.shiftKey && k.length === 1) { + const b = CONSTRAINT_BUTTONS.find((x) => x.key.toLowerCase() === k); + if (b) { + const have = existingConstraints(b.type, this.constraints, this.selPts, this.pickedCurves()); + if (have.length) this.removeConstraints(have); + else this.addConstraint(b.type); + return true; + } + } + // Two things selected with a distance shown: typing sets it. + if (this.distDim && /^[0-9.,(]$/.test(e.key)) { + this.distDim.focusWith(e.key === "," ? "." : e.key); + return true; + } + // Typing while drawing: e.g. line length, Enter, angle, Enter. + const keys = this.lockKeys(); + if (this.phase === "draw" && this.pts.length && keys.length && !this.dragging) { + const starts = /^[0-9.,(-]$/.test(e.key); + const routed = this.typing.active || starts || (k === "enter" && this.typedThisShape); + if (routed) { + const key = keys[this.lockIndex]; + this.typedThisShape = true; + const used = this.typing.key(e, { + kind: key === "ang" ? "angle" : key === "sides" ? "number" : "length", + show: this.kind === "line" ? (text, bad) => this.lineDim?.setText(text, bad) : undefined, + apply: (v) => this.applyLock(key, v), + commit: () => { + // Enter moves on to the next size — except the polygon's side count (Tab only). + if (this.lockIndex < keys.length - 1 && keys[this.lockIndex + 1] !== "sides") { + this.lockIndex++; + this.setHint(`Now type the ${{ ang: "angle", h: "height", sides: "number of sides" }[keys[this.lockIndex]] ?? "next value"} (or Enter to keep it), then Enter.`); + return; + } + this.lockIndex = 0; + this.typedThisShape = false; + if (this.cursor) this.addPoint(this.cursor.uv, 1); + this.setHint(); + }, + cancel: () => (delete this.locks[key], this.refreshPreview()), + next: () => (this.lockIndex < keys.length - 1 ? (this.lockIndex++, true) : false), + }); + if (used) return true; + } + } + if (k === "escape") { + // Step out one level: the shape being drawn → the selection → the drawing tool (to Select) → the sketch. + if (this.pts.length || this.edit.picking || this.edit.offsetOf || this.edit.extendFrom || this.edit.alignFrom || this.edit.filletFrom || this.filletEdit) this.resetDrawing(); + else if (this.selected.size || this.selPts.length) this.clearSelection(); + else if (this.kind !== "select" && this.phase === "draw" && this.sketchId) this.setKind("select"); + else this.app.setTool(null); + return true; + } + if (k === "enter") { + this.finishByKey(); + return true; + } + if ((k === "delete" || k === "backspace") && this.selected.size) { + this.deleteSelected(); + return true; + } + const shortcuts: Record = { l: "line", a: "arc", i: "spline", r: "rect", c: "circle", g: "polygon", p: "project", o: "offset", m: "move", s: "scale", t: "trim", e: "extend", v: "select" }; + if (shortcuts[k] && this.phase === "draw") { + this.setKind(shortcuts[k]); + return true; + } + return false; + } + + // ------------------------------------------------------- plane picking + + private pickPlane(p: ToolPointer): void { + const hit = this.app.view.pick(p.x, p.y, { edges: false, planes: true, planesFirst: true, profiles: true, edgeTolPx: 0 }); + if (!hit) return; + if (hit.kind === "plane") { + this.plane = this.app.view.planeOf(hit.id)!; + } else if (hit.kind === "face") { + const info = this.app.view.body(hit.body)?.faces[hit.face]; + if (!info?.plane) return this.app.ui.toast("Pick a flat face"); + this.plane = info.plane; + this.attachedTo = { body: hit.body, center: info.center, normal: info.normal, area: info.area }; + } else if (hit.kind === "profile") { + // Tapping an existing sketch continues it. + this.sketchId = hit.sketch; + this.plane = this.app.sketchPlane(hit.sketch) ?? null; + } else return; + this.beginDrawing(); + } + + // -------------------------------------------------------------- snapping + + private snap(p: ToolPointer): Snap | null { + const plane = this.plane; + if (!plane) return null; + const w = this.app.view.rayToPlane(p.x, p.y, plane); + if (!w) return null; + const raw = toPlane(plane, w); + if (p.shift) return { uv: raw }; + const s = settings.value.snap; + const view = this.app.view; + const screen = (uv: Vec2) => view.toScreen(sketchToWorld(plane, uv)); + const tol = p.tol * 1.4; + + const cands: { p: Vec2; label: string; ref?: PointRef }[] = [{ p: [0, 0], label: "Origin" }]; + if (s.guidePoints) { + for (const e of this.entities) { + // Named points first (they can be constrained), then midpoints etc. + for (const q of pointsOf(e)) cands.push({ p: q.at, label: q.p === "c" ? "Center" : "Endpoint", ref: { e: e.id, p: q.p } }); + for (const g of guidePoints(e)) if (g.kind === "mid") cands.push({ p: g.p, label: "Midpoint" }); + } + for (const e of this.boundary) for (const g of guidePoints(e)) cands.push({ p: g.p, label: g.kind === "mid" ? "Midpoint" : "Edge point" }); + for (const q of this.pts) cands.push({ p: q, label: "Point" }); + } + if (s.points3d) { + for (const b of view.bodyList) { + for (const e of b.edges) { + for (const v of [e.start, e.end]) { + const off = Math.abs((v[0] - plane.origin[0]) * plane.normal[0] + (v[1] - plane.origin[1]) * plane.normal[1] + (v[2] - plane.origin[2]) * plane.normal[2]); + if (off < 1e-4 || s.distantEdges) cands.push({ p: toPlane(plane, v), label: "3D point" }); + } + } + } + } + let best: { p: Vec2; label: string; d: number; ref?: PointRef } | null = null; + for (const c of cands) { + const sc = screen(c.p); + if (!sc) continue; + const d = Math.hypot(sc[0] - p.x, sc[1] - p.y); + if (d < tol && (!best || d < best.d)) best = { ...c, d }; + } + if (best) return { uv: [...best.p] as Vec2, label: best.label, ref: best.ref }; + + const out: Snap = { uv: raw, guides: [] }; + const wpp = view.cam.worldPerPixel(view.height); + if (s.guideLines) { + // Align horizontally/vertically with nearby guide points. + let bu: { v: number; from: Vec2 } | null = null; + let bv: { v: number; from: Vec2 } | null = null; + for (const c of cands) { + const du = Math.abs(raw[0] - c.p[0]) / wpp; + const dv = Math.abs(raw[1] - c.p[1]) / wpp; + if (du < tol && (!bu || du < Math.abs(raw[0] - bu.v) / wpp)) bu = { v: c.p[0], from: c.p }; + if (dv < tol && (!bv || dv < Math.abs(raw[1] - bv.v) / wpp)) bv = { v: c.p[1], from: c.p }; + } + if (bu) out.uv = [bu.v, out.uv[1]]; + if (bv) out.uv = [out.uv[0], bv.v]; + if (bu || bv) out.label = bu && bv ? "Aligned" : bu ? "Vertical" : "Horizontal"; + // Grid-snap only the coordinates that aren't aligned to a guide. + if (s.grid) { + const step = view.grid.step; + out.uv = [bu ? out.uv[0] : Math.round(out.uv[0] / step) * step, bv ? out.uv[1] : Math.round(out.uv[1] / step) * step]; + } + // Guides run from the reference point straight to the final point. + if (bu) out.guides!.push([bu.from, out.uv]); + if (bv) out.guides!.push([bv.from, out.uv]); + return out; + } + if (s.grid) { + const step = view.grid.step; + out.uv = [Math.round(out.uv[0] / step) * step, Math.round(out.uv[1] / step) * step]; + } + return out; + } + + // -------------------------------------------------------------- drawing + + /** Cursor after applying typed (locked) dimensions. */ + private lockedCursor(): Vec2 | null { + const c = this.cursor?.uv; + if (!c) return null; + const a = this.pts[0]; + const L = this.locks; + if (!a) return c; + const last = this.pts[this.pts.length - 1]; + switch (this.kind) { + case "line": { + let ang = Math.atan2(c[1] - last[1], c[0] - last[0]); + let len = Math.hypot(c[0] - last[0], c[1] - last[1]); + if (L.ang !== undefined) ang = (L.ang * Math.PI) / 180; + if (L.len !== undefined) len = L.len; + return [last[0] + Math.cos(ang) * len, last[1] + Math.sin(ang) * len]; + } + case "rect": { + if (this.pts.length !== 1) return c; + const k = memory.rect === "center" ? 0.5 : 1; + const sx = Math.sign(c[0] - a[0]) || 1; + const sy = Math.sign(c[1] - a[1]) || 1; + return [L.w !== undefined ? a[0] + sx * L.w * k : c[0], L.h !== undefined ? a[1] + sy * L.h * k : c[1]]; + } + case "circle": + case "polygon": { + if (L.r === undefined) return c; + // A circle's typed size is its diameter; a polygon's, its radius. + const r = this.kind === "circle" ? L.r / 2 : L.r; + const ang = Math.atan2(c[1] - a[1], c[0] - a[0]); + return [a[0] + Math.cos(ang) * r, a[1] + Math.sin(ang) * r]; + } + case "ellipse": { + if (this.pts.length === 1 && L.rx !== undefined) { + const ang = Math.atan2(c[1] - a[1], c[0] - a[0]); + return [a[0] + (Math.cos(ang) * L.rx) / 2, a[1] + (Math.sin(ang) * L.rx) / 2]; + } + return c; + } + } + return c; + } + + private lastLineId: string | null = null; + private chainFirstId: string | null = null; + + private addPoint(uv: Vec2, count: number): void { + const c = this.lockedCursor() ?? uv; + const pt = this.pts.length ? c : uv; + const k = this.kind; + const locked = Object.keys(this.locks).length > 0; + // A typed size moves the point off whatever it snapped to. + const snapRef = locked ? undefined : this.cursor?.ref; + if (!this.pts.length) this.startRef = snapRef ?? null; + if (k === "line") { + if (count >= 2 || (this.pts.length && samePt(pt, this.pts[this.pts.length - 1]))) return this.resetDrawing(); + if (this.pts.length) { + const start = this.pts[0]; + const a = this.pts[this.pts.length - 1]; + const id = uid(); + const cs: SketchConstraint[] = []; + const co = (p: PointRef, q: PointRef): SketchConstraint => ({ id: uid(), type: "coincident", pts: [p, q] }); + // A chain stays joined; the rest (snaps, H/V) only with Auto constrain on. + const auto = settings.value.autoConstrain; + if (this.lastLineId) cs.push(co({ e: this.lastLineId, p: "b" }, { e: id, p: "a" })); + else if (this.startRef && auto) cs.push(co(this.startRef, { e: id, p: "a" })); + const closes = this.pts.length > 1 && samePt(pt, start) && this.chainFirstId; + if (closes) cs.push(co({ e: id, p: "b" }, { e: this.chainFirstId!, p: "a" })); + else if (snapRef && auto) cs.push(co({ e: id, p: "b" }, snapRef)); + if (auto && Math.abs(pt[1] - a[1]) < 1e-9) cs.push({ id: uid(), type: "horizontal", curves: [id] }); + else if (auto && Math.abs(pt[0] - a[0]) < 1e-9) cs.push({ id: uid(), type: "vertical", curves: [id] }); + // Typed values become driving dimensions. + if (this.locks.len !== undefined) cs.push({ id: uid(), type: "dim", curves: [id], prop: "length", value: this.locks.len }); + if (this.locks.ang !== undefined && !cs.some((x) => x.type === "horizontal" || x.type === "vertical")) cs.push({ id: uid(), type: "dim", curves: [id], prop: "angle", value: this.locks.ang }); + this.commitAdd([{ id, kind: "line", a, b: pt }], cs); + this.lastLineId = id; + this.chainFirstId ??= id; + // Closing the chain on its first point ends it. + if (closes || (this.pts.length > 1 && samePt(pt, start))) return this.resetDrawing(); + } + this.pts.push(pt); + this.locks = {}; + this.typedThisShape = false; + } else if (k === "spline") { + if (count >= 2) return this.finishSpline(false); + if (this.pts.length >= 3 && this.screenDist(pt, this.pts[0]) < 14) return this.finishSpline(true); + this.pts.push(pt); + } else if (k === "text") { + this.pts = [pt]; + } else { + this.pts.push(pt); + const need = k === "arc" || k === "ellipse" || (k === "rect" && memory.rect === "3pt") ? 3 : 2; + if (this.pts.length >= need) { + const e = this.buildShape(this.pts); + const cs: SketchConstraint[] = []; + if (e) { + const L = this.locks; + const dim = (prop: string, value?: number) => value !== undefined && cs.push({ id: uid(), type: "dim", curves: [e.id], prop, value }); + if (e.kind === "rect") { + const f = memory.rect === "center" ? 1 : 1; + dim("w", L.w !== undefined ? L.w * (memory.rect === "center" ? 2 : 1) * f : undefined); + dim("h", L.h !== undefined ? L.h * (memory.rect === "center" ? 2 : 1) : undefined); + } + if (e.kind === "circle") dim("diameter", L.r); + if (e.kind === "polygon") dim("radius", L.r); + if (e.kind === "ellipse") (dim("dx", L.rx), dim("dy", L.ry)); + // A centre placed on an existing point stays on it. + if (settings.value.autoConstrain && (e.kind === "circle" || e.kind === "polygon" || e.kind === "ellipse" || (e.kind === "rect" && memory.rect === "center")) && this.startRef) { + cs.push({ id: uid(), type: "coincident", pts: [{ e: e.id, p: "c" }, this.startRef] }); + } + } + this.pts = []; + this.locks = {}; + this.typedThisShape = false; + this.app.ui.setLabel(0, 0, null); + if (e) this.commitAdd([e], cs); + } + } + this.updatePanel(); + this.refreshPreview(); + } + + private finishByKey(): void { + if (this.kind === "spline") return this.finishSpline(false); + if (this.kind === "text" && this.pts.length) return void this.commitText(); + if (this.kind === "offset" && this.edit.offsetOf) return this.applyOffset(); + if (this.isSelectionTool() && this.selected.size) return this.applyTransform(); + if (this.pts.length && Object.keys(this.locks).length && this.cursor) return this.addPoint(this.cursor.uv, 1); + this.resetDrawing(); + } + + private finishSpline(closed: boolean): void { + if (this.pts.length >= 2) this.commitAdd([{ id: uid(), kind: "spline", points: this.pts, closed: closed && this.pts.length >= 3, mode: memory.spline }]); + this.resetDrawing(); + } + + /** The entity the current points describe (also used for the preview). */ + private buildShape(pts: Vec2[]): SketchEntity | null { + const [a, b, c] = pts; + const id = uid(); + switch (this.kind) { + case "line": + return b ? { id, kind: "line", a, b } : null; + case "arc": + if (!b) return null; + if (!c) return { id, kind: "line", a, b }; + return arcFrom3(a, c, b) ? { id, kind: "arc", a, m: c, b } : null; + case "rect": { + if (!b) return null; + if (memory.rect === "3pt") { + const ang = Math.atan2(b[1] - a[1], b[0] - a[0]); + const w = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (!c) return w > 0 ? { id, kind: "line", a, b } : null; + // Height = signed distance of c from the a–b edge. + const h = (c[1] - a[1]) * Math.cos(ang) - (c[0] - a[0]) * Math.sin(ang); + const center: Vec2 = [(a[0] + b[0]) / 2 - (Math.sin(ang) * h) / 2, (a[1] + b[1]) / 2 + (Math.cos(ang) * h) / 2]; + return Math.abs(h) > 1e-9 ? { id, kind: "rect", center, w, h: Math.abs(h), rotation: ang } : null; + } + const center: Vec2 = memory.rect === "center" ? a : [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + const w = Math.abs(b[0] - a[0]) * (memory.rect === "center" ? 2 : 1); + const h = Math.abs(b[1] - a[1]) * (memory.rect === "center" ? 2 : 1); + return w > 1e-9 && h > 1e-9 ? { id, kind: "rect", center, w, h, rotation: 0 } : null; + } + case "circle": { + const r = b ? Math.hypot(b[0] - a[0], b[1] - a[1]) : 0; + return r > 1e-9 ? { id, kind: "circle", center: a, radius: r } : null; + } + case "polygon": { + const r = b ? Math.hypot(b[0] - a[0], b[1] - a[1]) : 0; + return r > 1e-9 ? { id, kind: "polygon", center: a, radius: r, sides: memory.sides, angle: Math.atan2(b[1] - a[1], b[0] - a[0]) } : null; + } + case "ellipse": { + if (!b) return null; + const rx = Math.hypot(b[0] - a[0], b[1] - a[1]); + const rot = Math.atan2(b[1] - a[1], b[0] - a[0]); + let ry = rx / 2; + if (c) ry = Math.abs((c[1] - a[1]) * Math.cos(rot) - (c[0] - a[0]) * Math.sin(rot)); + if (this.locks.ry !== undefined) ry = this.locks.ry / 2; + return rx > 1e-9 && ry > 1e-9 ? { id, kind: "ellipse", center: a, rx, ry, rotation: rot } : null; + } + case "spline": + return pts.length >= 2 ? { id, kind: "spline", points: pts, closed: false, mode: memory.spline } : null; + } + return null; + } + + private resetDrawing(): void { + this.pts = []; + this.locks = {}; + this.lastLineId = null; + this.chainFirstId = null; + this.startRef = null; + this.typedThisShape = false; + this.lockIndex = 0; + this.typing.reset(); + this.edit.picking = undefined; + this.edit.offsetOf = undefined; + this.edit.extendFrom = this.edit.alignFrom = undefined; + this.edit.filletFrom = undefined; + this.cancelFillet(); + this.clearPreviewJoin(); + this.clearOverlays(); + this.hideLineDim(); + this.app.ui.setLabel(0, 0, null); + this.updatePanel(); + this.setHint(); + } + + // -------------------------------------------------------------- preview + + // ----------------------------------------------- linear pattern gimbal + + /** Arrows showing which way a linear pattern runs: drag one to set direction and spacing. */ + private patGimbal: Gimbal | null = null; + private patDrag: { axis: number; from: ToolPointer; center: Vec2 } | null = null; + private patBox: PatternBox | null = null; + private patMeasure: "between" | "total" = "between"; + + private selectionCentre(): Vec2 | null { + const sel = this.entities.filter((e) => this.selected.has(e.id)); + return sel.length ? centroidOf(sel) : null; + } + + private refreshPatternGimbal(): void { + const c = this.kind === "patternLinear" && this.phase === "draw" && this.plane ? this.selectionCentre() : null; + if (!c) { + this.patGimbal?.dispose(); + this.patGimbal = null; + this.patBox?.dispose(); + this.patBox = null; + return; + } + const plane = this.plane!; + // Turned so its first arrow points the way the pattern runs. + const ang = Math.hypot(this.edit.dx, this.edit.dy) > 1e-12 ? Math.atan2(this.edit.dy, this.edit.dx) : 0; + const u = sketchToWorld({ ...plane, origin: [0, 0, 0] }, [Math.cos(ang), Math.sin(ang)]).toArray() as Vec3; + const v = sketchToWorld({ ...plane, origin: [0, 0, 0] }, [-Math.sin(ang), Math.cos(ang)]).toArray() as Vec3; + if (!this.patGimbal || this.patAng !== ang) { + this.patGimbal?.dispose(); + this.patGimbal = new Gimbal(this.app.view, { axes: [u, v, plane.normal], parts: (q) => q.kind === "axis" && q.i < 2 }); + this.patAng = ang; + } + this.patGimbal.setCenter(sketchToWorld(plane, c).toArray() as Vec3); + } + private patAng = 0; + + private startPatternDrag(p: ToolPointer): boolean { + const part = this.patGimbal?.hit(p); + const c = this.selectionCentre(); + if (!part || part.kind !== "axis" || !c) return false; + this.patDrag = { axis: part.i, from: p, center: c }; + this.patBox?.dispose(); + this.patBox = null; + return true; + } + + private dragPattern(p: ToolPointer): void { + const dr = this.patDrag!; + const plane = this.plane!; + // The arrow's direction in the sketch. + const a = this.patAng + (dr.axis === 1 ? Math.PI / 2 : 0); + const dir2: Vec2 = [Math.cos(a), Math.sin(a)]; + const dirW = sketchToWorld({ ...plane, origin: [0, 0, 0] }, dir2).toArray() as Vec3; + const view = this.app.view; + let d = axisDrag(view, sketchToWorld(plane, dr.center).toArray() as Vec3, dirW, dr.from, p); + const step = niceStepOf(view.cam.worldPerPixel(view.height) * 4); + if (!p.shift) d = Math.round(d / step) * step; + if (Math.abs(d) < 1e-12) return; + // The drag sets the spacing between neighbours (or the whole run, in Total mode). + const n = Math.max(2, this.edit.count); + const spacing = this.patMeasure === "total" ? d / (n - 1) : d; + this.edit.dx = dir2[0] * spacing; + this.edit.dy = dir2[1] * spacing; + this.app.ui.setLabel(p.x, p.y, `${fmtLen(Math.abs(d))} · ${n} copies`); + this.refreshPreview(); + } + + private endPatternDrag(): void { + this.patDrag = null; + this.app.ui.setLabel(0, 0, null); + this.patGimbal?.setHot(null); + this.refreshPatternGimbal(); + this.updatePanel(); + this.showPatternBox(); + } + + /** Count and spacing, typed right where the pattern is. */ + private showPatternBox(): void { + const c = this.selectionCentre(); + if (!c || !this.plane) return; + const spacing = Math.hypot(this.edit.dx, this.edit.dy); + const n = Math.max(2, this.edit.count); + this.patBox?.dispose(); + this.patBox = new PatternBox(this.app.view, { + count: n, + spacing: this.patMeasure === "total" ? spacing * (n - 1) : spacing, + measure: this.patMeasure, + onChange: (v) => { + this.patMeasure = v.measure; + this.edit.count = v.count; + const each = v.measure === "total" ? v.spacing / Math.max(1, v.count - 1) : v.spacing; + const L = Math.hypot(this.edit.dx, this.edit.dy) || 1; + const dir: Vec2 = L > 1e-12 && spacing > 1e-12 ? [this.edit.dx / L, this.edit.dy / L] : [Math.cos(this.patAng), Math.sin(this.patAng)]; + this.edit.dx = dir[0] * each; + this.edit.dy = dir[1] * each; + this.refreshPreview(); + this.updatePanel(); + }, + onCommit: () => { + this.patBox?.dispose(); + this.patBox = null; + this.applyTransform(); + }, + }); + const end: Vec2 = [c[0] + this.edit.dx * (n - 1), c[1] + this.edit.dy * (n - 1)]; + this.patBox.place(sketchToWorld(this.plane, end).toArray() as Vec3); + } + + private refreshPreview(p?: ToolPointer): void { + if (this.phase !== "draw" || !this.plane) return; + this.refreshPatternGimbal(); + this.clearOverlays(); + const ghosts: SketchEntity[] = []; + let label: string | null = null; + const c = this.lockedCursor(); + if (["line", "arc", "rect", "circle", "polygon", "ellipse", "spline"].includes(this.kind) && this.pts.length && c) { + const pts = this.kind === "line" ? [this.pts[this.pts.length - 1], c] : [...this.pts, c]; + const e = this.buildShape(pts); + // A line being drawn is its own dimension (arrows + length box, type to set it); others get a pointer label. + if (e?.kind === "line") this.showLineDim(e.a, e.b); + else { + if (e) ghosts.push(e); + label = dimLabel(e, pts); + } + } + if (!(this.kind === "line" && this.pts.length && c)) this.hideLineDim(); + if (this.kind === "text" && this.pts.length) { + void textEntities(this.text || " ", this.pts[0], memory.textSize).then((es) => { + if (this.kind !== "text" || !this.pts.length) return; + this.drawGhosts(es); + }); + } + if (this.kind === "offset" && this.edit.offsetOf) ghosts.push(...this.offsetResult()); + if (this.isSelectionTool() && this.selected.size) ghosts.push(...this.transformed(true)); + this.drawGhosts(ghosts); + // Midpoints of lines and sides: snap targets, shown so you can aim for them. + if (settings.value.showGuidePoints) { + const mids = [...this.entities, ...this.boundary].flatMap((e) => guidePoints(e).filter((g) => g.kind === "mid").map((g) => sketchToWorld(this.plane!, g.p, 0.01))); + if (mids.length) { + const m = new Points(new BufferGeometry().setFromPoints(mids), new PointsMaterial({ color: 0x9fb4d6, size: 6, sizeAttenuation: false, depthTest: false, transparent: true, opacity: 0.85 })); + m.renderOrder = 9; + this.addOverlay(m); + } + } + // Snap marker + guide lines. + if (this.cursor && settings.value.showGuidePoints) { + const marker = new Points(new BufferGeometry().setFromPoints([sketchToWorld(this.plane, c ?? this.cursor.uv, 0.01)]), dotMaterial({ color: this.cursor.label ? 0x4fd18b : 0xffc23d, size: 11 })); + marker.renderOrder = 10; + this.addOverlay(marker); + for (const [g0, g1] of this.cursor.guides ?? []) { + const line = new Line(new BufferGeometry().setFromPoints([sketchToWorld(this.plane, g0), sketchToWorld(this.plane, g1)]), new LineDashedMaterial({ color: 0x4fd18b, dashSize: this.app.view.cam.worldPerPixel(this.app.view.height) * 5, gapSize: this.app.view.cam.worldPerPixel(this.app.view.height) * 4, depthTest: false })); + line.computeLineDistances(); + this.addOverlay(line); + } + } + if (p) { + const hint = settings.value.showSnapHints && this.cursor?.label ? this.cursor.label : null; + // While a shape is being drawn its size can be typed. + const text = [label, hint].filter(Boolean).join(" · "); + this.app.ui.setLabel(p.x, p.y, text ? (label ? `${text} · type a value` : text) : null); + } + this.app.view.requestRender(); + } + + /** A typed size; "sides" (polygon) is a count, not a lock. */ + private applyLock(key: string, v: number): void { + if (key === "sides") { + memory.sides = Math.max(3, Math.min(64, Math.round(v))); + this.updateMenu(); + this.app.ui.updatePanelValues([memory.sides]); + } else this.locks[key] = v; + this.refreshPreview(); + } + + private lineDim: DimWidget | null = null; + + /** Length of the line being drawn: dimension line with arrows + a box you can type into. */ + private showLineDim(a: Vec2, b: Vec2): void { + const plane = this.plane!; + const len = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (len < 1e-9) return this.hideLineDim(); + const w = (q: Vec2) => sketchToWorld(plane, q, 0.02).toArray() as Vec3; + this.lineDim ??= new DimWidget(this.app.view, { + solidColor: 0xffc23d, + boxAt: "side", + value: len, + onInput: (v) => { + if (v <= 0) return; + this.locks.len = v; + this.typedThisShape = true; + this.refreshPreview(); + }, + onCommit: () => this.placeTyped(), + }); + this.lineDim.set(w(a), w(b)); + if (this.typing.active) this.lineDim.setText(`${this.typing.text}`); + else this.lineDim.setValue(len); + } + + private hideLineDim(): void { + this.lineDim?.dispose(); + this.lineDim = null; + } + + /** Enter after typing a size: place the point at that size. */ + private placeTyped(): void { + this.lockIndex = 0; + this.typedThisShape = false; + this.typing.reset(); + if (this.cursor) this.addPoint(this.cursor.uv, 1); + this.setHint(); + } + + private drawGhosts(es: SketchEntity[], color = 0xffc23d): void { + for (const e of es) { + for (const poly of entityPolylines(e)) { + const line = new Line(new BufferGeometry().setFromPoints(poly.map((q) => sketchToWorld(this.plane!, q, 0.02))), new LineBasicMaterial({ color, depthTest: false })); + line.renderOrder = 9; + this.addOverlay(line); + } + } + this.app.view.requestRender(); + } + + private addOverlay(o: Line | Points): void { + this.overlays.push(o); + this.app.view.overlay.add(o); + } + + private clearOverlays(): void { + for (const o of this.overlays) { + this.app.view.overlay.remove(o); + o.geometry.dispose(); + } + this.overlays = []; + this.app.view.requestRender(); + } + + private screenDist(a: Vec2, b: Vec2): number { + const sa = this.app.view.toScreen(sketchToWorld(this.plane!, a)); + const sb = this.app.view.toScreen(sketchToWorld(this.plane!, b)); + return sa && sb ? Math.hypot(sa[0] - sb[0], sa[1] - sb[1]) : Infinity; + } + + // ------------------------------------------------------------- commits + + /** Save curves (and constraints); constraints on deleted curves are dropped. */ + /** Name of the step being committed (else it's named after the tool). */ + private opLabel: string | null = null; + + /** The step a commit records in the sketch's log. */ + private stepName(entities: SketchEntity[], constraints: SketchConstraint[]): string { + if (this.opLabel) return this.opLabel; + if (JSON.stringify(entities) === JSON.stringify(this.entities)) return JSON.stringify(constraints) === JSON.stringify(this.constraints) ? "Edit" : "Constraint"; + const k = this.kind; + if (k === "trim") return memory.trim === "join" ? "Join lines" : "Trim"; + if (k === "select") return entities.length < this.entities.length ? "Delete" : "Edit"; + if (k === "text") return "Text"; + return titleOf(k); + } + + private commit(entities: SketchEntity[], constraints: SketchConstraint[] = this.constraints): void { + const store = this.app.store; + const ids = new Set(entities.map((e) => e.id)); + const cs = constraints.filter((c) => refsOf(c).every((id) => ids.has(id))); + // One line per step in History (repeats of the same step are counted). + const op = this.stepName(entities, constraints); + this.opLabel = null; + const log = [...(this.sketch?.log ?? [])]; + const last = log[log.length - 1]; + if (last?.op === op) log[log.length - 1] = { op, n: last.n + 1 }; + else log.push({ op, n: 1 }); + const patch = cs.length ? { entities, constraints: cs, log } : { entities, constraints: undefined, log }; + if (this.sketchId && this.sketch) { + store.update(this.sketchId, patch); + } else { + const f: SketchFeature = { ...store.newIdentity("sketch"), type: "sketch", plane: this.plane!, attachedTo: this.attachedTo, ...patch }; + store.add(f); + this.sketchId = f.id; + } + this.refreshConstraintUI(); + // Tools with nothing to set show the step just done. + if (["trim", "extend", "split", "align", "delete", "project"].includes(this.kind)) this.updatePanel(); + } + + private commitAdd(es: SketchEntity[], cs: SketchConstraint[] = []): void { + this.commit([...this.entities, ...es.map((e) => (this.construction ? { ...e, construction: true } : e))], [...this.constraints, ...cs]); + } + + private async commitText(): Promise { + if (!this.pts.length || !this.text.trim()) return; + const es = await textEntities(this.text, this.pts[0], memory.textSize); + this.commitAdd(es); + this.resetDrawing(); + } + + // --------------------------------------------------------- edit tools + + private isSelectionTool(): boolean { + return ["move", "scale", "patternLinear", "patternCircular", "rotate", "mirror"].includes(this.kind); + } + + private curveAt(p: ToolPointer): { id: string; uv: Vec2 } | null { + const hit = this.app.view.pick(p.x, p.y, { curves: this.sketchId ?? true, profiles: false, bodies: false, planes: false, axes: false, edgeTolPx: p.tol }); + // A point (end, centre…) stands for its curve here — small shapes are mostly points when zoomed out. + if ((hit?.kind !== "curve" && hit?.kind !== "point") || hit.sketch !== this.sketchId) return null; + const w = this.app.view.rayToPlane(p.x, p.y, this.plane!); + return { id: hit.entity, uv: w ? toPlane(this.plane!, w) : [0, 0] }; + } + + /** + * Extend in two taps: the half of the first curve, then the half of the + * second — both picked ends run along their own line/circle until they meet. + */ + private tapAlign(id: string): void { + const all = [...this.entities, ...this.boundary]; + const e = all.find((x) => x.id === id); + if (e?.kind !== "line") return this.app.ui.toast("Align works on lines"); + const first = this.edit.alignFrom; + if (!first) { + if (id.startsWith("bnd-")) return this.app.ui.toast("Pick a line of this sketch to move (face edges stay)"); + this.edit.alignFrom = id; + this.app.setSelection([{ kind: "curve", sketch: this.sketchId ?? "", entity: id }]); + return this.setHint("Now tap the line it should line up with."); + } + this.edit.alignFrom = undefined; + this.app.setSelection([]); + this.setHint(); + if (first === id) return; + const next = alignLine(this.entities, first, e); + if (!next) return this.app.ui.toast("Those lines can't be aligned"); + // Constraints that held the old position would pull it back: keep the rest. + const moved = new Set(next.filter((x, i) => x !== this.entities[i]).map((x) => x.id)); + this.commit(next, this.constraints.filter((c) => c.type === "coincident" || c.type === "horizontal" || c.type === "vertical" || !refsOf(c).some((r) => moved.has(r)))); + } + + /** Trim's Join mode: a line and the line on its axis it touches become one. */ + private tapJoin(id: string, uv: Vec2): void { + if (id.startsWith("bnd-")) return this.app.ui.toast("Face edges can't be joined"); + const out = joinCollinear(this.entities, id, uv); + if (!out) return this.app.ui.toast("No line on the same axis touches this one"); + const joined = out.entities.find((x) => x.id === id)!; + const old = new Map(this.entities.map((x) => [x.id, x])); + const ends = [["a", (joined as { a: Vec2 }).a], ["b", (joined as { b: Vec2 }).b]] as const; + const tol = 1e-6 * (1 + Math.hypot(...((joined as { a: Vec2 }).a))); + // Point constraints follow the outer ends; ones at the old joint go. + const cons: SketchConstraint[] = []; + for (const c of this.constraints) { + if (c.curves?.some((x) => x === out.removed) || (c.type === "dim" && c.curves?.includes(id))) continue; + let ok = true; + const pts = (c.pts ?? []).map((r) => { + if (r.e !== id && r.e !== out.removed) return r; + const at = pointOf(old.get(r.e)!, r.p); + const end = at && ends.find(([, q]) => Math.hypot(q[0] - at[0], q[1] - at[1]) < tol); + if (!end) ok = false; + return end ? { e: id, p: end[0] } : r; + }); + if (!ok) continue; + // Both points now on the same line end: nothing left to hold together. + if (pts.length === 2 && pts[0].e === pts[1].e && pts[0].p === pts[1].p) continue; + cons.push(c.pts ? { ...c, pts } : c); + } + this.commit(out.entities, cons); + } + + private tapExtend(id: string, uv: Vec2): void { + const first = this.edit.extendFrom; + const all = [...this.entities, ...this.boundary]; + if (!first) { + const e = all.find((x) => x.id === id); + if (!e || !endNear(e, uv)) return this.app.ui.toast("Pick a line, an arc or an open spline"); + this.edit.extendFrom = { id, at: uv }; + this.app.setSelection([{ kind: "curve", sketch: this.sketchId ?? "", entity: id }]); + this.setHint("Now tap the half of the curve it should meet (or the same half again to extend to the next curve)."); + return; + } + this.edit.extendFrom = undefined; + this.app.setSelection([]); + this.setHint(); + const a = all.find((x) => x.id === first.id); + const b = all.find((x) => x.id === id); + const endA = a && endNear(a, first.at); + const endB = b && endNear(b, uv); + // Same half twice: the old one-tap extend, to the next curve in the way. + if (first.id === id && endA === endB) { + const next = extend(all, id, uv); + if (next) this.commit(this.withoutBoundary(next)); + else this.app.ui.toast("Nothing to extend to"); + return; + } + const next = joinEnds(all, first, { id, at: uv }); + if (!next) return this.app.ui.toast("These can't meet (parallel, or the circles don't cross)"); + const closed = next.find((x) => x.id === first.id)?.kind === "circle"; + // The ends now touch: keep them together. + const keep = + !closed && endA && endB && !first.id.startsWith("bnd-") && !id.startsWith("bnd-") + ? [...this.constraints, { id: uid(), type: "coincident" as const, pts: [{ e: first.id, p: endA }, { e: id, p: endB }] }] + : this.constraints; + this.commit(this.withoutBoundary(next), keep); + } + + /** + * Camera turned away from the sketch view: tapping a closed region (not a + * curve) finishes the sketch and selects that region, with its extrude arrow + * ready to drag. + */ + private tapSurfaceIn3D(p: ToolPointer): boolean { + const view = this.app.view; + const facing = Math.abs(dot(view.cam.viewDir().toArray() as Vec3, this.plane!.normal)); + if (facing > 0.995 || this.curveAt(p)) return false; + const hit = view.pick(p.x, p.y, { profiles: true, curves: false, bodies: false, planes: false, axes: false, images: false, edgeTolPx: p.tol }); + if (hit?.kind !== "profile") return false; + this.app.setTool(null); + this.app.setSelection([{ kind: "profile", sketch: hit.sketch, region: hit.region }]); + return true; + } + + /** Modify tools: a tap on a curve uses it; on empty space it cancels, then goes back to Select. */ + private tapCurve(p: ToolPointer, fn: (id: string, uv: Vec2) => void): void { + const c = this.curveAt(p); + if (c) return fn(c.id, c.uv); + this.tapEmpty(); + } + + private tapEmpty(): void { + if (this.edit.extendFrom || this.edit.alignFrom || this.edit.filletFrom || this.edit.offsetOf) { + this.edit.extendFrom = this.edit.alignFrom = this.edit.filletFrom = this.edit.offsetOf = undefined; + this.clearPreviewJoin(); + this.app.setSelection([]); + this.setHint(); + this.updatePanel(); + this.refreshPreview(); + return; + } + this.setKind("select"); + } + + /** Dashed preview of what the second Extend/Fillet pick would make. */ + private previewJoin(c: { id: string; uv: Vec2 } | null): void { + this.clearPreviewJoin(); + const first = this.kind === "extend" ? this.edit.extendFrom : this.kind === "fillet" ? this.edit.filletFrom : undefined; + if (!first || !c || !this.plane) return; + const all = [...this.entities, ...this.boundary]; + const next = this.kind === "extend" ? joinEnds(all, first, { id: c.id, at: c.uv }) : filletEnds(all, first, { id: c.id, at: c.uv }, memory.fillet); + if (!next) return; + const old = new Map(all.map((e) => [e.id, JSON.stringify(e)])); + const changed = next.filter((e) => old.get(e.id) !== JSON.stringify(e)); + const wpp = this.app.view.cam.worldPerPixel(this.app.view.height); + for (const e of changed) + for (const poly of entityPolylines(e)) { + const line = new Line(new BufferGeometry().setFromPoints(poly.map((q) => sketchToWorld(this.plane!, q, 0.03))), new LineDashedMaterial({ color: 0x4fd18b, dashSize: wpp * 6, gapSize: wpp * 4, depthTest: false })); + line.computeLineDistances(); + line.renderOrder = 10; + this.joinPreview.push(line); + this.app.view.overlay.add(line); + } + this.app.view.requestRender(); + } + + private joinPreview: Line[] = []; + + private clearPreviewJoin(): void { + for (const l of this.joinPreview) { + this.app.view.overlay.remove(l); + l.geometry.dispose(); + } + if (this.joinPreview.length) this.app.view.requestRender(); + this.joinPreview = []; + } + + /** Split: cut a line/arc at its midpoint (Shift: where tapped). The pieces stay joined. */ + private tapSplit(id: string, uv: Vec2, atTap: boolean): void { + const newId = uid(); + const next = splitEntity(this.entities, id, newId, atTap ? uv : undefined); + if (!next) return this.app.ui.toast("Split works on lines and arcs"); + const cs = this.constraints.flatMap((c): SketchConstraint[] => { + // A length dimension no longer fits half a line. + if (c.type === "dim" && c.curves?.[0] === id && c.prop === "length") return []; + // The far end now belongs to the second piece. + const pts = c.pts?.map((r) => (r.e === id && r.p === "b" ? { e: newId, p: "b" } : r)); + return [{ ...c, ...(pts ? { pts } : {}) }]; + }); + cs.push({ id: uid(), type: "coincident", pts: [{ e: id, p: "b" }, { e: newId, p: "a" }] }); + this.commit(next, cs); + } + + private tapSelect(p: ToolPointer, count = 1): void { + if (this.selConstraint) this.deselectConstraint(); + // Points can be picked in the Select tool (for constraints and dragging) — but a + // double tap is always "the whole shape", even when it lands near a corner. + if (this.kind === "select" && count < 2) { + const hit = this.app.view.pick(p.x, p.y, { curves: this.sketchId ?? true, profiles: false, bodies: false, planes: false, axes: false, images: false, edgeTolPx: p.tol }); + if (hit?.kind === "point" && hit.sketch === this.sketchId) { + const r = { e: hit.entity, p: hit.p }; + const i = this.selPts.findIndex((x) => refKey(x) === refKey(r)); + if (i >= 0) this.selPts.splice(i, 1); + else (this.selPts.push(r), this.pickSeq.set(refKey(r), ++this.seq)); + return this.selectionChanged(); + } + } + const c = this.curveAt(p); + // Mirror: with something selected, the next line tapped (even one of the + // selection) is the mirror axis — Shift+tap adds to the selection instead. + if (c && this.kind === "mirror" && this.selected.size && !p.shift && count < 2) { + const e = [...this.entities, ...this.boundary].find((x) => x.id === c.id); + if (e?.kind !== "line") return this.app.ui.toast("The mirror axis must be a straight line"); + this.edit.mirrorLine = [e.a, e.b]; + return this.applyTransform(); + } + // Double tap (or Mirror's first tap): the whole shape the curve belongs to (joined end to end). + if (c && (count >= 2 || (this.kind === "mirror" && !this.selected.size && !p.shift))) { + const chain = connectedChain(this.entities, c.id); + for (const l of chain?.links ?? [{ id: c.id }]) if (!this.selected.has(l.id)) (this.selected.add(l.id), this.pickSeq.set(l.id, ++this.seq)); + return this.selectionChanged(); + } + if (!c) { + // Empty space: deselect; with nothing selected, an editing tool goes back to Select. + if (this.selected.size || this.selPts.length) this.clearSelection(); + else if (this.kind !== "select") this.setKind("select"); + return; + } + if (this.selected.has(c.id)) this.selected.delete(c.id); + else (this.selected.add(c.id), this.pickSeq.set(c.id, ++this.seq)); + this.selectionChanged(); + } + + private selectionChanged(): void { + this.updateMenu(); + this.refreshDistanceDim(); + this.showSelection(); + this.updatePanel(); + this.refreshPreview(); + this.refreshConstraintUI(); + } + + private clearSelection(): void { + this.selected.clear(); + this.selPts = []; + this.selectionChanged(); + } + + private showSelection(): void { + if (!this.sketchId) return; + this.app.setSelection([ + ...[...this.selected].map((entity) => ({ kind: "curve" as const, sketch: this.sketchId!, entity })), + ...this.selPts.map((r) => ({ kind: "point" as const, sketch: this.sketchId!, entity: r.e, p: r.p })), + ]); + this.refreshGimbal(); + } + + private deleteSelected(): void { + const ids = this.selected; + this.commit(this.entities.filter((e) => !ids.has(e.id))); + this.clearSelection(); + } + + private pickForEdit(p: ToolPointer): void { + if (this.edit.picking === "pivot") { + const s = this.snap(p); + if (s) this.edit.pivot = s.uv; + } else if (this.edit.picking === "mirror") { + const c = this.curveAt(p); + const e = c && this.entities.find((x) => x.id === c.id); + if (e?.kind === "line") this.edit.mirrorLine = [e.a, e.b]; + else { + // Or a world axis lying in the sketch plane (X/Y on the ground, …). + const hit = this.app.view.pick(p.x, p.y, { curves: false, profiles: false, bodies: false, planes: false, axes: true, worldAxes: true, edgeTolPx: p.tol }); + const ax = hit?.kind === "axis" ? this.app.view.axisOf(hit.id) : undefined; + const plane = this.plane!; + if (!ax || Math.abs(dot(ax.plane.normal, plane.normal)) > 1e-6) return this.app.ui.toast("Pick a straight line or an axis in the sketch plane"); + const o = ax.plane.origin; + const d = ax.plane.normal; + this.edit.mirrorLine = [toPlane(plane, o), toPlane(plane, [o[0] + d[0], o[1] + d[1], o[2] + d[2]])]; + } + } + this.edit.picking = undefined; + this.updatePanel(); + this.refreshPreview(); + } + + /** Copies/moved versions of the selection for the current transform tool. */ + private transformed(preview: boolean): SketchEntity[] { + const sel = this.entities.filter((e) => this.selected.has(e.id)); + const pivot = this.edit.pivot ?? [0, 0]; + const deg = (this.edit.angle * Math.PI) / 180; + const out: SketchEntity[] = []; + switch (this.kind) { + case "move": { + const c = centroidOf(sel); + const rot = (this.edit.moveRot * Math.PI) / 180; + for (const e of sel) out.push(transformEntity(transformEntity(e, rotateXf(c, rot), !preview && this.edit.copy), translateXf(this.edit.dx, this.edit.dy))); + break; + } + case "scale": { + const c = centroidOf(sel); + for (const e of sel) out.push(transformEntity(e, scaleXf(c, this.edit.factor), !preview && this.edit.copy)); + break; + } + case "patternLinear": + for (let k = 1; k < this.edit.count; k++) for (const e of sel) out.push(transformEntity(e, translateXf(this.edit.dx * k, this.edit.dy * k), true)); + break; + case "patternCircular": { + const full = Math.abs(Math.abs(this.edit.patAngle) - 360) < 1e-6; + const step = ((this.edit.patAngle * Math.PI) / 180) / (full ? this.edit.count : Math.max(1, this.edit.count - 1)); + for (let k = 1; k < this.edit.count; k++) for (const e of sel) out.push(transformEntity(e, rotateXf(pivot, step * k), true)); + break; + } + case "rotate": + for (const e of sel) out.push(transformEntity(e, rotateXf(pivot, deg), !preview && this.edit.copy)); + break; + case "mirror": + if (this.edit.mirrorLine) for (const e of sel) out.push(transformEntity(e, mirrorXf(...this.edit.mirrorLine), !preview && this.edit.mirrorCopy)); + break; + } + return out; + } + + private applyTransform(): void { + if (!this.selected.size) return this.app.ui.toast("Select curves first"); + if (this.kind === "patternCircular" && !this.edit.pivot) return this.app.ui.toast("Tap the centre of the pattern first"); + if (this.kind === "mirror" && !this.edit.mirrorLine) return this.app.ui.toast("Pick the mirror line"); + let results = this.transformed(false); + // Mirroring across one of the shape's own edges: that edge maps onto itself — don't double it. + const ml = this.edit.mirrorLine; + if (this.kind === "mirror" && ml) { + const d: Vec2 = [ml[1][0] - ml[0][0], ml[1][1] - ml[0][1]]; + const L = Math.hypot(...d) || 1; + const onAxis = (q: Vec2) => Math.abs((q[0] - ml[0][0]) * d[1] - (q[1] - ml[0][1]) * d[0]) / L < 1e-7 * Math.max(1, L); + results = results.filter((e) => !(e.kind === "line" && onAxis(e.a) && onAxis(e.b))); + } + const keepOriginals = this.kind === "patternLinear" || this.kind === "patternCircular" || ((this.kind === "mirror" ? this.edit.mirrorCopy : this.edit.copy)); + const base = keepOriginals ? this.entities : this.entities.filter((e) => !this.selected.has(e.id)); + this.commit([...base, ...results]); + if (!keepOriginals) { + this.selected = new Set(results.map((e) => e.id)); + this.showSelection(); + } + this.refreshPreview(); + } + + /** New curves the offset would add (one curve, or the whole chain in Chain mode). */ + private offsetResult(): SketchEntity[] { + const id = this.edit.offsetOf; + const src = this.entities.find((e) => e.id === id); + if (!id || !src) return []; + if (memory.offsetMode === "chain" && (src.kind === "line" || src.kind === "arc" || (src.kind === "spline" && !src.closed))) { + const all = offsetChain(this.entities, id, memory.offset); + if (all) return all.slice(this.entities.length); + } + const o = offsetEntity(src, memory.offset); + return o ? [o] : []; + } + + private applyOffset(): void { + const made = this.offsetResult(); + if (!made.length) return this.app.ui.toast("That offset would collapse the curve"); + // Chain pieces stay joined to each other. + const cs: SketchConstraint[] = []; + for (let i = 0; i < made.length; i++) { + const a = made[i]; + const b = made[(i + 1) % made.length]; + if (made.length > 1 && (a.kind === "line" || a.kind === "arc") && (b.kind === "line" || b.kind === "arc") && Math.hypot(a.b[0] - b.a[0], a.b[1] - b.a[1]) < 1e-9) + cs.push({ id: uid(), type: "coincident", pts: [{ e: a.id, p: "b" }, { e: b.id, p: "a" }] }); + } + this.commitAdd(made, cs); + this.edit.offsetOf = undefined; + this.resetDrawing(); + } + + /** + * Fillet like Extend: tap the halves of two lines (they needn't touch) — or + * tap right on a corner. The rounded corner appears; type its radius, Enter. + */ + private tapFillet(p: ToolPointer): void { + if (this.filletEdit) return this.finishFillet(); + const w = this.app.view.rayToPlane(p.x, p.y, this.plane!); + if (!w) return; + const uv = toPlane(this.plane!, w); + const tol = this.app.view.cam.worldPerPixel(this.app.view.height) * p.tol * 1.5; + const base = this.entities; + if (!this.edit.filletFrom) { + // Right on a corner (two curve ends meet there): round it directly. + const ends = base.flatMap(guidePoints).filter((g) => g.kind === "end"); + const corner = ends.reduce<{ p: Vec2; d: number } | null>((best, g) => { + const d = Math.hypot(g.p[0] - uv[0], g.p[1] - uv[1]); + const meets = ends.filter((h) => Math.hypot(h.p[0] - g.p[0], h.p[1] - g.p[1]) < 1e-6).length >= 2; + return meets && d < tol && (!best || d < best.d) ? { p: g.p, d } : best; + }, null); + if (corner) return this.startFillet((r) => filletCorner(base, corner.p, r, tol * 0.01 + 1e-6)); + const c = this.curveAt(p); + if (!c) return this.tapEmpty(); + if (base.find((x) => x.id === c.id)?.kind !== "line") return this.app.ui.toast("Pick a line (or tap a corner)"); + this.edit.filletFrom = { id: c.id, at: c.uv }; + this.app.setSelection([{ kind: "curve", sketch: this.sketchId ?? "", entity: c.id }]); + return this.setHint("Now tap the half of the other line."); + } + const first = this.edit.filletFrom; + const c = this.curveAt(p); + if (!c) return this.tapEmpty(); + this.edit.filletFrom = undefined; + this.clearPreviewJoin(); + this.app.setSelection([]); + this.startFillet((r) => filletEnds(base, first, { id: c.id, at: c.uv }, r)); + } + + private filletEdit: { make: (r: number) => SketchEntity[] | null; widget: DimWidget; base: SketchEntity[]; baseIds: Set } | null = null; + + /** Show the fillet with the last radius and a focused radius box to type into. */ + private startFillet(make: (r: number) => SketchEntity[] | null): void { + if (!make(memory.fillet)) return this.app.ui.toast("Can't fillet these (radius too big, parallel, or not two lines)"); + const widget = new DimWidget(this.app.view, { + value: memory.fillet, + boxAt: "beyond", + focus: true, + onInput: (v) => v > 0 && this.applyFillet(v), + onCommit: () => this.finishFillet(), + }); + this.filletEdit = { make, widget, base: this.entities, baseIds: new Set(this.entities.map((e) => e.id)) }; + this.applyFillet(memory.fillet); + this.setHint("Type the radius, then Enter (or tap anywhere)."); + } + + private applyFillet(r: number): void { + const fe = this.filletEdit; + const next = fe?.make(r); + // Too big for these lines: keep the last good fillet, show the value in red. + fe?.widget.markInvalid(!next); + if (!fe || !next || !this.sketchId) return; + memory.fillet = r; + const id = this.sketchId; + this.app.store.transient((doc) => { + const f = doc.features.find((x) => x.id === id); + if (f?.type === "sketch") f.entities = next; + }); + // The radius dimension runs from the new arc's centre to its middle. + const arc = next.find((e) => e.kind === "arc" && !fe.baseIds.has(e.id)); + if (arc?.kind === "arc") { + const c = arcFrom3(arc.a, arc.m, arc.b); + if (c) fe.widget.set(sketchToWorld(this.plane!, c.c).toArray() as Vec3, sketchToWorld(this.plane!, arc.m).toArray() as Vec3); + } + } + + /** Esc: drop the fillet being sized. */ + private cancelFillet(): void { + const fe = this.filletEdit; + if (!fe) return; + this.filletEdit = null; + fe.widget.dispose(); + this.commit(fe.base); + this.setHint(); + } + + private finishFillet(): void { + const fe = this.filletEdit; + if (!fe) return; + this.filletEdit = null; + fe.widget.dispose(); + // One undo step for the whole fillet; the arc stays tangent and joined to its lines. + this.commit(this.entities, filletConstraints(this.entities, this.constraints, fe.baseIds)); + this.setHint(); + } + + /** Last curve of another sketch projected (a second tap on it brings the whole sketch). */ + private projectedFrom: { sketch: string; entity: string; at: number } | null = null; + + /** Curves of another sketch → this sketch's plane (straight across, or squashed if tilted). */ + private projectCurves(sketch: string, entities: SketchEntity[]): SketchEntity[] { + const from = this.app.sketchPlane(sketch); + const to = this.plane!; + if (!from) return []; + if (Math.abs(dot(from.normal, to.normal)) > 1 - 1e-9) { + // Parallel planes: the same shapes, moved (and turned) into this plane. + return entities.map((e) => transformEntity(e, (uv) => toPlane(to, sketchToWorld(from, uv).toArray() as Vec3), true)); + } + return entities.flatMap((e) => + entityPolylines(e).flatMap((pl) => { + const out = projectPolyline(pl.map((uv) => sketchToWorld(from, uv).toArray() as Vec3), to, e.kind === "line" ? "LINE" : ""); + return out ? [out] : []; + }), + ); + } + + private tapProject(p: ToolPointer): void { + const hit = this.app.view.pick(p.x, p.y, { profiles: false, planes: false, axes: false, edgeTolPx: p.tol }); + if (hit?.kind === "curve" && hit.sketch !== this.sketchId) { + const all = this.app.sketchCurves(hit.sketch).filter((e) => !e.id.startsWith("bnd-") && !e.construction); + const last = this.projectedFrom; + if (last && last.sketch === hit.sketch && Date.now() - last.at < 450) { + // Double tap: the rest of that sketch too (e.g. a whole text). + this.projectedFrom = null; + this.commitAdd(this.projectCurves(hit.sketch, all.filter((e) => e.id !== last.entity))); + return this.app.ui.toast("Projected the whole sketch"); + } + const one = all.filter((e) => e.id === hit.entity); + if (!one.length) return; + this.projectedFrom = { sketch: hit.sketch, entity: hit.entity, at: Date.now() }; + this.commitAdd(this.projectCurves(hit.sketch, one)); + return this.app.ui.toast("Double-tap a curve to project its whole sketch"); + } + if (hit?.kind !== "edge") return this.app.ui.toast("Tap a body edge or a curve of another sketch"); + const b = this.app.view.body(hit.body); + const g = b?.edgeGroups.find((x) => x.edge === hit.edge); + if (!b || !g) return; + const pts: [number, number, number][] = []; + for (let i = g.start; i < g.start + g.count; i++) { + // Segment pairs: take the first point of each pair plus the very last point. + if ((i - g.start) % 2 === 0 || i === g.start + g.count - 1) pts.push([b.edgePositions[i * 3], b.edgePositions[i * 3 + 1], b.edgePositions[i * 3 + 2]]); + } + const e = projectPolyline(pts, this.plane!, b.edges[hit.edge].type); + if (e) this.commitAdd([e]); + } + + // ------------------------------------------------- single-entity sizes + + private showSizePanel(): void { + const id = [...this.selected][0]; + let e = this.entities.find((x) => x.id === id); + if (!e) return; + const set = (patch: Partial) => { + this.commit(this.entities.map((x) => (x.id === id ? ({ ...x, ...patch } as SketchEntity) : x))); + e = this.entities.find((x) => x.id === id) ?? e; + }; + const items: PanelItem[] = []; + // Sizes are driving dimensions: they show on the sketch and can use variables (ƒx). + let pending: string | null = null; + const dimField = (label: string, prop: string, kind: "length" | "angle" = "length"): PanelItem => { + const d = dimOf(this.constraints, id, prop); + return { + type: "number", + label, + value: d?.value ?? sizeOfEntity(e!, prop), + kind, + min: kind === "length" ? 0.0001 : undefined, + expr: d?.expr, + onExpr: (x) => (pending = x), + onInput: (v) => { + const expr = pending && isExpression(pending) ? pending : null; + pending = null; + // A diameter replaces a radius dimension (and axis lengths the half-axes), never both. + const replaced: Record = { diameter: "radius", dx: "rx", dy: "ry" }; + const base = this.constraints.filter((c) => !(c.type === "dim" && c.curves?.[0] === id && c.curves.length === 1 && c.prop === replaced[prop])); + this.commit(this.entities, setDim(base, id, prop, v, expr)); + if (this.app.store.problems.length) this.app.ui.toast(this.app.store.problems[0], "error"); + }, + }; + }; + switch (e.kind) { + case "line": + items.push(dimField("Length", "length"), dimField("Angle", "angle", "angle")); + break; + case "rect": + items.push( + dimField("Width", "w"), + dimField("Height", "h"), + { type: "number", label: "Angle", value: (e.rotation * 180) / Math.PI, kind: "angle", onInput: (v) => set({ rotation: (v * Math.PI) / 180 }) }, + ); + break; + case "circle": + items.push(dimField("Diameter", "diameter")); + break; + case "ellipse": + items.push(dimField("Length", "dx"), dimField("Width", "dy")); + break; + case "polygon": + items.push(dimField("Radius", "radius"), { type: "number", label: "Sides", value: e.sides, kind: "int", min: 3, onInput: (v) => set({ sides: Math.max(3, Math.min(64, v)) }) }); + break; + case "arc": + items.push(dimField("Radius", "radius")); + break; + } + items.push( + { type: "toggle", label: "Construction", value: !!e.construction, onChange: () => this.toggleConstruction() }, + ...(e.kind === "rect" || e.kind === "polygon" ? [{ type: "button", label: "Explode", icon: "line", onClick: () => this.commit(this.entities.flatMap((x) => (x.id === id ? explode(x) : [x]))) } as PanelItem] : []), + { type: "button", label: "Delete", icon: "trash", onClick: () => this.deleteSelected() }, + ); + this.app.ui.showPanel({ title: titleOf(e.kind as Kind), items, onDone: () => this.clearSelection() }); + } +} + +function titleOf(k: string): string { + const t: Record = { patternLinear: "Pattern – Linear", patternCircular: "Pattern – Circular", rotate: "Rotate Around Axis", rect: "Rectangle", offset: "Offset Edge", polyline: "Outline" }; + return t[k] ?? k[0].toUpperCase() + k.slice(1); +} + +function sizeOfEntity(e: SketchEntity, prop: string): number { + return sizeOfFn(e, prop) ?? 0; +} + +function samePt(a: Vec2, b: Vec2): boolean { + return Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9; +} + +function centroidOf(es: SketchEntity[]): Vec2 { + const pts = es.flatMap((e) => guidePoints(e).map((g) => g.p)); + if (!pts.length) return [0, 0]; + return [pts.reduce((s, p) => s + p[0], 0) / pts.length, pts.reduce((s, p) => s + p[1], 0) / pts.length]; +} + +function dimLabel(e: SketchEntity | null, pts: Vec2[]): string | null { + if (!e) return null; + switch (e.kind) { + case "line": { + const [a, b] = [e.a, e.b]; + return fmtLen(Math.hypot(b[0] - a[0], b[1] - a[1])); + } + case "rect": + return `${fmtLen(e.w)} × ${fmtLen(e.h)}`; + case "circle": + return `⌀ ${fmtLen(2 * e.radius)}`; + case "polygon": + return `R ${fmtLen(e.radius)} · ${e.sides} sides (Tab)`; + case "ellipse": + return `${fmtLen(2 * e.rx)} × ${fmtLen(2 * e.ry)}`; + case "arc": { + const c = arcFrom3(e.a, e.m, e.b); + return c ? `R ${fmtLen(c.r)}` : null; + } + default: + return pts.length ? `${pts.length} points` : null; + } +} diff --git a/src/tools/sketchConstraints.ts b/src/tools/sketchConstraints.ts new file mode 100644 index 0000000..95e1da7 --- /dev/null +++ b/src/tools/sketchConstraints.ts @@ -0,0 +1,240 @@ +// Sketch constraint UI: the constraint button column, building constraints from +// the selection, and the badges/dimension labels drawn next to the geometry. + +import type { ConstraintType, PlaneDef, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types"; +import { applicable, pointOf, pointsOf, sizeOf } from "../sketch/constraints"; +import { arcFrom3 } from "../sketch/curves"; +import { uid } from "../sketch/edit"; +import { el } from "../ui/ui"; +import { fmtLen, trim } from "../units"; +import type { Viewport } from "../view/viewport"; +import { sketchToWorld } from "../view/viewport"; + +export const CONSTRAINT_BUTTONS: { type: ConstraintType | "hv"; label: string; glyph: string; key: string }[] = [ + { type: "parallel", label: "Parallel", glyph: "∥", key: "A" }, + { type: "perpendicular", label: "Perpendicular", glyph: "⟂", key: "P" }, + { type: "tangent", label: "Tangent", glyph: "T", key: "T" }, + { type: "coincident", label: "Coincident", glyph: "●", key: "N" }, + { type: "midpoint", label: "Midpoint", glyph: "M", key: "M" }, + { type: "concentric", label: "Concentric", glyph: "◎", key: "C" }, + { type: "hv", label: "Horizontal/Vertical", glyph: "H/V", key: "V" }, + { type: "equal", label: "Equal", glyph: "=", key: "E" }, + { type: "symmetric", label: "Symmetry", glyph: "⇋", key: "S" }, + { type: "fix", label: "Lock", glyph: "🔒", key: "L" }, + { type: "distance", label: "Distance", glyph: "↔", key: "D" }, +]; + +const GLYPH: Partial> = { + coincident: "●", + horizontal: "H", + vertical: "V", + parallel: "∥", + perpendicular: "⟂", + equal: "=", + tangent: "T", + concentric: "◎", + midpoint: "M", + symmetric: "⇋", + fix: "🔒", +}; + +/** Constraints for a button press, from the current selection (empty if it doesn't fit). */ +export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] { + if (type === "hv") { + if (curves.length === 1 && curves[0].kind === "line" && !pts.length) { + const l = curves[0]; + const horiz = Math.abs(l.b[0] - l.a[0]) >= Math.abs(l.b[1] - l.a[1]); + return [{ id: uid(), type: horiz ? "horizontal" : "vertical", curves: [l.id] }]; + } + return []; + } + if (!applicable(type, pts, curves)) return []; + const ids = curves.map((c) => c.id); + switch (type) { + case "coincident": + return pts.length === 2 ? [{ id: uid(), type, pts }] : [{ id: uid(), type, pts, curves: ids }]; + case "midpoint": + case "symmetric": + return [{ id: uid(), type, pts, curves: ids }]; + case "distance": { + const v = distanceOf(pts, curves); + return v === null ? [] : [{ id: uid(), type, pts, curves: ids.length ? ids : undefined, value: v }]; + } + case "fix": { + // Locking a curve holds all of its points (and a circle's size). + const all = [...pts, ...curves.flatMap((e) => pointsOf(e).map((q) => ({ e: e.id, p: q.p })))]; + const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius }] : [])); + return [...all.map((p) => ({ id: uid(), type, pts: [p] })), ...sizes]; + } + default: + return [{ id: uid(), type, curves: ids }]; + } +} + +/** Current distance between two points, or a point and a line. */ +export function distanceOf(pts: PointRef[], curves: SketchEntity[], all: SketchEntity[] = curves): number | null { + const P = (r: PointRef) => { + const e = all.find((x) => x.id === r.e); + return e ? pointOf(e, r.p) : null; + }; + if (pts.length === 2 && !curves.length) { + const [a, b] = pts.map(P); + return a && b ? Math.hypot(a[0] - b[0], a[1] - b[1]) : null; + } + const l = curves[0]; + const p = pts[0] && P(pts[0]); + if (pts.length === 1 && curves.length === 1 && l.kind === "line" && p) { + const dx = l.b[0] - l.a[0]; + const dy = l.b[1] - l.a[1]; + return Math.abs((p[0] - l.a[0]) * dy - (p[1] - l.a[1]) * dx) / (Math.hypot(dx, dy) || 1); + } + return null; +} + +/** + * Constraints already on the selection for a button: the column shows them + * as on, and tapping the button removes them. + */ +export function existingConstraints(type: ConstraintType | "hv", constraints: SketchConstraint[], pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] { + const ids = new Set(curves.map((e) => e.id)); + const ptKeys = new Set(pts.map((p) => `${p.e}:${p.p}`)); + const types: string[] = type === "hv" ? ["horizontal", "vertical"] : [type]; + // A point counts as selected when it is, or when its curve is. + const ptIn = (p: PointRef) => ptKeys.has(`${p.e}:${p.p}`) || ids.has(p.e); + return constraints.filter((c) => { + if (!types.includes(c.type)) return false; + const cv = c.curves ?? []; + const cp = c.pts ?? []; + if (!cv.length && !cp.length) return false; + if (type === "fix") return cp.every(ptIn); + // Every curve and point it involves is in the selection. + return cv.every((id) => ids.has(id)) && cp.every(ptIn) && (cv.length + cp.length > 1 || ids.size + pts.length === 1); + }); +} + +export function buttonEnabled(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): boolean { + return buildConstraints(type, pts, curves).length > 0; +} + +/** Upsert a driving dimension on one entity (length / radius / w / h / …). */ +export function setDim(list: SketchConstraint[], entity: string, prop: string, value: number, expr?: string | null): SketchConstraint[] { + const i = list.findIndex((c) => c.type === "dim" && c.curves?.[0] === entity && c.curves.length === 1 && c.prop === prop); + const c: SketchConstraint = { id: i >= 0 ? list[i].id : uid(), type: "dim", curves: [entity], prop, value, ...(expr ? { expr } : {}) }; + return i >= 0 ? list.map((x, k) => (k === i ? c : x)) : [...list, c]; +} + +/** The dimension constraint on an entity's property, if any. */ +export function dimOf(list: SketchConstraint[], entity: string, prop: string): SketchConstraint | undefined { + return list.find((c) => c.type === "dim" && c.curves?.[0] === entity && c.curves.length === 1 && c.prop === prop); +} + +/** Badges + dimension labels for the constraints of the sketch being edited. */ +export class ConstraintGlyphs { + private host = el("div", "cglyphs"); + private chips = new Map(); + private hook = () => this.layout(); + private items: { c: SketchConstraint; at: Vec2; off: [number, number] }[] = []; + private plane: PlaneDef | null = null; + selected: string | null = null; + + constructor( + private view: Viewport, + private onClick: (id: string) => void, + ) { + document.body.append(this.host); + view.frameHooks.add(this.hook); + } + + set(plane: PlaneDef, entities: SketchEntity[], constraints: SketchConstraint[]): void { + this.plane = plane; + const get = (id: string) => entities.find((e) => e.id === id); + const mid = (e: SketchEntity): Vec2 | null => { + if (e.kind === "line") return [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2]; + if (e.kind === "arc") return e.m; + if (e.kind === "circle" || e.kind === "ellipse" || e.kind === "rect" || e.kind === "polygon") return e.center; + return e.points[0] ?? null; + }; + this.items = []; + // Several badges at one spot are fanned out so they stay readable. + const counts = new Map(); + for (const c of constraints) { + let at: Vec2 | null = null; + if (c.pts?.length) { + const e = get(c.pts[0].e); + at = e ? pointOf(e, c.pts[0].p) : null; + } else if (c.curves?.length) { + const e = get(c.curves[0]); + at = e ? mid(e) : null; + if (e && c.type === "dim" && (c.prop === "radius" || c.prop === "diameter")) { + const r = e.kind === "circle" ? e.radius : e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.r ?? 0) : e.kind === "polygon" ? e.radius : 0; + const ctr = e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.c ?? at!) : at!; + at = [ctr[0] + r * 0.707, ctr[1] + r * 0.707]; + } + if (e && c.type === "dim" && e.kind === "rect" && (c.prop === "w" || c.prop === "h")) { + const cs = Math.cos(e.rotation); + const sn = Math.sin(e.rotation); + const off = c.prop === "w" ? [0, -e.h / 2] : [e.w / 2, 0]; + at = [e.center[0] + off[0] * cs - off[1] * sn, e.center[1] + off[0] * sn + off[1] * cs]; + } + } + if (!at) continue; + const k = `${at[0].toFixed(4)},${at[1].toFixed(4)}`; + const n = counts.get(k) ?? 0; + counts.set(k, n + 1); + const isDim = c.type === "dim" || c.type === "distance"; + this.items.push({ c, at, off: isDim ? [0, -16] : [14 + n * 18, 12] }); + } + // Sync chips. + const live = new Set(this.items.map((i) => i.c.id)); + for (const [id, chip] of this.chips) if (!live.has(id)) (chip.remove(), this.chips.delete(id)); + for (const { c } of this.items) { + let chip = this.chips.get(c.id); + if (!chip) { + chip = el("button", "cglyph"); + chip.addEventListener("pointerdown", (e) => e.stopPropagation()); + chip.addEventListener("click", (e) => (e.stopPropagation(), this.onClick(c.id))); + this.host.append(chip); + this.chips.set(c.id, chip); + } + chip.className = `cglyph${c.type === "dim" || c.type === "distance" ? " dim" : ""}${c.id === this.selected ? " sel" : ""}${c.expr ? " expr" : ""}`; + chip.textContent = label(c, get); + chip.title = c.type === "dim" ? `${c.prop} dimension${c.expr ? ` = ${c.expr}` : ""} (click to edit)` : `${c.type} (click to select)`; + } + this.layout(); + } + + /** Show or hide all the badges (the "Show constraints" switch). */ + setVisible(on: boolean): void { + this.host.hidden = !on; + } + + private layout(): void { + if (!this.plane) return; + for (const it of this.items) { + const chip = this.chips.get(it.c.id); + if (!chip) continue; + const s = this.view.toScreen(sketchToWorld(this.plane, it.at)); + chip.hidden = !s; + if (s) chip.style.transform = `translate(${Math.round(s[0] + it.off[0])}px, ${Math.round(s[1] + it.off[1])}px) translate(-50%, -50%)`; + } + } + + dispose(): void { + this.view.frameHooks.delete(this.hook); + this.host.remove(); + } +} + +function label(c: SketchConstraint, get: (id: string) => SketchEntity | undefined): string { + if (c.type === "dim") { + const e = c.curves?.[0] ? get(c.curves[0]) : undefined; + const v = c.value ?? (e && c.prop ? sizeOf(e, c.prop) : 0) ?? 0; + const name = c.expr && /[a-z_]/i.test(c.expr) ? `${c.expr} = ` : ""; + if (c.prop === "angle") return `${name}${trim(v, 2)}°`; + if (c.prop === "radius") return `${name}R ${fmtLen(v)}`; + if (c.prop === "diameter") return `${name}⌀ ${fmtLen(v)}`; + return `${name}${fmtLen(v)}`; + } + if (c.type === "distance") return fmtLen(c.value ?? 0); + return GLYPH[c.type] ?? "?"; +} diff --git a/src/tools/slots.ts b/src/tools/slots.ts new file mode 100644 index 0000000..fe42583 --- /dev/null +++ b/src/tools/slots.ts @@ -0,0 +1,278 @@ +// Reusable pick slots: axis, plane, direction, path, faces, profiles. + +import type { AxisRef, EdgeRef, ExtrudeSource, FaceRef, PathRef, PlaneDef, SketchFeature, Vec3 } from "../doc/types"; +import { norm, sub, toWorld } from "../geom"; +import { arrangement, regionRef } from "../sketch/regions"; +import { Vector3 } from "three"; +import type { Slot } from "./featureOp"; +import { edgeRefOf, faceRefOf, type AppContext, type Sel } from "./tool"; + +const WORLD_AXES: { label: string; dir: Vec3 }[] = [ + { label: "X", dir: [1, 0, 0] }, + { label: "Y", dir: [0, 1, 0] }, + { label: "Z", dir: [0, 0, 1] }, +]; + +export function axisSlot(app: AppContext, label: string, get: () => AxisRef | null, set: (a: AxisRef) => void): Slot { + let shown: Sel | null = null; + let name = ""; + return { + label, + describe: () => (get() ? name || "Axis" : "Tap a line, edge or axis"), + filled: () => !!get(), + pick: { profiles: false, curves: true, planes: false, axes: true, worldAxes: true }, + presets: WORLD_AXES.map((a) => ({ label: a.label, apply: () => ((name = `${a.label} axis`), (shown = null), set({ origin: [0, 0, 0], dir: a.dir })) })), + shows: () => (shown ? [shown] : []), + accept(hit) { + if (hit.kind === "curve") { + const s = app.store.find(hit.sketch); + const e = s?.entities.find((x) => x.id === hit.entity); + const plane = app.sketchPlane(hit.sketch); + if (!s || !plane || e?.kind !== "line") return false; + const a = toWorld(plane, e.a); + set({ origin: a, dir: norm(sub(toWorld(plane, e.b), a)), ref: { kind: "sketchLine", sketch: s.id, entity: e.id } }); + name = "Sketch line"; + } else if (hit.kind === "edge") { + const info = app.view.body(hit.body)?.edges[hit.edge]; + if (!info || info.type !== "LINE") return false; + set({ origin: info.start, dir: info.dir }); + name = "Edge"; + } else if (hit.kind === "axis") { + const ax = app.view.axisOf(hit.id); + if (!ax) return false; + // World axes don't move; construction axes are followed by reference. + const world = ["X", "Y", "Z"].includes(hit.id); + set({ origin: ax.plane.origin, dir: ax.plane.normal, ...(world ? {} : { ref: { kind: "axis" as const, feature: hit.id } }) }); + name = ax.name; + } else return false; + shown = { ...hit } as Sel; + delete (shown as { point?: unknown }).point; + return true; + }, + }; +} + +export function planeSlot(app: AppContext, label: string, get: () => PlaneDef | null, set: (p: PlaneDef, face?: FaceRef) => void): Slot { + let shown: Sel | null = null; + let name = ""; + return { + label, + describe: () => (get() ? name || "Plane" : "Tap a plane or flat face"), + originPlanes: true, + rejectHint: "Tap a flat face or a plane (or pick XY / XZ / YZ)", + filled: () => !!get(), + pick: { profiles: false, edges: false, planes: true }, + presets: ["XY", "XZ", "YZ"].map((id) => ({ label: id, apply: () => ((name = `${id} plane`), (shown = null), set(app.view.planeOf(id)!)) })), + shows: () => (shown ? [shown] : []), + accept(hit) { + if (hit.kind === "plane") { + const p = app.view.planeOf(hit.id); + if (!p) return false; + set(p); + name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : "Plane"; + shown = { kind: "plane", id: hit.id }; + return true; + } + if (hit.kind === "face") { + const info = app.view.body(hit.body)?.faces[hit.face]; + if (!info?.plane) return false; + set(info.plane, faceRefOf(app, hit) ?? undefined); + name = "Face"; + shown = { kind: "face", body: hit.body, face: hit.face }; + return true; + } + return false; + }, + }; +} + +/** A direction: an edge, an axis, a face normal, or X/Y/Z. */ +export function directionSlot(app: AppContext, label: string, get: () => Vec3 | null, set: (d: Vec3) => void): Slot { + let shown: Sel | null = null; + let name = ""; + return { + label, + describe: () => (get() ? name || "Direction" : "Tap an edge, axis or face"), + filled: () => !!get(), + pick: { profiles: false, planes: false, axes: true, worldAxes: true }, + presets: WORLD_AXES.map((a) => ({ label: a.label, apply: () => ((name = a.label), (shown = null), set(a.dir)) })), + shows: () => (shown ? [shown] : []), + accept(hit) { + if (hit.kind === "edge") { + const info = app.view.body(hit.body)?.edges[hit.edge]; + if (!info) return false; + set(info.dir); + name = "Edge"; + shown = { kind: "edge", body: hit.body, edge: hit.edge }; + } else if (hit.kind === "face") { + const info = app.view.body(hit.body)?.faces[hit.face]; + if (!info) return false; + set(info.normal); + name = "Face normal"; + shown = { kind: "face", body: hit.body, face: hit.face }; + } else if (hit.kind === "axis") { + const ax = app.view.axisOf(hit.id); + if (!ax) return false; + set(ax.plane.normal); + name = ax.name; + shown = { kind: "axis", id: hit.id }; + } else return false; + return true; + }, + }; +} + +/** Sweep path: sketch curves (one sketch) or body edges. */ +export function pathSlot(app: AppContext, get: () => PathRef | null, set: (p: PathRef) => void): Slot { + return { + label: "Path", + multi: true, + describe: () => { + const p = get(); + if (!p) return "Tap curves or edges"; + return p.kind === "sketch" ? `${p.entities.length} curve${p.entities.length > 1 ? "s" : ""}` : `${p.edges.length} edge${p.edges.length > 1 ? "s" : ""}`; + }, + filled: () => !!get(), + pick: { profiles: false, curves: true, planes: false, axes: false }, + shows: () => { + const p = get(); + if (!p) return []; + if (p.kind === "sketch") return p.entities.map((entity) => ({ kind: "curve", sketch: p.sketch, entity }) as Sel); + return []; + }, + accept(hit) { + const p = get(); + if (hit.kind === "curve") { + if (p?.kind === "sketch" && p.sketch === hit.sketch) { + const has = p.entities.includes(hit.entity); + set({ ...p, entities: has ? p.entities.filter((e) => e !== hit.entity) : [...p.entities, hit.entity] }); + } else set({ kind: "sketch", sketch: hit.sketch, entities: [hit.entity] }); + return true; + } + if (hit.kind === "edge") { + const ref = edgeRefOf(app, hit); + if (!ref) return false; + const edges: EdgeRef[] = p?.kind === "edges" ? [...p.edges, ref] : [ref]; + set({ kind: "edges", edges }); + return true; + } + return false; + }, + }; +} + +/** Faces of one body (e.g. faces to open in Shell). */ +export function facesSlot(app: AppContext, label: string, get: () => FaceRef[], set: (f: FaceRef[]) => void, optional = false): Slot { + const picked: Sel[] = []; + return { + label, + multi: true, + describe: () => (get().length ? `${get().length} face${get().length > 1 ? "s" : ""}` : optional ? "None (closed)" : "Tap faces"), + filled: () => optional || get().length > 0, + pick: { profiles: false, edges: false, planes: false, axes: false }, + shows: () => picked, + accept(hit) { + if (hit.kind !== "face") return false; + const ref = faceRefOf(app, hit); + if (!ref) return false; + const i = picked.findIndex((s) => s.kind === "face" && s.body === hit.body && s.face === hit.face); + if (i >= 0) { + picked.splice(i, 1); + set(get().filter((_, k) => k !== i)); + } else { + picked.push({ kind: "face", body: hit.body, face: hit.face }); + set([...get(), ref]); + } + return true; + }, + }; +} + +/** Profiles / flat faces for loft sections. */ +export function sectionsSlot(app: AppContext, get: () => ExtrudeSource[], set: (s: ExtrudeSource[]) => void, initial: Sel[]): Slot { + const picked: Sel[] = [...initial]; + return { + label: "Profiles", + multi: true, + describe: () => `${get().length} picked${get().length < 2 ? " — tap more" : ""}`, + filled: () => get().length >= 2, + pick: { edges: false, planes: false, axes: false }, + shows: () => picked, + accept(hit) { + if (hit.kind === "profile") { + const r = arrangement(app.sketchCurves(hit.sketch)).regions[hit.region]; + if (!r) return false; + // Tapped again: take it back out. + const i = picked.findIndex((p) => p.kind === "profile" && p.sketch === hit.sketch && p.region === hit.region); + const ref = regionRef(r); + if (i >= 0) { + picked.splice(i, 1); + set(get().filter((s) => !(s.kind === "profile" && s.sketch === hit.sketch && s.regions.length === 1 && Math.hypot(s.regions[0].c[0] - ref.c[0], s.regions[0].c[1] - ref.c[1]) < 1e-6))); + return true; + } + picked.push({ kind: "profile", sketch: hit.sketch, region: hit.region }); + set([...get(), { kind: "profile", sketch: hit.sketch, regions: [ref] }]); + return true; + } + if (hit.kind === "face") { + const ref = faceRefOf(app, hit); + if (!ref || !app.view.body(hit.body)?.faces[hit.face]?.plane) return false; + const i = picked.findIndex((p) => p.kind === "face" && p.body === hit.body && p.face === hit.face); + if (i >= 0) { + picked.splice(i, 1); + set(get().filter((s) => !(s.kind === "face" && s.face.body === ref.body && Math.hypot(...(sub3(s.face.center, ref.center) as [number, number, number])) < 1e-6))); + return true; + } + picked.push({ kind: "face", body: hit.body, face: hit.face }); + set([...get(), { kind: "face", face: ref }]); + return true; + } + return false; + }, + }; +} + +const sub3 = (a: number[], b: number[]) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + +/** + * A point: a corner, a point on an edge (its ends and middle snap), a face + * (its centre snaps), a sketch point or curve, or a plane. + */ +export function pointSlot(app: AppContext, label: string, get: () => Vec3 | null, set: (p: Vec3) => void): Slot { + let shown: Sel | null = null; + return { + label, + describe: () => { + const p = get(); + return p ? p.map((v) => Math.round(v * 1000) / 1000).join(", ") : "Tap a corner, edge, face or point"; + }, + filled: () => !!get(), + pick: { profiles: false, curves: true, planes: true }, + shows: () => (shown ? [shown] : []), + accept(hit) { + let at: Vec3 | null = "point" in hit ? hit.point : null; + if (!at) return false; + // Snap to the obvious points when close on screen. + const near = (q: Vec3) => { + const a = app.view.toScreen(new Vector3(...q)); + const b = app.view.toScreen(new Vector3(...at!)); + return !!a && !!b && Math.hypot(a[0] - b[0], a[1] - b[1]) < 16; + }; + if (hit.kind === "vertex") { + at = app.view.vertexOf(hit.body, hit.vertex) ?? at; + shown = { kind: "vertex", body: hit.body, vertex: hit.vertex }; + } else if (hit.kind === "edge") { + const e = app.view.body(hit.body)?.edges[hit.edge]; + const snap = e && [e.start, e.end, e.mid].find(near); + if (snap) at = snap; + shown = { kind: "edge", body: hit.body, edge: hit.edge }; + } else if (hit.kind === "face") { + const f = app.view.body(hit.body)?.faces[hit.face]; + if (f?.plane && near(f.center)) at = f.center; + shown = { kind: "face", body: hit.body, face: hit.face }; + } else shown = null; + set(at); + return true; + }, + }; +} diff --git a/src/tools/tool.ts b/src/tools/tool.ts new file mode 100644 index 0000000..ed94674 --- /dev/null +++ b/src/tools/tool.ts @@ -0,0 +1,184 @@ +import type { DocStore } from "../doc/store"; +import type { EdgeRef, ExtrudeSource, FaceRef, Feature, PinDef, PlaneDef, SketchEntity, SketchFeature, Vec3 } from "../doc/types"; +import type { KernelClient } from "../kernel/client"; +import type { RegenResult } from "../kernel/protocol"; +import { arrangement, regionRef } from "../sketch/regions"; +import type { ToolItem, UI } from "../ui/ui"; +import type { PointerHandler } from "../view/input"; +import type { Highlight, PickHit, Viewport } from "../view/viewport"; + +/** Something selected in the viewport. Same shape as a highlight. */ +export type Sel = Highlight; + +export interface Tool extends PointerHandler { + readonly id: string; + /** Sketch being edited, so the viewport can draw it as active. */ + readonly activeSketch?: string; + /** Feature being created/edited (highlighted in History). */ + readonly editingId?: string; + enter?(): void; + exit?(): void; + /** Return true when the key was handled. */ + key?(e: KeyboardEvent): boolean; + /** Keys typed while a drag is held (type an exact value; Enter finishes). */ + dragKey?(e: KeyboardEvent): boolean; + /** Called after every regeneration (committed or preview). */ + refresh?(): void; +} + +export interface AppContext { + readonly store: DocStore; + readonly kernel: KernelClient; + readonly view: Viewport; + readonly ui: UI; + readonly result: RegenResult | null; + readonly selection: Sel[]; + setSelection(sel: Sel[]): void; + setHover(h: Sel | null): void; + /** null returns to the selection tool. */ + setTool(tool: Tool | null): void; + /** Show the model as if `features` were the document (live preview). */ + preview(features: Feature[]): Promise; + /** Current plane of a sketch (sketches on faces follow the face). */ + sketchPlane(id: string): PlaneDef | undefined; + /** A sketch's curves plus the outline of the face it sits on (what regions are made of). */ + sketchCurves(id: string): SketchEntity[]; + mainTools(): ToolItem[]; + bottomTools(): ToolItem[]; + /** Pin a measurement in 3D (saved with the project). */ + addPin(pin: PinDef): void; + /** Bodies shown alone, or null when nothing is isolated. */ + readonly isolated: string[] | null; + isolate(bodies: string[] | null): void; +} + +/** Index of the body face matching a stored reference (by centre and normal). */ +export function faceIndexOf(app: AppContext, ref: FaceRef): number | null { + const faces = app.view.body(ref.body)?.faces ?? []; + let best: { i: number; d: number } | null = null; + faces.forEach((f, i) => { + const align = f.normal[0] * ref.normal[0] + f.normal[1] * ref.normal[1] + f.normal[2] * ref.normal[2]; + if (align < 0.99) return; + const d = Math.hypot(f.center[0] - ref.center[0], f.center[1] - ref.center[1], f.center[2] - ref.center[2]); + if (!best || d < best.d) best = { i, d }; + }); + return best ? (best as { i: number }).i : null; +} + +/** + * The nearest parallel face of the same body facing the other way, behind a + * flat face: "total" thickness for push/pull (like the distance to the bottom). + */ +export function oppositeFace(app: AppContext, body: string, face: number): { distance: number; point: Vec3 } | null { + const b = app.view.body(body); + const f = b?.faces[face]; + if (!b || !f?.plane) return null; + let best: number | null = null; + for (const g of b.faces) { + if (!g.plane) continue; + const d = f.normal[0] * g.normal[0] + f.normal[1] * g.normal[1] + f.normal[2] * g.normal[2]; + if (d > -0.999) continue; + const t = f.normal[0] * (f.center[0] - g.center[0]) + f.normal[1] * (f.center[1] - g.center[1]) + f.normal[2] * (f.center[2] - g.center[2]); + if (t > 1e-9 && (best === null || t < best)) best = t; + } + if (best === null) return null; + return { distance: best, point: [f.center[0] - f.normal[0] * best, f.center[1] - f.normal[1] * best, f.center[2] - f.normal[2] * best] }; +} + +export function sameSel(a: Sel, b: Sel): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +export function hitToSel(h: PickHit | null): Sel | null { + if (!h) return null; + const { point: _p, ...rest } = h; + return rest as Sel; +} + +// -------------------------------------------------- selection → references + +export function faceRefOf(app: AppContext, s: { body: string; face: number }): FaceRef | null { + const info = app.view.body(s.body)?.faces[s.face]; + return info ? { body: s.body, center: info.center, normal: info.normal, area: info.area } : null; +} + +export function edgeRefOf(app: AppContext, s: { body: string; edge: number }): EdgeRef | null { + const info = app.view.body(s.body)?.edges[s.edge]; + return info ? { body: s.body, mid: info.mid, dir: info.dir, length: info.length } : null; +} + +/** A selected profile or flat face as something extrude/revolve/… can use. */ +export function sourcesOf(app: AppContext, sel: Sel[]): ExtrudeSource[] { + const out: ExtrudeSource[] = []; + const bySketch = new Map(); + for (const s of sel) { + if (s.kind === "profile") bySketch.set(s.sketch, [...(bySketch.get(s.sketch) ?? []), s.region]); + if (s.kind === "face") { + const f = faceRefOf(app, s); + if (f) out.push({ kind: "face", face: f }); + } + } + for (const [sketch, idx] of bySketch) { + if (!app.store.find(sketch)) continue; + const regions = arrangement(app.sketchCurves(sketch)).regions; + out.unshift({ kind: "profile", sketch, regions: idx.map((i) => regions[i]).filter(Boolean).map(regionRef) }); + } + return out; +} + +/** + * A point on a curved face (its centre is off the face — on a cylinder's axis) + * and the normal there: the mesh vertex nearest the centre on the side facing the viewer. + */ +export function faceAnchor(app: AppContext, body: string, face: number): { base: Vec3; normal: Vec3 } | null { + const b = app.view.body(body); + const g = b?.faceGroups.find((x) => x.face === face); + const info = b?.faces[face]; + if (!b || !g || !info) return null; + const view = app.view.cam.viewDir().toArray() as Vec3; + let best: { base: Vec3; normal: Vec3; score: number } | null = null; + for (let i = g.start; i < g.start + g.count; i++) { + const v = b.indices[i] * 3; + const p: Vec3 = [b.positions[v], b.positions[v + 1], b.positions[v + 2]]; + const n: Vec3 = [b.normals[v], b.normals[v + 1], b.normals[v + 2]]; + const facing = n[0] * view[0] + n[1] * view[1] + n[2] * view[2]; + const d = Math.hypot(p[0] - info.center[0], p[1] - info.center[1], p[2] - info.center[2]); + const score = d + (facing > 0 ? 1e6 : 0); + if (!best || score < best.score) best = { base: p, normal: n, score }; + } + return best && { base: best.base, normal: best.normal }; +} + +/** Point + normal of a source, for placing handles. */ +export function sourceFrame(app: AppContext, src: ExtrudeSource): { base: Vec3; normal: Vec3 } { + if (src.kind === "face") { + const k = faceIndexOf(app, src.face); + const info = k !== null ? app.view.body(src.face.body)?.faces[k] : undefined; + if (k !== null && info && !info.plane) return faceAnchor(app, src.face.body, k) ?? { base: src.face.center, normal: src.face.normal }; + return { base: src.face.center, normal: src.face.normal }; + } + const plane = app.sketchPlane(src.sketch); + if (!plane) return { base: [0, 0, 0], normal: [0, 0, 1] }; + const c = src.regions[0]?.c ?? [0, 0]; + const y: Vec3 = [ + plane.normal[1] * plane.xDir[2] - plane.normal[2] * plane.xDir[1], + plane.normal[2] * plane.xDir[0] - plane.normal[0] * plane.xDir[2], + plane.normal[0] * plane.xDir[1] - plane.normal[1] * plane.xDir[0], + ]; + return { + base: [plane.origin[0] + plane.xDir[0] * c[0] + y[0] * c[1], plane.origin[1] + plane.xDir[1] * c[0] + y[1] * c[1], plane.origin[2] + plane.xDir[2] * c[0] + y[2] * c[1]], + normal: plane.normal, + }; +} + +/** Body that a source "sits on" (joins/cuts default to it). */ +export function targetOf(app: AppContext, src: ExtrudeSource): string | undefined { + if (src.kind === "face") return src.face.body; + return app.store.find(src.sketch)?.attachedTo?.body; +} + +/** Bodies referenced by the selection (faces/edges/vertices count for their body). */ +export function bodiesOf(sel: Sel[]): string[] { + const ids = sel.flatMap((s) => (s.kind === "body" || s.kind === "face" || s.kind === "edge" || s.kind === "vertex" ? [s.body] : [])); + return [...new Set(ids)]; +} diff --git a/src/ui/icons.ts b/src/ui/icons.ts new file mode 100644 index 0000000..dc366cd --- /dev/null +++ b/src/ui/icons.ts @@ -0,0 +1,92 @@ +// Inline SVG icons (24×24, stroke = currentColor). Original artwork. + +const svg = (body: string) => + `${body}`; + +export const icons = { + pivot: svg(''), + sketch: svg(''), + line: svg(''), + arc: svg(''), + spline: svg(''), + rect: svg(''), + circle: svg(''), + ellipse: svg(''), + polygon: svg(''), + project: svg(''), + offset: svg(''), + sketchFillet: svg(''), + text: svg(''), + move: svg(''), + scale: svg(''), + patternLinear: svg(''), + patternCircular: svg(''), + rotateAxis: svg(''), + mirror: svg(''), + trim: svg(''), + alignLine: svg(''), + extend: svg(''), + construction: svg(''), + pointer: svg(''), + extrude: svg(''), + revolve: svg(''), + sweep: svg(''), + loft: svg(''), + shell: svg(''), + split: svg(''), + fill: svg(''), + wrap: svg(''), + replaceFace: svg(''), + projectEdge: svg(''), + plane: svg(''), + axis: svg(''), + align: svg(''), + translate: svg(''), + fillet: svg(''), + chamfer: svg(''), + offsetFace: svg(''), + union: svg(''), + subtract: svg(''), + intersect: svg(''), + trash: svg(''), + undo: svg(''), + redo: svg(''), + history: svg(''), + fit: svg(''), + file: svg(''), + insert: svg(''), + variable: svg(''), + image: svg(''), + construct: svg(''), + transform: svg(''), + tools: svg(''), + section: svg(''), + measure: svg(''), + magnet: svg(''), + ruler: svg(''), + views: svg(''), + display: svg(''), + camera: svg(''), + eye: svg(''), + eyeOff: svg(''), + check: svg(''), + close: svg(''), + exit: svg(''), + normal: svg(''), + menu: svg(''), + rename: svg(''), + pin: svg(''), + flip: svg(''), + deselect: svg(''), + more: svg(''), + splitLine: svg(''), + freeform: svg(''), + copy: svg(''), + color: svg(''), + folder: svg(''), + constraints: svg(''), + isolate: svg(''), + body: svg(''), +}; + +export type IconName = keyof typeof icons; diff --git a/src/ui/items.ts b/src/ui/items.ts new file mode 100644 index 0000000..cdc22e4 --- /dev/null +++ b/src/ui/items.ts @@ -0,0 +1,228 @@ +// Items panel: every body, sketch, plane, axis and image, with visibility +// toggles — plus folders (at the bottom) to group any of them. + +import type { DocStore } from "../doc/store"; +import type { Feature, ItemFolder } from "../doc/types"; +import type { RegenResult } from "../kernel/protocol"; +import { icons, type IconName } from "./icons"; +import { el } from "./ui"; + +export interface ItemsHandlers { + selectBody(id: string): void; + editSketch(id: string): void; + selectPlane(id: string): void; + selectImage(id: string): void; + deleteBody(id: string): void; + deleteFeature(id: string): void; + /** Rename a body (custom name) or a feature (its history name). */ + rename(id: string, current: string, isBody: boolean): void; + /** Ask for a name (folders). */ + askName(title: string, current: string): Promise; + isolated(): string[] | null; +} + +interface Row { + id: string; + name: string; + icon: IconName; + open(): void; + remove(): void; + extra?: string; + isBody?: boolean; +} + +export class ItemsPanel { + private el = document.getElementById("items")!; + private list = document.getElementById("items-list")!; + /** Rows ticked for grouping (Ctrl/Shift+click, or the checkboxes in Select mode). */ + private checked = new Set(); + private picking = false; + private collapsed = new Set(); + private last: RegenResult | null = null; + + constructor( + private store: DocStore, + private h: ItemsHandlers, + ) { + document.getElementById("items-btn")!.addEventListener("click", () => this.toggle()); + document.getElementById("items-close")!.innerHTML = icons.close; + document.getElementById("items-close")!.addEventListener("click", () => this.toggle(false)); + const pick = document.getElementById("items-pick")!; + pick.addEventListener("click", () => { + this.picking = !this.picking; + if (!this.picking) this.checked.clear(); + pick.classList.toggle("on", this.picking); + this.render(this.last); + }); + } + + toggle(open?: boolean): void { + const on = this.el.classList.toggle("open", open); + // Phones: one panel at a time (Items or History). + if (on && window.innerWidth <= 720) { + document.getElementById("history")?.classList.remove("open"); + document.body.classList.remove("history-open"); + } + // The tool column steps aside while Items is open. + document.body.classList.toggle("items-open", on); + // The value panel and tool column re-fit around it. + window.dispatchEvent(new Event("resize")); + } + + private get folders(): ItemFolder[] { + return this.store.doc.folders ?? []; + } + + private shown = ""; + + render(result: RegenResult | null): void { + this.last = result; + // Nothing that the list shows changed: keep the rows (rebuilding them under a + // click that's in progress would swallow that click). + const d = this.store.doc; + const sig = JSON.stringify([ + d.hidden, d.names, d.folders, this.h.isolated(), [...this.checked], this.picking, [...this.collapsed], + result?.bodies.map((b) => [b.id, b.name]), + d.features.filter((f) => ["sketch", "plane", "axis", "image"].includes(f.type)).map((f) => [f.id, f.name, f.type]), + ]); + if (sig === this.shown) return; + this.shown = sig; + this.list.innerHTML = ""; + const hidden = new Set(this.store.doc.hidden); + const iso = this.h.isolated(); + const inFolder = new Set(this.folders.flatMap((f) => f.items)); + const section = (title: string) => this.list.append(el("li", "items-heading", title)); + + // Everything there is, by kind. + const bodies = result?.bodies ?? []; + const names = this.store.doc.names ?? {}; + const feats = this.store.doc.features; + const of = (t: T) => feats.filter((f) => f.type === t); + const rows: Record = { + Bodies: bodies.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, icon: "body" as IconName, open: () => this.h.selectBody(b.id), remove: () => this.h.deleteBody(b.id), extra: iso && !iso.includes(b.id) ? " isolated-out" : "", isBody: true })), + Sketches: of("sketch").map((s) => ({ id: s.id, name: s.name, icon: "sketch" as IconName, open: () => this.h.editSketch(s.id), remove: () => this.h.deleteFeature(s.id) })), + "Planes & axes": [...of("plane"), ...of("axis")].map((c) => ({ id: c.id, name: c.name, icon: (c.type === "plane" ? "plane" : "axis") as IconName, open: () => this.h.selectPlane(c.id), remove: () => this.h.deleteFeature(c.id) })), + Images: of("image").map((i) => ({ id: i.id, name: i.name, icon: "image" as IconName, open: () => this.h.selectImage(i.id), remove: () => this.h.deleteFeature(i.id) })), + }; + const byId = new Map(Object.values(rows).flat().map((r) => [r.id, r])); + + for (const [title, list] of Object.entries(rows)) { + const loose = list.filter((r) => !inFolder.has(r.id)); + if (title !== "Bodies" && !loose.length) continue; + section(`${title} (${loose.length})`); + if (!loose.length) this.list.append(el("li", "items-empty", bodies.length ? "All in folders" : "No bodies yet")); + for (const r of loose) this.row(r, hidden, 0); + } + + // Folders last, each with what it holds. + if (this.folders.length) section(`Folders (${this.folders.length})`); + for (const f of this.folders) { + const items = f.items.map((id) => byId.get(id)).filter((r): r is Row => !!r); + this.folderRow(f, items, hidden); + if (!this.collapsed.has(f.id)) for (const r of items) this.row(r, hidden, 1); + } + + // Grouping bar. + if (this.checked.size) { + const bar = el("li", "items-groupbar"); + const make = el("button", "text-btn primary", `New folder (${this.checked.size})`); + make.addEventListener("click", () => void this.makeFolder()); + const clear = el("button", "text-btn", "Clear"); + clear.addEventListener("click", () => (this.checked.clear(), this.render(this.last))); + bar.append(make, clear); + this.list.append(bar); + } else if (this.picking) { + this.list.append(el("li", "items-empty", "Tick items, then make a folder of them.")); + } + } + + private row(r: Row, hidden: Set, depth: number): void { + const li = el("li", `items-row${hidden.has(r.id) ? " hidden-item" : ""}${r.extra ?? ""}${this.checked.has(r.id) ? " checked" : ""}${depth ? " in-folder" : ""}`); + if (this.picking) { + const box = document.createElement("input"); + box.type = "checkbox"; + box.className = "items-check"; + box.checked = this.checked.has(r.id); + box.addEventListener("change", () => this.check(r.id, box.checked)); + li.append(box); + } + const eye = el("button", "icon-btn"); + eye.title = hidden.has(r.id) ? "Show" : "Hide"; + eye.innerHTML = icons[hidden.has(r.id) ? "eyeOff" : "eye"]; + eye.addEventListener("click", (e) => { + e.stopPropagation(); + this.store.commit((d) => (d.hidden = hidden.has(r.id) ? d.hidden.filter((x) => x !== r.id) : [...d.hidden, r.id])); + }); + const label = el("button", "items-name"); + label.innerHTML = icons[r.icon]; + label.append(r.name); + // Ctrl/Cmd/Shift+click ticks the row for grouping; a plain click opens it. + label.addEventListener("click", (e) => (e.ctrlKey || e.metaKey || e.shiftKey || this.picking ? this.check(r.id, !this.checked.has(r.id)) : r.open())); + const ren = el("button", "icon-btn"); + ren.title = "Rename"; + ren.innerHTML = icons.rename; + ren.addEventListener("click", (e) => (e.stopPropagation(), this.h.rename(r.id, r.name, !!r.isBody))); + const del = el("button", "icon-btn"); + del.title = "Delete"; + del.innerHTML = icons.trash; + del.addEventListener("click", (e) => (e.stopPropagation(), r.remove())); + li.append(eye, label, ren, del); + this.list.append(li); + } + + private folderRow(f: ItemFolder, items: Row[], hidden: Set): void { + const li = el("li", "items-row folder-row"); + const allHidden = items.length > 0 && items.every((r) => hidden.has(r.id)); + const eye = el("button", "icon-btn"); + eye.title = allHidden ? "Show all in folder" : "Hide all in folder"; + eye.innerHTML = icons[allHidden ? "eyeOff" : "eye"]; + eye.addEventListener("click", () => + this.store.commit((d) => { + const ids = new Set(items.map((r) => r.id)); + d.hidden = allHidden ? d.hidden.filter((x) => !ids.has(x)) : [...new Set([...d.hidden, ...ids])]; + }), + ); + const label = el("button", "items-name"); + label.innerHTML = icons.folder; + label.append(f.name, el("span", "items-count", ` ${items.length}`), el("span", "items-caret", this.collapsed.has(f.id) ? " ▸" : " ▾")); + label.title = "Show / hide its contents"; + label.addEventListener("click", () => { + if (this.collapsed.has(f.id)) this.collapsed.delete(f.id); + else this.collapsed.add(f.id); + this.render(this.last); + }); + const ren = el("button", "icon-btn"); + ren.title = "Rename folder"; + ren.innerHTML = icons.rename; + ren.addEventListener("click", async () => { + const name = await this.h.askName("Rename folder", f.name); + if (name) this.store.commit((d) => (d.folders = (d.folders ?? []).map((x) => (x.id === f.id ? { ...x, name } : x)))); + }); + const del = el("button", "icon-btn"); + del.title = "Remove folder (keeps what's in it)"; + del.innerHTML = icons.trash; + del.addEventListener("click", () => this.store.commit((d) => (d.folders = (d.folders ?? []).filter((x) => x.id !== f.id)))); + li.append(eye, label, ren, del); + this.list.append(li); + } + + private check(id: string, on: boolean): void { + if (on) this.checked.add(id); + else this.checked.delete(id); + this.render(this.last); + } + + private async makeFolder(): Promise { + const ids = [...this.checked]; + const name = await this.h.askName("New folder", `Folder ${this.folders.length + 1}`); + if (!name) return; + this.checked.clear(); + this.picking = false; + document.getElementById("items-pick")!.classList.remove("on"); + // An item lives in one folder at a time. + this.store.commit((d) => { + const rest = (d.folders ?? []).map((f) => ({ ...f, items: f.items.filter((x) => !ids.includes(x)) })); + d.folders = [...rest, { id: `folder-${Date.now().toString(36)}`, name, items: ids }]; + }); + } +} diff --git a/src/ui/panels.ts b/src/ui/panels.ts new file mode 100644 index 0000000..ede5e44 --- /dev/null +++ b/src/ui/panels.ts @@ -0,0 +1,167 @@ +// Right column popovers: snapping, units & grid, views, display modes, screenshot, history. + +import type { SavedView, Units, Vec3 } from "../doc/types"; +import type { DocStore } from "../doc/store"; +import { settings, type Settings } from "../settings"; +import { UNIT_LABEL, units } from "../units"; +import type { Viewport } from "../view/viewport"; +import type { UI } from "./ui"; +import { el } from "./ui"; + +export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnits: (u: Units) => void): void { + ui.addRight("fit", "fit", "Zoom to fit (F)", () => view.cam.fit(view.bounds()), () => "Fit"); + ui.addRight("snap", "magnet", "Snapping", (host) => { + const s = settings.value; + host.append(heading("Snap to")); + const snapRow = (key: keyof Settings["snap"], label: string) => + toggleRow(label, s.snap[key], (v) => settings.set("snap", { ...settings.value.snap, [key]: v })); + host.append(snapRow("grid", "Grid"), snapRow("guideLines", "Sketch guide lines"), snapRow("guidePoints", "Sketch guide points"), snapRow("points3d", "3D guide points"), snapRow("distantEdges", "Distant edges")); + host.append(heading("Show")); + host.append(toggleRow("Guide points", s.showGuidePoints, (v) => settings.set("showGuidePoints", v)), toggleRow("Snapping hints", s.showSnapHints, (v) => settings.set("showSnapHints", v))); + host.append(el("div", "pop-note", "Hold Shift while drawing to place a point without snapping.")); + }); + + ui.addRight( + "units", + "ruler", + "Units & grid", + (host) => { + host.append(heading("Units")); + const list: [Units, string][] = [ + ["mm", "Millimeter"], + ["cm", "Centimeter"], + ["m", "Meter"], + ["in", "Inch"], + ["ft", "Foot"], + ]; + for (const [u, label] of list) host.append(choiceRow(label, units() === u, () => (onUnits(u), ui.refreshPopover()))); + host.append(heading("Grid")); + const s = settings.value; + host.append(toggleRow(`Lock grid size (${s.gridStep} mm)`, s.gridLocked, (v) => settings.set("gridLocked", v))); + const stepRow = el("label", "pop-row"); + stepRow.append(el("span", "", "Locked size (mm)")); + const input = document.createElement("input"); + input.className = "pop-input"; + input.value = String(s.gridStep); + input.addEventListener("change", () => { + const v = Number(input.value); + if (v > 0) settings.set("gridStep", v); + }); + stepRow.append(input); + host.append(stepRow); + host.append(el("div", "pop-note", `Tip: the grid adapts to zoom (now ${fmtStep(view.grid.step)} per square).`)); + host.append(heading("Degree format")); + host.append(choiceRow("Decimal (27.15°)", s.degrees === "decimal", () => settings.set("degrees", "decimal")), choiceRow("Fractional (27° 15′)", s.degrees === "fractional", () => settings.set("degrees", "fractional"))); + }, + () => UNIT_LABEL[units()], + ); + + ui.addRight("views", "views", "Views", (host) => { + const tabs = el("div", "pop-tabs"); + const views = el("button", "", "Views"); + const appearance = el("button", "active", "Appearance"); + tabs.append(appearance, views); + const body = el("div", ""); + host.append(tabs, body); + const showViews = () => { + views.className = "active"; + appearance.className = ""; + body.innerHTML = ""; + const go = (label: string, n: Vec3, x?: Vec3) => choiceRow(label, false, () => view.cam.lookAlong(n, x)); + body.append(choiceRow("⌂ Default view", false, () => (view.cam.iso(), view.cam.fit(view.bounds())))); + body.append(go("Top", [0, 0, 1]), go("Bottom", [0, 0, -1]), go("Front", [0, -1, 0]), go("Back", [0, 1, 0], [-1, 0, 0]), go("Right", [1, 0, 0], [0, 1, 0]), go("Left", [-1, 0, 0], [0, -1, 0])); + body.append(heading("Saved views")); + for (const v of store.doc.views) { + const row = choiceRow(v.name, false, () => view.cam.restore(v)); + const del = el("button", "icon-btn small", "✕"); + del.title = "Delete view"; + del.addEventListener("click", (e) => { + e.stopPropagation(); + store.commit((d) => (d.views = d.views.filter((x) => x.name !== v.name))); + showViews(); + }); + row.append(del); + body.append(row); + } + body.append( + choiceRow("+ Save current view", false, () => { + const name = `View ${store.doc.views.length + 1}`; + const sv: SavedView = view.cam.savedView(name); + store.commit((d) => d.views.push(sv)); + showViews(); + }), + ); + }; + const showAppearance = () => { + views.className = ""; + appearance.className = "active"; + body.innerHTML = ""; + const s = settings.value; + body.append( + toggleRow("Animate camera", s.animateCamera, (v) => settings.set("animateCamera", v)), + toggleRow("Orthographic", s.ortho, (v) => settings.set("ortho", v)), + toggleRow("Show grid", s.showGrid, (v) => settings.set("showGrid", v)), + toggleRow("Show world axes", s.showAxes, (v) => settings.set("showAxes", v)), + ); + }; + views.addEventListener("click", showViews); + appearance.addEventListener("click", showAppearance); + showAppearance(); + }); + + ui.addRight("display", "display", "Display modes", (host) => { + const s = settings.value; + host.append(heading("Shaders")); + for (const [id, label] of [["wireframe", "Wireframe"], ["xray", "X-Ray"], ["shaded", "Shaded"]] as const) { + host.append(choiceRow(label, s.shader === id, () => (settings.set("shader", id), ui.refreshPopover()))); + } + host.append(heading("Options")); + host.append(toggleRow("Show edges", s.showEdges, (v) => settings.set("showEdges", v)), toggleRow("Show hidden edges", s.showHiddenEdges, (v) => settings.set("showHiddenEdges", v))); + }, () => ({ shaded: "Shaded", wireframe: "Wire", xray: "X-Ray" })[settings.value.shader]); + + ui.addRight("shot", "camera", "Screenshot", () => { + void view.screenshot().then((blob) => { + if (!blob) return; + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = `${store.doc.name} ${new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-")}.png`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); + ui.toast("Screenshot saved"); + }); + }); + + ui.addRight("history", "history", "History", () => ui.toggleHistory()); + // Sketch mode only (CSS shows it under body.sketching): show/hide the constraint column. + const cons = ui.addRight("constraints", "constraints", "Constraints (sketch)", () => settings.set("showConstraints", !settings.value.showConstraints)); + cons.classList.add("sketch-only"); + const mark = () => cons.classList.toggle("on", settings.value.showConstraints); + settings.onChange(mark); + mark(); + settings.onChange(() => ui.refreshRight()); +} + +function heading(text: string): HTMLElement { + return el("div", "pop-heading", text); +} + +function toggleRow(label: string, value: boolean, onChange: (v: boolean) => void): HTMLElement { + const row = el("button", `pop-row toggle-row${value ? " on" : ""}`); + row.append(el("span", "", label), el("span", "switch")); + row.addEventListener("click", () => { + const next = !row.classList.contains("on"); + row.classList.toggle("on", next); + onChange(next); + }); + return row; +} + +function choiceRow(label: string, active: boolean, run: () => void): HTMLElement { + const row = el("button", `pop-row choice-row${active ? " active" : ""}`, label); + row.addEventListener("click", run); + return row; +} + +function fmtStep(mm: number): string { + return mm >= 1000 ? `${mm / 1000} m` : mm >= 10 ? `${mm / 10} cm` : `${mm} mm`; +} diff --git a/src/ui/pivot.ts b/src/ui/pivot.ts new file mode 100644 index 0000000..26f5c72 --- /dev/null +++ b/src/ui/pivot.ts @@ -0,0 +1,80 @@ +// Orbit centre: a button under the view cube. Tap it, then tap a body, a sketch +// or the ground: from then on the view turns about that point. Zoom to fit +// (or tapping empty space while choosing) goes back to turning about the view's centre. + +import { BufferGeometry, Points, Vector3 } from "three"; +import type { Viewport } from "../view/viewport"; +import { dotMaterial } from "../view/viewport"; +import { GROUND } from "../geom"; +import { icons } from "./icons"; + +export class PivotButton { + readonly el = document.createElement("button"); + private cursor = document.createElement("div"); + private choosing = false; + private marker: Points; + + constructor(private view: Viewport, private toast: (text: string) => void) { + this.el.className = "pivot-btn"; + this.el.title = "Orbit centre: tap here, then tap where the view should turn around"; + this.el.innerHTML = icons.pivot; + this.el.addEventListener("click", () => this.setChoosing(!this.choosing)); + this.cursor.className = "pivot-cursor"; + this.cursor.innerHTML = icons.pivot; + this.cursor.hidden = true; + document.body.append(this.cursor); + this.marker = new Points(new BufferGeometry().setFromPoints([new Vector3()]), dotMaterial({ color: 0x3d8bff, size: 10 })); + this.marker.renderOrder = 60; + (this.marker.material as { depthTest: boolean }).depthTest = false; + this.marker.visible = false; + view.overlay.add(this.marker); + // While choosing, the next press on the model picks the point (and goes nowhere else). + view.canvas.addEventListener( + "pointerdown", + (e) => { + if (!this.choosing || e.button !== 0) return; + e.stopImmediatePropagation(); + e.preventDefault(); + const r = view.canvas.getBoundingClientRect(); + this.pick(e.clientX - r.left, e.clientY - r.top); + }, + true, + ); + window.addEventListener("pointermove", (e) => { + if (!this.choosing) return; + this.cursor.style.transform = `translate(${e.clientX + 14}px, ${e.clientY + 14}px)`; + }); + window.addEventListener("keydown", (e) => e.key === "Escape" && this.choosing && this.setChoosing(false)); + view.frameHooks.add(() => this.layout()); + } + + private setChoosing(on: boolean): void { + this.choosing = on; + this.el.classList.toggle("on", on || !!this.view.cam.pivot); + this.cursor.hidden = !on; + this.view.canvas.style.cursor = on ? "crosshair" : ""; + if (on) this.toast("Tap a point on the model to turn the view around it"); + } + + private pick(x: number, y: number): void { + const hit = this.view.pick(x, y, { edgeTolPx: 10, curves: true, planes: false, axes: false }); + const at = hit?.point ?? this.view.rayToPlane(x, y, GROUND); + if (hit?.point || at) { + this.view.cam.pivot = new Vector3(...(at as [number, number, number])); + } else { + this.view.cam.pivot = null; + } + this.setChoosing(false); + this.view.requestRender(); + } + + private layout(): void { + const p = this.view.cam.pivot; + this.marker.visible = !!p; + this.el.classList.toggle("on", this.choosing || !!p); + if (p) { + this.marker.position.copy(p); + this.marker.updateMatrixWorld(); + } + } +} diff --git a/src/ui/ui.ts b/src/ui/ui.ts new file mode 100644 index 0000000..5ebd0f1 --- /dev/null +++ b/src/ui/ui.ts @@ -0,0 +1,631 @@ +import type { Feature } from "../doc/types"; +import type { FeatureError } from "../kernel/protocol"; +import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units"; +import { icons, type IconName } from "./icons"; + +export interface ToolItem { + id: string; + label: string; + icon: IconName; + /** Small second line, e.g. the current variant ("Diagonal"). */ + sub?: string; + shortcut?: string; + active?: boolean; + disabled?: boolean; + /** Reason shown when disabled. */ + why?: string; + /** Opens a flyout with variants / sub-tools instead of running. */ + children?: ToolItem[]; + /** Show a colour circle instead of the icon (colour choices). */ + swatch?: string; + run?(): void; +} + +export type FieldKind = "length" | "angle" | "number" | "int"; + +export type PanelItem = + | { + type: "number"; + label: string; + value: number; + kind?: FieldKind; + min?: number; + onInput(v: number): void; + /** Expression currently driving the value (shown instead of the number). */ + expr?: string; + /** Set when the field may hold an expression: called with it, or null for a plain number. */ + onExpr?(expr: string | null): void; + } + | { type: "slot"; label: string; value: string; active: boolean; filled: boolean; onClick(): void } + | { type: "choice"; label?: string; options: { id: string; label: string }[]; value: string; onChange(id: string): void } + | { type: "toggle"; label: string; value: boolean; onChange(v: boolean): void } + | { type: "button"; label: string; icon?: IconName; onClick(): void }; + +/** Kept for older call sites: a numeric field. */ +export interface ValueField { + label: string; + value: number; + unit?: string; + min?: number; + step?: number; + integer?: boolean; + kind?: FieldKind; + onInput(v: number): void; +} + +export interface ValuePanel { + title: string; + fields?: ValueField[]; + items?: PanelItem[]; + onDone?(): void; + onCancel?(): void; + /** Extra buttons shown in the panel (e.g. Delete). */ + actions?: ToolItem[]; +} + +export interface HistoryHandlers { + edit(id: string): void; + /** Pointer over a step (null: left it): show what it works on. */ + hover?(id: string | null): void; + toggle(id: string): void; + remove(id: string): void; +} + +const $ = (sel: string) => document.querySelector(sel) as T; + +/** All DOM chrome around the viewport. Deliberately framework-free and small. */ +export class UI { + private toolbar = $("#toolbar"); + private bottomLeft = $("#bottom-left"); + private flyout = $("#flyout"); + private hint = $("#hint"); + private panel = $("#panel"); + private historyEl = $("#history"); + private historyList = $("#history-list"); + private toastEl = $("#toast"); + private labelEl = $("#label"); + private status = $("#status"); + private rightCol = $("#right-col"); + private popover = $("#popover"); + readonly pins = $("#pins"); + private toastTimer = 0; + private panelSpec: ValuePanel | null = null; + private flyoutOwner: string | null = null; + private popoverOwner: string | null = null; + + constructor() { + $("#history-close").innerHTML = icons.close; + $("#history-close").addEventListener("click", () => this.toggleHistory(false)); + document.addEventListener("pointerdown", (e) => { + const t = e.target as HTMLElement; + if (!t.closest("#flyout, #toolbar, #bottom-left")) this.closeFlyout(); + }); + if (window.innerWidth >= 1000) this.toggleHistory(true); + window.addEventListener("resize", () => (this.fitToolbar(), this.fitPanel())); + } + + toggleHistory(open?: boolean): void { + const on = this.historyEl.classList.toggle("open", open); + // Phones: one panel at a time (History or Items). + if (on && window.innerWidth <= 720) { + document.getElementById("items")?.classList.remove("open"); + document.body.classList.remove("items-open"); + } + // Everything on the right makes room for the docked History panel. + document.body.classList.toggle("history-open", on); + // Things placed beside the right-hand bar (panel, constraint column) re-fit. + window.dispatchEvent(new Event("resize")); + } + + // ------------------------------------------------------------- left column + + setTools(items: ToolItem[]): void { + this.closeFlyout(); + this.toolItems = items; + renderTools(this.toolbar, items, (item, btn) => this.runAndOpen(item, btn, this.toolbar, () => this.toolItems)); + this.fitToolbar(); + } + + setBottom(items: ToolItem[]): void { + this.bottomItems = items; + renderTools(this.bottomLeft, items, (item, btn) => this.runAndOpen(item, btn, this.bottomLeft, () => this.bottomItems)); + this.fitToolbar(); + } + + private toolItems: ToolItem[] = []; + private bottomItems: ToolItem[] = []; + + /** + * A tool with options (Spline: fit / control points…): a click starts it + * straight away with the option used last, and opens the options beside it. + */ + private runAndOpen(item: ToolItem, btn: HTMLElement, host: HTMLElement, items: () => ToolItem[]): void { + if (!item.run || this.flyoutOwner === item.id) return this.openFlyout(item, btn); + const rect = btn.getBoundingClientRect(); + item.run(); + // Running it may have redrawn the column: open the options on the new button + // (or where the button was, if a tool took the column over). + const fresh = items().find((x) => x.id === item.id) ?? item; + const nb = host.querySelector(`[data-tool="${CSS.escape(item.id)}"]`) ?? ({ getBoundingClientRect: () => rect } as HTMLElement); + if (fresh.children?.length) this.openFlyout(fresh, nb); + } + + /** + * The tool column is centred on the left edge; keep it clear of the top bar + * and of the buttons at the bottom-left, with a gap like the other panels. + */ + /** + * The value panel is centred at the bottom: keep it between the left tool + * columns and the right column / History, wrapping onto more rows if needed. + */ + fitPanel(): void { + if (window.innerWidth <= 720) return void (this.panel.style.maxWidth = ""); + const GAP = 12; + const visible = (e: HTMLElement) => !e.hidden && e.childElementCount > 0 && getComputedStyle(e).display !== "none"; + const left = Math.max(0, ...[this.toolbar, this.bottomLeft, document.getElementById("undo-dock")!].filter(visible).map((e) => e.getBoundingClientRect().right)); + const rights = [this.rightCol, ...(this.historyEl.classList.contains("open") ? [this.historyEl] : [])].map((e) => e.getBoundingClientRect().left); + const right = window.innerWidth - Math.min(window.innerWidth, ...rights); + const reserve = Math.max(left, right) + GAP; + this.panel.style.maxWidth = `${Math.max(260, window.innerWidth - 2 * reserve)}px`; + } + + fitToolbar(): void { + if (window.innerWidth <= 720) return void (this.toolbar.style.maxHeight = ""); + const GAP = 14; + // Whatever is stacked at the bottom-left (section/measure buttons, the undo dock). + const stack = [this.bottomLeft, document.getElementById("undo-dock")!].filter((e) => e.childElementCount && getComputedStyle(e).display !== "none"); + const below = stack.length ? window.innerHeight - Math.min(...stack.map((e) => e.getBoundingClientRect().top)) + GAP : 0; + const above = 52 + GAP; + this.toolbar.style.maxHeight = `${Math.max(160, window.innerHeight - 2 * Math.max(below, above))}px`; + } + + /** Back-compat: the context list now lives in the main column. */ + setContext(_items: ToolItem[]): void {} + + private openFlyout(item: ToolItem, anchor: HTMLElement): void { + if (this.flyoutOwner === item.id) return this.closeFlyout(); + this.flyoutOwner = item.id; + // Measure before re-rendering: a nested anchor lives inside this flyout. + const r = anchor.getBoundingClientRect(); + this.flyout.innerHTML = ""; + renderTools(this.flyout, item.children ?? [], (child, btn) => this.openFlyout(child, btn), () => this.closeFlyout()); + // Colour choices show as a grid of circles. + this.flyout.classList.toggle("swatch-grid", !!item.children?.length && item.children.every((c) => c.swatch)); + this.flyout.hidden = false; + const narrow = window.innerWidth <= 720; + if (narrow) { + // Above the bottom strip and the buttons stacked over it (undo, section…). + const stack = [this.bottomLeft, document.getElementById("undo-dock")!].filter((e) => e.childElementCount && getComputedStyle(e).display !== "none").map((e) => e.getBoundingClientRect().top); + const above = Math.min(r.top, ...stack.filter((t) => t < r.top)); + this.flyout.style.left = "8px"; + this.flyout.style.top = ""; + this.flyout.style.bottom = `${window.innerHeight - above + 8}px`; + } else { + this.flyout.style.left = `${r.right + 6}px`; + this.flyout.style.bottom = ""; + this.flyout.style.top = `${Math.min(r.top, window.innerHeight - this.flyout.offsetHeight - 12)}px`; + } + } + + closeFlyout(): void { + this.flyout.hidden = true; + this.flyoutOwner = null; + } + + // ------------------------------------------------------------ right column + + addRight(id: string, icon: IconName, title: string, open: (host: HTMLElement) => void, label?: () => string): HTMLButtonElement { + const b = document.createElement("button"); + b.className = "right-btn"; + b.title = title; + b.innerHTML = icons[icon]; + if (label) { + const l = document.createElement("span"); + l.className = "right-label"; + b.append(l); + b.dataset.dynamic = "1"; + (b as HTMLButtonElement & { refresh?: () => void }).refresh = () => (l.textContent = label()); + (b as HTMLButtonElement & { refresh?: () => void }).refresh!(); + } + b.addEventListener("click", () => { + // Popovers stay open until their button is clicked again. + if (this.popoverOwner === id) return this.closePopover(); + this.popoverOwner = id; + this.popoverFill = () => { + this.popover.innerHTML = ""; + open(this.popover); + }; + this.popoverFill(); + if (!this.popover.childElementCount) return this.closePopover(); + this.popover.hidden = false; + const r = b.getBoundingClientRect(); + this.popover.style.top = `${Math.max(8, Math.min(r.top, window.innerHeight - this.popover.offsetHeight - 8))}px`; + this.rightCol.querySelectorAll(".right-btn").forEach((x) => x.classList.toggle("pop-open", x === b)); + // Things placed beside the right column (the constraint column) move over. + window.dispatchEvent(new Event("resize")); + }); + this.rightCol.append(b); + return b; + } + + refreshRight(): void { + this.rightCol.querySelectorAll void }>("button").forEach((b) => b.refresh?.()); + } + + private popoverFill: (() => void) | null = null; + + closePopover(): void { + if (this.popover.hidden) return; + this.popover.hidden = true; + this.popoverOwner = null; + this.popoverFill = null; + this.rightCol.querySelectorAll(".pop-open").forEach((x) => x.classList.remove("pop-open")); + window.dispatchEvent(new Event("resize")); + } + + /** Re-draw the open popover (after one of its choices changed). */ + refreshPopover(): void { + this.popoverFill?.(); + } + + // ------------------------------------------------------- hint/status/toast + + setHint(text: string | null): void { + this.hint.textContent = text ?? ""; + this.hint.hidden = !text; + } + + /** A small persistent note (e.g. "body not closed"), never blocking. */ + setWarning(text: string | null): void { + const w = document.getElementById("warn")!; + w.textContent = text ?? ""; + w.hidden = !text; + } + + setStatus(text: string | null): void { + this.status.textContent = text ?? ""; + this.status.hidden = !text; + } + + toast(text: string, kind: "info" | "error" = "info"): void { + this.toastEl.textContent = text; + this.toastEl.className = `show ${kind}`; + clearTimeout(this.toastTimer); + this.toastTimer = window.setTimeout(() => (this.toastEl.className = ""), 3600); + } + + /** Floating label next to the pointer, e.g. live dimensions while drawing. */ + setLabel(x: number, y: number, text: string | null): void { + if (!text) { + this.labelEl.hidden = true; + return; + } + this.labelEl.hidden = false; + // The value, plus a reminder that it can be typed (or how to apply what's typed). + // Callers mark typeable values with a trailing "· type a value". + const value = text.replace(/\s+· type a value$/, ""); + const typeable = value !== text; + const typing = value.includes("▌"); + const tip = typing ? "Enter ↵ apply · Esc cancel" : typeable ? "⌨ type a value · Enter ↵" : null; + this.labelEl.replaceChildren(el("span", "label-value", value), ...(tip ? [el("span", "label-tip", tip)] : [])); + this.labelEl.classList.toggle("typing", typing); + this.labelEl.style.transform = `translate(${Math.round(x + 18)}px, ${Math.round(y + 14)}px)`; + } + + /** Small modal form; resolves with the values, or null if cancelled. */ + dialog(title: string, fields: { key: string; label: string; value: string; placeholder?: string }[], note?: string): Promise | null> { + return new Promise((resolve) => { + const back = el("div", "dialog-back"); + const box = el("form", "dialog"); + box.append(el("div", "panel-title", title)); + if (note) box.append(el("div", "dialog-note", note)); + const inputs = fields.map((f) => { + const l = el("label", "dialog-field"); + l.append(el("span", "field-label", f.label)); + const i = document.createElement("input"); + i.value = f.value; + i.placeholder = f.placeholder ?? ""; + i.autocomplete = "off"; + i.spellcheck = false; + l.append(i); + box.append(l); + return i; + }); + const row = el("div", "panel-buttons"); + const close = (v: Record | null) => { + back.remove(); + resolve(v); + }; + row.append(textButton("Cancel", "Esc", () => close(null))); + const ok = textButton("OK", "Enter", () => close(Object.fromEntries(fields.map((f, i) => [f.key, inputs[i].value]))), true); + row.append(ok); + box.append(row); + box.addEventListener("submit", (e) => (e.preventDefault(), ok.click())); + // Enter is OK (left to the browser it would "click" the first button: Cancel). + for (const b of row.querySelectorAll("button")) b.type = "button"; + box.addEventListener("keydown", (e) => { + if (e.key === "Escape") close(null); + if (e.key === "Enter") (e.preventDefault(), ok.click()); + e.stopPropagation(); + }); + back.append(box); + document.body.append(back); + inputs[0]?.focus(); + }); + } + + // ------------------------------------------------------------------- panel + + get panelOpen(): boolean { + return this.panelSpec !== null; + } + + showPanel(spec: ValuePanel | null): void { + this.panelSpec = spec; + this.panel.innerHTML = ""; + this.panel.hidden = !spec; + if (!spec) return; + queueMicrotask(() => this.fitPanel()); + this.panel.append(el("div", "panel-title", spec.title)); + const row = el("div", "panel-fields"); + const items: PanelItem[] = [ + ...(spec.fields ?? []).map( + (f): PanelItem => ({ type: "number", label: f.label, value: f.value, kind: f.kind ?? (f.integer ? "int" : f.unit ? "length" : "number"), min: f.min, onInput: f.onInput }), + ), + ...(spec.items ?? []), + ]; + let numberIndex = 0; + for (const it of items) { + if (it.type === "number") row.append(this.numberField(it, numberIndex++, spec)); + else if (it.type === "slot") { + const b = el("button", `slot${it.active ? " active" : ""}${it.filled ? " filled" : ""}`); + b.append(el("span", "slot-label", it.label), el("span", "slot-value", it.value)); + b.addEventListener("click", it.onClick); + row.append(b); + } else if (it.type === "choice") { + const g = el("div", "choice"); + if (it.label) g.append(el("span", "field-label", it.label)); + for (const o of it.options) { + const b = el("button", o.id === it.value ? "active" : "", o.label); + b.addEventListener("click", () => it.onChange(o.id)); + g.append(b); + } + row.append(g); + } else if (it.type === "toggle") { + const b = el("button", `toggle${it.value ? " on" : ""}`, it.label); + b.addEventListener("click", () => it.onChange(!it.value)); + row.append(b); + } else { + const b = el("button", "text-btn"); + if (it.icon) b.innerHTML = icons[it.icon]; + b.append(it.label); + b.addEventListener("click", it.onClick); + row.append(b); + } + } + this.panel.append(row); + const buttons = el("div", "panel-buttons"); + for (const a of spec.actions ?? []) { + const b = toolButton(a, true); + b.addEventListener("click", () => a.run?.()); + buttons.append(b); + } + if (spec.onCancel) buttons.append(textButton("Cancel", "Esc", spec.onCancel)); + if (spec.onDone) buttons.append(textButton("Done", "Enter", spec.onDone, true)); + this.panel.append(buttons); + } + + private numberField(f: Extract, index: number, spec: ValuePanel): HTMLElement { + const kind = f.kind ?? "length"; + const label = el("label", "field"); + label.append(el("span", "field-label", f.label)); + const input = document.createElement("input"); + input.type = "text"; + input.inputMode = "decimal"; + input.autocomplete = "off"; + input.spellcheck = false; + input.value = f.expr ?? shown(f.value, kind); + input.dataset.index = String(index); + input.dataset.kind = kind; + if (f.expr) input.classList.add("has-expr"); + const apply = () => { + const v = evaluate(input.value, kind === "length" ? "length" : kind === "angle" ? "angle" : "number"); + const ok = v !== null && (f.min === undefined || v >= f.min); + input.classList.toggle("invalid", !ok); + if (!ok) return; + // Text with a variable name stays an expression (parametric); plain numbers don't. + const isExpr = isExpression(input.value); + input.classList.toggle("has-expr", isExpr); + f.onExpr?.(isExpr ? input.value.trim() : null); + f.onInput(kind === "int" ? Math.round(v!) : v!); + }; + input.addEventListener("input", apply); + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + apply(); + spec.onDone?.(); + } else if (e.key === "Escape") { + e.preventDefault(); + spec.onCancel?.(); + } else if (e.key === "ArrowUp" || e.key === "ArrowDown") { + e.preventDefault(); + const v = evaluate(input.value, kind === "length" ? "length" : "number") ?? 0; + const step = kind === "length" ? (e.shiftKey ? 10 : 1) : e.shiftKey ? 10 : 1; + const next = v + (e.key === "ArrowUp" ? step : -step) * (kind === "length" ? unitScale() : 1); + input.value = shown(next, kind); + apply(); + } + e.stopPropagation(); + }); + label.append(input); + const unit = kind === "length" ? UNIT_LABEL[units()] : kind === "angle" ? "°" : ""; + if (unit) label.append(el("span", "field-unit", unit)); + if (f.onExpr && this.variableFactory) { + const fx = el("button", "fx-btn", "ƒx"); + fx.title = "Make this value a named variable"; + fx.addEventListener("click", async (e) => { + e.preventDefault(); + const name = await this.variableFactory!(input.value); + if (!name) return; + input.value = name; + apply(); + }); + label.append(fx); + } + return label; + } + + /** Creates a variable from a field's current text; returns its name (set by the app). */ + variableFactory: ((current: string) => Promise) | null = null; + + /** Update displayed values without rebuilding (keeps focus while dragging). */ + updatePanelValues(values: number[]): void { + this.panel.querySelectorAll("input[data-index]").forEach((input) => { + const v = values[Number(input.dataset.index)]; + if (v !== undefined && document.activeElement !== input) input.value = shown(v, input.dataset.kind as FieldKind); + }); + } + + focusPanel(): void { + // Only focus with a keyboard; on touch it would pop the on-screen keyboard. + if (matchMedia("(pointer: fine)").matches) this.panel.querySelector("input")?.select(); + } + + // ----------------------------------------------------------------- history + + renderHistory(features: readonly Feature[], errors: FeatureError[], activeId: string | null, h: HistoryHandlers, warnings: Map = new Map()): void { + this.historyList.innerHTML = ""; + if (features.length === 0) { + this.historyList.append(el("li", "history-empty", "Nothing yet. Start with Sketch.")); + return; + } + for (const f of features) { + const li = el("li", "history-item"); + const err = errors.find((e) => e.featureId === f.id); + if (err) li.classList.add("error"); + if (f.suppressed) li.classList.add("suppressed"); + if (f.id === activeId) li.classList.add("active"); + const name = el("button", "history-name", f.name); + name.title = err ? err.message : "Edit"; + // A step that works but leaves something to look at (e.g. a body that isn't closed). + const warn = warnings.get(f.id); + if (warn && !err) { + const mark = el("span", "history-warn", "!"); + mark.title = warn; + name.prepend(mark); + name.title = warn; + } + name.addEventListener("click", () => h.edit(f.id)); + li.addEventListener("pointerenter", () => h.hover?.(f.id)); + li.addEventListener("pointerleave", () => h.hover?.(null)); + const eye = iconButton(f.suppressed ? "eyeOff" : "eye", f.suppressed ? "Enable" : "Suppress", () => h.toggle(f.id)); + const del = iconButton("trash", "Delete", () => h.remove(f.id)); + li.append(name, eye, del); + if (err) li.append(el("div", "history-error", err.message)); + this.historyList.append(li); + // What was done inside a sketch, step by step. + if (f.type === "sketch" && f.log?.length) { + const steps = f.log; + const shownSteps = steps.length > 12 ? steps.slice(-12) : steps; + const sub = el("li", "history-steps"); + if (steps.length > shownSteps.length) sub.append(el("div", "history-step more", `… ${steps.length - shownSteps.length} earlier`)); + for (const s of shownSteps) { + const row = el("button", "history-step", `${s.op}${s.n > 1 ? ` ×${s.n}` : ""}`); + row.title = "Open the sketch"; + row.addEventListener("click", () => h.edit(f.id)); + sub.append(row); + } + this.historyList.append(sub); + } + } + } +} + +/** Does the text use a variable (a name that isn't a unit suffix)? */ +export function isExpression(text: string): boolean { + return /[a-z_]/i.test(text.replace(/(\d|\))\s*(mm|cm|m|in|ft)\b/gi, "$1")); +} + +function unitScale(): number { + return { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8 }[units()]; +} + +function shown(v: number, kind: FieldKind): string { + if (kind === "length") return trim(toDisplay(v), 4); + if (kind === "int") return String(Math.round(v)); + return trim(v, 4); +} + +function renderTools(host: HTMLElement, items: ToolItem[], onFlyout: (item: ToolItem, btn: HTMLElement) => void, after?: () => void): void { + host.innerHTML = ""; + for (const item of items) { + if (item.id.startsWith("---")) { + host.append(el("div", "tool-sep")); + continue; + } + const b = toolButton(item, true); + b.addEventListener("click", (e) => { + e.stopPropagation(); + if (item.disabled) return; + if (item.children?.length) onFlyout(item, b); + else { + item.run?.(); + after?.(); + } + }); + host.append(b); + } +} + +function toolButton(item: ToolItem, withLabel: boolean): HTMLButtonElement { + const b = document.createElement("button"); + b.className = "tool"; + b.dataset.tool = item.id; + b.classList.toggle("active", !!item.active); + b.classList.toggle("has-children", !!item.children?.length); + b.classList.toggle("disabled", !!item.disabled); + b.title = item.disabled && item.why ? item.why : item.shortcut ? `${item.label} (${item.shortcut})` : item.label; + b.innerHTML = item.swatch ? `` : icons[item.icon]; + if (withLabel) { + const l = el("span", "tool-label"); + const top = el("span", "tool-name", item.label); + if (item.shortcut) top.append(el("kbd", "", item.shortcut)); + l.append(top); + if (item.sub) l.append(el("span", "tool-sub", item.sub)); + b.append(l); + } + return b; +} + +function iconButton(icon: IconName, title: string, run: () => void): HTMLButtonElement { + const b = document.createElement("button"); + b.className = "icon-btn"; + b.title = title; + b.innerHTML = icons[icon]; + b.addEventListener("click", (e) => { + e.stopPropagation(); + run(); + }); + return b; +} + +function textButton(label: string, kbd: string, run: () => void, primary = false): HTMLButtonElement { + const b = document.createElement("button"); + b.className = primary ? "text-btn primary" : "text-btn"; + b.append(label); + if (matchMedia("(pointer: fine)").matches) b.append(el("kbd", "", kbd)); + b.addEventListener("click", run); + return b; +} + +export function el(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text) e.textContent = text; + return e; +} + +export function fmt(v: number): string { + return String(Math.round(v * 1000) / 1000); +} diff --git a/src/units.ts b/src/units.ts new file mode 100644 index 0000000..80e3367 --- /dev/null +++ b/src/units.ts @@ -0,0 +1,137 @@ +// Length units and expression evaluation for every numeric field. +// Internally everything is millimetres. + +import type { Units, Variable } from "./doc/types"; + +export const UNIT_MM: Record = { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8 }; +export const UNIT_LABEL: Record = { mm: "mm", cm: "cm", m: "m", in: "in", ft: "ft" }; + +let current: Units = "mm"; +let variables: Variable[] = []; + +export function setUnits(u: Units): void { + current = u; +} +export function units(): Units { + return current; +} +export function setVariables(v: Variable[]): void { + variables = v; +} + +/** mm → display string in the current unit. */ +export function fmtLen(mm: number, digits = 3): string { + const v = mm / UNIT_MM[current]; + return `${trim(v, digits)} ${UNIT_LABEL[current]}`; +} + +/** mm → number in the current unit (for input fields). */ +export function toDisplay(mm: number): number { + return mm / UNIT_MM[current]; +} + +export function trim(v: number, digits = 3): string { + const p = Math.pow(10, digits); + return String(Math.round(v * p) / p); +} + +/** + * Parse a field value: numbers, + - * / ^ ( ), unit suffixes (25.4mm, 1in, + * 2 ft), and variable names. Plain numbers are in the current unit. + * Returns millimetres for lengths (kind "length"), the raw value otherwise. + */ +export function evaluate(text: string, kind: "length" | "number" | "angle" = "length"): number | null { + try { + const scaleFor = kind === "length" ? UNIT_MM[current] : 1; + const v = new Parser(text, scaleFor, kind === "length", 0).parse(); + return Number.isFinite(v) ? v : null; + } catch { + return null; + } +} + +class Parser { + private i = 0; + constructor( + private s: string, + private defaultScale: number, + private lengths: boolean, + private depth: number, + ) {} + + parse(): number { + const v = this.expr(); + this.ws(); + if (this.i < this.s.length) throw new Error("Unexpected input"); + return v; + } + + private ws() { + while (this.s[this.i] === " ") this.i++; + } + + private expr(): number { + let v = this.term(); + for (;;) { + this.ws(); + const c = this.s[this.i]; + if (c === "+") (this.i++, (v += this.term())); + else if (c === "-") (this.i++, (v -= this.term())); + else return v; + } + } + + private term(): number { + let v = this.factor(); + for (;;) { + this.ws(); + const c = this.s[this.i]; + // Multiplying/dividing two lengths would square units; treat the right side as a plain number. + if (c === "*") (this.i++, (v *= this.factor() / (this.lengths ? this.defaultScale : 1))); + else if (c === "/") (this.i++, (v /= this.factor() / (this.lengths ? this.defaultScale : 1))); + else return v; + } + } + + private factor(): number { + this.ws(); + const c = this.s[this.i]; + if (c === "-") { + this.i++; + return -this.factor(); + } + if (c === "(") { + this.i++; + const v = this.expr(); + this.ws(); + if (this.s[this.i++] !== ")") throw new Error("Missing )"); + // Already in mm; a suffix re-interprets the bracketed number in that unit. + return this.unit(v / this.defaultScale); + } + const num = /^\d*\.?\d+(e[-+]?\d+)?/i.exec(this.s.slice(this.i)); + if (num) { + this.i += num[0].length; + return this.unit(parseFloat(num[0])); + } + const name = /^[a-z_][a-z0-9_]*/i.exec(this.s.slice(this.i)); + if (name) { + this.i += name[0].length; + const variable = variables.find((x) => x.name === name[0]); + if (!variable || this.depth > 8) throw new Error(`Unknown variable ${name[0]}`); + return new Parser(variable.expr, this.defaultScale, this.lengths, this.depth + 1).parse(); + } + throw new Error("Expected a number"); + } + + /** Apply an optional unit suffix; no suffix = current unit. */ + private unit(v: number): number { + this.ws(); + const m = /^(mm|cm|m|in|ft|"|')(?![a-z])/i.exec(this.s.slice(this.i)); + if (m && this.lengths) { + this.i += m[0].length; + const u = m[0] === '"' ? "in" : m[0] === "'" ? "ft" : (m[0].toLowerCase() as Units); + return v * UNIT_MM[u]; + } + return v * this.defaultScale; + } +} diff --git a/src/view/camera.ts b/src/view/camera.ts new file mode 100644 index 0000000..d2037f8 --- /dev/null +++ b/src/view/camera.ts @@ -0,0 +1,265 @@ +import { Box3, MathUtils, OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from "three"; +import type { SavedView, Vec3 } from "../doc/types"; + +const UP = new Vector3(0, 0, 1); +const FOV = 40; + +/** + * Z-up orbit camera: azimuth around Z, elevation above the XY plane. + * Perspective and orthographic share target/distance, so switching is seamless. + */ +export class CameraController { + readonly persp: PerspectiveCamera; + readonly orthoCam: OrthographicCamera; + ortho = false; + target = new Vector3(0, 0, 0); + distance = 300; + azimuth = MathUtils.degToRad(-60); + elevation = MathUtils.degToRad(30); + /** Roll around the view direction (used for face-on views, rotated 90° steps). */ + roll = 0; + animate = true; + /** A chosen point to orbit around (else the view turns about its target). Zoom to fit clears it. */ + pivot: Vector3 | null = null; + private aspect = 1; + private animation: { from: ViewState; to: ViewState; t0: number } | null = null; + + constructor(aspect: number) { + this.persp = new PerspectiveCamera(FOV, aspect, 0.1, 1e7); + this.orthoCam = new OrthographicCamera(-1, 1, 1, -1, -1e7, 1e7); + this.aspect = aspect; + this.update(); + } + + get camera(): PerspectiveCamera | OrthographicCamera { + return this.ortho ? this.orthoCam : this.persp; + } + + setAspect(a: number): void { + this.aspect = a; + this.update(); + } + + setOrtho(on: boolean): void { + this.ortho = on; + this.update(); + } + + orbit(dxPx: number, dyPx: number): void { + this.animation = null; + this.roll = 0; + const az0 = this.azimuth; + const el0 = this.elevation; + this.azimuth -= dxPx * 0.006; + this.elevation = MathUtils.clamp(this.elevation + dyPx * 0.006, -Math.PI / 2 + 1e-4, Math.PI / 2 - 1e-4); + if (this.pivot) { + // Turn the target about the pivot the same way the view turned, so the + // pivot stays put on screen: first about Z (azimuth), then about the + // view's sideways axis (elevation). + const right0 = new Vector3(-Math.sin(az0), Math.cos(az0), 0); + const qEl = new Quaternion().setFromAxisAngle(right0, -(this.elevation - el0)); + const qAz = new Quaternion().setFromAxisAngle(UP, this.azimuth - az0); + const rel = this.target.clone().sub(this.pivot).applyQuaternion(qEl).applyQuaternion(qAz); + this.target.copy(this.pivot).add(rel); + } + this.update(); + } + + /** Pan so the scene follows the pointer. */ + pan(dxPx: number, dyPx: number, viewportHeight: number): void { + this.animation = null; + const worldPerPx = this.worldPerPixel(viewportHeight); + const right = new Vector3().setFromMatrixColumn(this.camera.matrixWorld, 0); + const up = new Vector3().setFromMatrixColumn(this.camera.matrixWorld, 1); + this.target.addScaledVector(right, -dxPx * worldPerPx).addScaledVector(up, dyPx * worldPerPx); + this.update(); + } + + /** factor < 1 zooms in. `toward` keeps that world point under the pointer. */ + zoom(factor: number, toward?: Vector3): void { + this.animation = null; + // 0.001 mm … 1 000 000 mm scenes. + const newDist = MathUtils.clamp(this.distance * factor, 0.005, 5e6); + // A point far off (the ground at the horizon, a bad hit) would fling the + // target away: zoom straight in instead. + if (toward && (!Number.isFinite(toward.x + toward.y + toward.z) || toward.distanceTo(this.target) > this.distance * 20)) toward = undefined; + if (toward) { + const k = 1 - newDist / this.distance; + if (this.ortho) { + // In ortho, only move sideways (depth doesn't change what's under the cursor). + const view = this.viewDir(); + const t = toward.clone().sub(this.target); + t.addScaledVector(view, -t.dot(view)); + this.target.addScaledVector(t, k); + } else { + this.target.lerp(toward, k); + } + } + this.distance = newDist; + this.update(); + } + + worldPerPixel(viewportHeight: number): number { + return (2 * this.distance * Math.tan(MathUtils.degToRad(FOV / 2))) / viewportHeight; + } + + /** Unit vector from the camera towards the target. */ + viewDir(): Vector3 { + return this.target.clone().sub(this.camera.position).normalize(); + } + + /** + * Look along -normal at the target. `xDir` (optional) is the world direction + * that should point right on screen, e.g. a sketch plane's x axis. + */ + lookAlong(normal: Vec3, xDir?: Vec3, target?: Vec3): void { + const n = new Vector3(...normal).normalize(); + const to = this.state(); + if (target) to.target = new Vector3(...target); + to.elevation = MathUtils.clamp(Math.asin(n.z), -Math.PI / 2 + 1e-4, Math.PI / 2 - 1e-4); + to.roll = 0; + const x = new Vector3(...(xDir ?? [1, 0, 0])); + if (Math.abs(n.z) > 0.999) { + // Top/bottom: at the poles the screen's right is (-sin a, cos a, 0). + to.azimuth = Math.atan2(-x.x, x.y); + } else { + to.azimuth = Math.atan2(n.y, n.x); + if (xDir) { + // Tilted planes: roll so xDir points right on screen. + const d = new Vector3(...normal).normalize(); + const right = new Vector3().crossVectors(UP, d).normalize(); + const up = new Vector3().crossVectors(d, right); + to.roll = Math.atan2(x.dot(up), x.dot(right)); + } + } + this.go(to); + } + + /** Rotate the view 90° around the view direction (view cube arrows). */ + rollBy(rad: number): void { + const to = this.state(); + to.roll += rad; + this.go(to); + } + + iso(): void { + this.go({ ...this.state(), azimuth: MathUtils.degToRad(-60), elevation: MathUtils.degToRad(30), roll: 0 }); + } + + fit(box: Box3, animate = true): void { + this.pivot = null; + const finite = (v: Vector3) => Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z); + if (box.isEmpty() || !finite(box.min) || !finite(box.max)) box = new Box3(new Vector3(-50, -50, 0), new Vector3(50, 50, 20)); + const size = box.getSize(new Vector3()).length(); + const center = box.getCenter(new Vector3()); + // Fit the tighter of the vertical and horizontal fields of view (portrait phones). + const tanV = Math.tan(MathUtils.degToRad(FOV / 2)); + const tanH = tanV * this.aspect; + const distance = (Math.max(size, 0.01) / (2 * Math.min(tanV, tanH))) * 1.15; + const to = { ...this.state(), target: center, distance }; + if (animate) this.go(to); + else this.applyState(to); + } + + savedView(name: string): SavedView { + return { name, target: this.target.toArray() as Vec3, distance: this.distance, azimuth: this.azimuth, elevation: this.elevation, ortho: this.ortho }; + } + + restore(v: SavedView): void { + this.ortho = v.ortho; + this.go({ target: new Vector3(...v.target), distance: v.distance, azimuth: v.azimuth, elevation: v.elevation, roll: 0 }); + } + + /** Advance animations; returns true while animating. */ + tick(now: number): boolean { + if (!this.animation) return false; + const { from, to, t0 } = this.animation; + const t = Math.min(1, (now - t0) / 380); + const e = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2; + let dAz = to.azimuth - from.azimuth; + dAz = Math.atan2(Math.sin(dAz), Math.cos(dAz)); + let dRoll = to.roll - from.roll; + dRoll = Math.atan2(Math.sin(dRoll), Math.cos(dRoll)); + this.applyState( + { + target: from.target.clone().lerp(to.target, e), + distance: MathUtils.lerp(from.distance, to.distance, e), + azimuth: from.azimuth + dAz * e, + elevation: MathUtils.lerp(from.elevation, to.elevation, e), + roll: from.roll + dRoll * e, + }, + ); + if (t >= 1) this.animation = null; + return true; + } + + get animating(): boolean { + return this.animation !== null; + } + + private state(): ViewState { + return { target: this.target.clone(), distance: this.distance, azimuth: this.azimuth, elevation: this.elevation, roll: this.roll }; + } + + private go(to: ViewState): void { + if (!this.animate) { + this.applyState(to); + return; + } + this.animation = { from: this.state(), to, t0: performance.now() }; + } + + private applyState(s: ViewState): void { + // Never take a broken view (NaN/Infinity would blank everything, grid included). + const ok = [s.target.x, s.target.y, s.target.z, s.distance, s.azimuth, s.elevation, s.roll].every(Number.isFinite) && s.distance > 0; + if (!ok) return; + this.target.copy(s.target); + this.distance = s.distance; + this.azimuth = s.azimuth; + this.elevation = s.elevation; + this.roll = s.roll; + this.update(); + } + + /** The last view that was valid: restored if something ever corrupts it. */ + private good: ViewState | null = null; + + update(): void { + const valid = [this.target.x, this.target.y, this.target.z, this.distance, this.azimuth, this.elevation, this.roll].every(Number.isFinite) && this.distance > 0; + if (!valid) { + const g = this.good ?? { target: new Vector3(), distance: 300, azimuth: MathUtils.degToRad(-60), elevation: MathUtils.degToRad(30), roll: 0 }; + this.target.copy(g.target); + Object.assign(this, { distance: g.distance, azimuth: g.azimuth, elevation: g.elevation, roll: g.roll }); + this.animation = null; + } else this.good = this.state(); + const ce = Math.cos(this.elevation); + const dir = new Vector3(ce * Math.cos(this.azimuth), ce * Math.sin(this.azimuth), Math.sin(this.elevation)); + for (const cam of [this.persp, this.orthoCam] as Camera[]) { + cam.position.copy(this.target).addScaledVector(dir, this.distance); + cam.up.copy(UP); + // Near the poles, derive "up" from the azimuth so the view doesn't spin. + if (Math.abs(dir.z) > 0.99) cam.up.set(-Math.cos(this.azimuth) * Math.sign(dir.z), -Math.sin(this.azimuth) * Math.sign(dir.z), 0); + cam.lookAt(this.target); + if (this.roll) cam.rotateZ(this.roll); + } + this.persp.aspect = this.aspect; + this.persp.near = Math.max(1e-4, this.distance / 2000); + this.persp.far = this.distance * 2000; + this.persp.updateProjectionMatrix(); + const h = this.distance * Math.tan(MathUtils.degToRad(FOV / 2)); + Object.assign(this.orthoCam, { left: -h * this.aspect, right: h * this.aspect, top: h, bottom: -h }); + this.orthoCam.near = -this.distance * 1000; + this.orthoCam.far = this.distance * 1000; + this.orthoCam.updateProjectionMatrix(); + this.persp.updateMatrixWorld(); + this.orthoCam.updateMatrixWorld(); + } +} + +interface ViewState { + target: Vector3; + distance: number; + azimuth: number; + elevation: number; + roll: number; +} diff --git a/src/view/grid.ts b/src/view/grid.ts new file mode 100644 index 0000000..ce73111 --- /dev/null +++ b/src/view/grid.ts @@ -0,0 +1,107 @@ +import { DoubleSide, Matrix4, Mesh, PlaneGeometry, ShaderMaterial, Vector3 } from "three"; +import type { PlaneDef } from "../doc/types"; +import { planeY } from "../geom"; + +/** + * Infinite-looking grid that adapts its spacing to the zoom level (powers of + * ten, 0.001 mm … 1 000 000 mm), or stays at a locked step. It lies on the + * ground, or on the active sketch plane while sketching. + */ +export class AdaptiveGrid { + readonly mesh: Mesh; + /** Current minor step in mm (also used for grid snapping). */ + step = 1; + locked = false; + lockedStep = 1; + private plane: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; + private material: ShaderMaterial; + + constructor() { + this.material = new ShaderMaterial({ + transparent: true, + depthWrite: false, + side: DoubleSide, + uniforms: { + uStep: { value: 1 }, + uFade: { value: 0 }, + uCenter: { value: [0, 0] }, + uRadius: { value: 100 }, + // Quad centre (u, v) on the plane and its size: turns quad coords into plane coords. + uLocal: { value: [0, 0, 1] }, + }, + vertexShader: /* glsl */ ` + uniform vec3 uLocal; + varying vec2 vUv; + void main() { + vUv = uLocal.xy + position.xy * uLocal.z; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + }`, + fragmentShader: /* glsl */ ` + uniform float uStep; + uniform float uFade; + uniform vec2 uCenter; + uniform float uRadius; + varying vec2 vUv; + float lines(vec2 p, float s) { + vec2 g = abs(fract(p / s - 0.5) - 0.5) / fwidth(p / s); + return 1.0 - min(min(g.x, g.y), 1.0); + } + void main() { + vec2 p = vUv; + float minor = lines(p, uStep) * (1.0 - uFade); + float mid = lines(p, uStep * 10.0); + float major = lines(p, uStep * 100.0); + float a = max(max(minor * 0.22, mid * 0.38), major * 0.55); + float d = length(p - uCenter) / uRadius; + a *= 1.0 - smoothstep(0.55, 1.0, d); + if (a < 0.01) discard; + gl_FragColor = vec4(vec3(0.78), a); + }`, + }); + this.mesh = new Mesh(new PlaneGeometry(1, 1), this.material); + this.mesh.renderOrder = -1; + this.mesh.matrixAutoUpdate = false; + this.mesh.frustumCulled = false; + } + + setPlane(p: PlaneDef): void { + this.plane = p; + } + + /** Recompute spacing and placement for the current view. */ + update(worldPerPixel: number, target: Vector3, distance: number, eye?: Vector3): void { + let fade = 0; + if (this.locked) { + this.step = this.lockedStep; + } else { + // Minor lines at least ~10 px apart; fade them in as they get there. + const raw = worldPerPixel * 10; + const exp = Math.log10(raw); + this.step = Math.pow(10, Math.ceil(exp)); + fade = 1 - (Math.ceil(exp) - exp); + fade = Math.max(0, Math.min(1, (fade - 0.6) / 0.4)); + } + const n = new Vector3(...this.plane.normal); + const x = new Vector3(...this.plane.xDir); + const y = new Vector3(...planeY(this.plane)); + const o = new Vector3(...this.plane.origin); + // Centre the quad under the camera target (projected on the plane). + const rel = target.clone().sub(o); + const cu = rel.dot(x); + const cv = rel.dot(y); + // Big enough to reach the horizon from where the camera is (it can sit far + // above the plane while its target is close, after zooming towards a point). + const height = eye ? Math.abs(eye.clone().sub(o).dot(n)) : 0; + const size = Math.max(distance * 6, height * 12, this.step * 400); + // The quad spans local coords [cu ± size/2]; vUv carries plane coordinates. + const m = new Matrix4().makeBasis(x, y, n).setPosition(o); + const local = new Matrix4().makeScale(size, size, 1).setPosition(cu, cv, 0); + this.mesh.matrix.copy(m.multiply(local)); + this.mesh.matrixWorldNeedsUpdate = true; + this.material.uniforms.uStep.value = this.step; + this.material.uniforms.uFade.value = fade; + this.material.uniforms.uCenter.value = [cu, cv]; + this.material.uniforms.uRadius.value = size / 2; + this.material.uniforms.uLocal.value = [cu, cv, size]; + } +} diff --git a/src/view/input.ts b/src/view/input.ts new file mode 100644 index 0000000..25199da --- /dev/null +++ b/src/view/input.ts @@ -0,0 +1,285 @@ +// One input model for mouse, touch and pen (see docs/ARCHITECTURE.md §5). + +import type { Viewport } from "./viewport"; + +export interface ToolPointer { + x: number; + y: number; + type: "mouse" | "pen" | "touch"; + shift: boolean; + /** Ctrl/Cmd/Shift held at press: add to the selection. */ + add?: boolean; + /** Pick tolerance in px; fingers are fat. */ + tol: number; +} + +export interface PointerHandler { + /** Return true to capture the drag (e.g. grabbed a handle, started drawing). */ + down?(p: ToolPointer): boolean; + drag?(p: ToolPointer): void; + up?(p: ToolPointer): void; + tap?(p: ToolPointer, count: number): void; + hover?(p: ToolPointer | null): void; + /** Right-click without dragging (e.g. end a line chain). */ + context?(p: ToolPointer): void; + /** + * The pointer moved past the tap slop without `down` capturing it: return + * true to take this as a drag of what was under the press (`from`), so a + * plain tap on the same thing still selects it. + */ + dragStart?(from: ToolPointer): boolean; + /** Box (window) selection with mouse/pen; `final` on release. */ + box?(a: { x: number; y: number }, b: { x: number; y: number }, final: boolean, add: boolean): void; +} + +const TAP_SLOP = { mouse: 4, pen: 6, touch: 10 }; +const DOUBLE_TAP_MS = 350; + +interface Tracked { + id: number; + type: ToolPointer["type"]; + x0: number; + y0: number; + x: number; + y: number; + button: number; + shift: boolean; +} + +export class InputRouter { + handler: PointerHandler = {}; + private pointers = new Map(); + private mode: "idle" | "pending" | "captured" | "orbit" | "pan" | "pinch" | "box" | "ended" | "rpending" = "idle"; + + /** A tool is holding a drag (keys typed now go to it). */ + get dragging(): boolean { + return this.mode === "captured"; + } + + /** The drag was finished from the keyboard: ignore the rest until release. */ + endDrag(): void { + if (this.mode === "captured") this.mode = "ended"; + } + private marquee = document.createElement("div"); + private modifiers = false; + private penDown = false; + private lastPinch: { d: number; cx: number; cy: number } | null = null; + private lastTap = { t: 0, x: 0, y: 0, count: 0 }; + + constructor(private view: Viewport) { + const el = view.canvas; + el.style.touchAction = "none"; + this.marquee.id = "marquee"; + this.marquee.hidden = true; + document.body.append(this.marquee); + el.addEventListener("pointerdown", (e) => this.onDown(e)); + el.addEventListener("pointermove", (e) => this.onMove(e)); + el.addEventListener("pointerup", (e) => this.onUp(e)); + el.addEventListener("pointercancel", (e) => this.onCancel(e)); + el.addEventListener("pointerleave", (e) => { + if (e.pointerType !== "touch" && this.mode === "idle") this.handler.hover?.(null); + }); + el.addEventListener("contextmenu", (e) => e.preventDefault()); + el.addEventListener("wheel", (e) => this.onWheel(e), { passive: false }); + // Stop iPad Safari's own gestures (Scribble, magnifier, page zoom) on the canvas. + el.addEventListener("touchstart", (e) => e.preventDefault(), { passive: false }); + el.addEventListener("gesturestart", (e) => e.preventDefault()); + } + + private local(e: PointerEvent | WheelEvent): [number, number] { + const r = this.view.canvas.getBoundingClientRect(); + return [e.clientX - r.left, e.clientY - r.top]; + } + + private tp(t: Tracked): ToolPointer { + return { x: t.x, y: t.y, type: t.type, shift: t.shift, add: this.modifiers, tol: t.type === "touch" ? 18 : 8 }; + } + + private onDown(e: PointerEvent): void { + const type = e.pointerType as ToolPointer["type"]; + // Palm rejection: while the pen touches the screen, ignore fingers. + if (type === "touch" && this.penDown) return; + if (type === "pen") this.penDown = true; + try { + this.view.canvas.setPointerCapture(e.pointerId); + } catch { + // Synthetic/expired pointers can't be captured; tracking still works. + } + const [x, y] = this.local(e); + const t: Tracked = { id: e.pointerId, type, x0: x, y0: y, x, y, button: e.button, shift: e.shiftKey }; + this.pointers.set(e.pointerId, t); + + if (type === "touch" && this.pointers.size === 2) { + // Second finger: abandon whatever the first finger was doing and pinch. + if (this.mode === "captured") this.handler.up?.(this.tp(t)); + this.mode = "pinch"; + this.lastPinch = this.pinchState(); + return; + } + if (this.pointers.size > 1) return; + + // Mouse: right-drag orbits, middle-drag (or shift+right) pans, alt+left orbits (trackpads). + if (type === "mouse" && (e.button === 1 || (e.button === 2 && e.shiftKey))) { + this.mode = "pan"; + return; + } + // Right button: a drag orbits, a click is a "context" action (decided on move/up). + if (type === "mouse" && e.button === 2) { + this.mode = "rpending"; + return; + } + if (type === "mouse" && e.button === 0 && e.altKey) { + this.mode = "orbit"; + return; + } + this.modifiers = e.ctrlKey || e.metaKey || e.shiftKey; + if (this.handler.down?.(this.tp(t))) { + this.mode = "captured"; + return; + } + this.mode = "pending"; + } + + private onMove(e: PointerEvent): void { + const [x, y] = this.local(e); + const t = this.pointers.get(e.pointerId); + if (!t) { + if (e.pointerType !== "touch" && this.mode === "idle") { + // At most one hover pick per frame: mice report far more often than the screen redraws. + this.hoverAt = { x, y, type: e.pointerType as ToolPointer["type"], shift: e.shiftKey, tol: 8 }; + this.hoverFrame ||= requestAnimationFrame(() => { + this.hoverFrame = 0; + if (this.hoverAt && this.mode === "idle") this.handler.hover?.(this.hoverAt); + }); + } + return; + } + const dx = x - t.x; + const dy = y - t.y; + t.x = x; + t.y = y; + t.shift = e.shiftKey; + + switch (this.mode) { + case "rpending": + if (Math.hypot(x - t.x0, y - t.y0) >= TAP_SLOP.mouse) this.mode = "orbit"; + return; + case "pending": { + if (Math.hypot(x - t.x0, y - t.y0) < TAP_SLOP[t.type]) return; + if (this.handler.dragStart?.({ ...this.tp(t), x: t.x0, y: t.y0 })) { + this.mode = "captured"; + this.handler.drag?.(this.tp(t)); + return; + } + // Mouse/pen drag on empty space = box selection; a finger orbits. + this.mode = t.type !== "touch" && this.handler.box ? "box" : "orbit"; + return; + } + case "box": { + const a = { x: t.x0, y: t.y0 }; + const b = { x, y }; + const r = this.view.canvas.getBoundingClientRect(); + Object.assign(this.marquee.style, { + left: `${r.left + Math.min(a.x, b.x)}px`, + top: `${r.top + Math.min(a.y, b.y)}px`, + width: `${Math.abs(b.x - a.x)}px`, + height: `${Math.abs(b.y - a.y)}px`, + }); + this.marquee.hidden = false; + this.handler.box?.(a, b, false, this.modifiers); + return; + } + case "captured": + this.handler.drag?.(this.tp(t)); + return; + case "orbit": + this.view.cam.orbit(dx, dy); + this.view.requestRender(); + return; + case "pan": + this.view.cam.pan(dx, dy, this.view.height); + this.view.requestRender(); + return; + case "pinch": { + const s = this.pinchState(); + if (!s || !this.lastPinch) return; + this.view.cam.pan(s.cx - this.lastPinch.cx, s.cy - this.lastPinch.cy, this.view.height); + if (s.d > 0 && this.lastPinch.d > 0) { + this.view.cam.zoom(this.lastPinch.d / s.d, this.view.worldUnder(s.cx, s.cy)); + } + this.lastPinch = s; + this.view.requestRender(); + return; + } + } + } + + private onUp(e: PointerEvent): void { + const t = this.pointers.get(e.pointerId); + if (e.pointerType === "pen") this.penDown = false; + if (!t) return; + this.pointers.delete(e.pointerId); + if (this.mode === "pinch") { + // Lifting one finger of a pinch must not orbit with the remaining one. + if (this.pointers.size === 0) this.mode = "idle"; + else this.lastPinch = null; + return; + } + if (this.pointers.size > 0) return; + const mode = this.mode; + this.mode = "idle"; + if (mode === "captured") this.handler.up?.(this.tp(t)); + if (mode === "pending") this.emitTap(t); + if (mode === "rpending") this.handler.context?.(this.tp(t)); + if (mode === "box") { + this.marquee.hidden = true; + this.handler.box?.({ x: t.x0, y: t.y0 }, { x: t.x, y: t.y }, true, this.modifiers); + } + } + + private onCancel(e: PointerEvent): void { + if (e.pointerType === "pen") this.penDown = false; + const t = this.pointers.get(e.pointerId); + this.pointers.delete(e.pointerId); + if (this.pointers.size === 0) { + if (this.mode === "captured" && t) this.handler.up?.(this.tp(t)); + this.mode = "idle"; + } + } + + private hoverAt: ToolPointer | null = null; + private hoverFrame = 0; + + private emitTap(t: Tracked): void { + const now = performance.now(); + const near = Math.hypot(t.x - this.lastTap.x, t.y - this.lastTap.y) < 20; + const count = now - this.lastTap.t < DOUBLE_TAP_MS && near ? this.lastTap.count + 1 : 1; + this.lastTap = { t: now, x: t.x, y: t.y, count }; + this.handler.tap?.(this.tp(t), count); + } + + private pinchState(): { d: number; cx: number; cy: number } | null { + const pts = [...this.pointers.values()]; + if (pts.length < 2) return null; + const [a, b] = pts; + return { d: Math.hypot(a.x - b.x, a.y - b.y), cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2 }; + } + + private onWheel(e: WheelEvent): void { + e.preventDefault(); + const [x, y] = this.local(e); + if (e.ctrlKey || !isTrackpadPan(e)) { + // Mouse wheel, or trackpad pinch (reported as ctrl+wheel). + const factor = Math.exp(e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)); + this.view.cam.zoom(factor, this.view.worldUnder(x, y)); + } else { + this.view.cam.pan(-e.deltaX, -e.deltaY, this.view.height); + } + this.view.requestRender(); + } +} + +/** Trackpads send pixel deltas with horizontal components; wheels send lines or big steps. */ +function isTrackpadPan(e: WheelEvent): boolean { + return e.deltaMode === 0 && e.deltaX !== 0; +} diff --git a/src/view/viewcube.ts b/src/view/viewcube.ts new file mode 100644 index 0000000..e6e7952 --- /dev/null +++ b/src/view/viewcube.ts @@ -0,0 +1,232 @@ +import { + AmbientLight, + BoxGeometry, + CanvasTexture, + DirectionalLight, + EdgesGeometry, + Group, + LineBasicMaterial, + LineSegments, + Matrix4, + Mesh, + MeshBasicMaterial, + MeshLambertMaterial, + OrthographicCamera, + PlaneGeometry, + Raycaster, + Scene, + SRGBColorSpace, + Vector2, + Vector3, + WebGLRenderer, +} from "three"; +import type { Vec3 } from "../doc/types"; +import type { Viewport } from "./viewport"; + +const PX = 110; + +interface FaceDef { + label: string; + n: Vec3; + /** Screen-right and screen-up directions when looking at the face (Z-up world). */ + u: Vec3; + up: Vec3; +} + +const FACES: FaceDef[] = [ + { label: "TOP", n: [0, 0, 1], u: [1, 0, 0], up: [0, 1, 0] }, + { label: "BOTTOM", n: [0, 0, -1], u: [1, 0, 0], up: [0, -1, 0] }, + { label: "FRONT", n: [0, -1, 0], u: [1, 0, 0], up: [0, 0, 1] }, + { label: "BACK", n: [0, 1, 0], u: [-1, 0, 0], up: [0, 0, 1] }, + { label: "RIGHT", n: [1, 0, 0], u: [0, 1, 0], up: [0, 0, 1] }, + { label: "LEFT", n: [-1, 0, 0], u: [0, -1, 0], up: [0, 0, 1] }, +]; + +/** + * View cube rendered with its own tiny three.js scene, rotated with the main + * camera. Click a face, edge or corner (26 zones) to look from there; drag to orbit. + */ +export class ViewCube { + readonly el: HTMLElement; + private canvas: HTMLCanvasElement; + private renderer: WebGLRenderer; + private scene = new Scene(); + private camera = new OrthographicCamera(-1.05, 1.05, 1.05, -1.05, 0.1, 10); + private faces: Mesh[] = []; + private hover = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ color: 0x3d8bff, transparent: true, opacity: 0.55, depthTest: false })); + private raycaster = new Raycaster(); + private lastKey = ""; + private dragged = false; + + constructor(private view: Viewport) { + this.el = document.createElement("div"); + this.el.id = "viewcube"; + this.canvas = document.createElement("canvas"); + this.canvas.style.width = this.canvas.style.height = `${PX}px`; + this.el.append(this.canvas); + this.renderer = new WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: true }); + this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + this.renderer.setSize(PX, PX, false); + + const cube = new Group(); + for (const f of FACES) { + const mesh = new Mesh(new PlaneGeometry(1, 1), new MeshLambertMaterial({ map: labelTexture(f.label) })); + mesh.matrixAutoUpdate = false; + mesh.matrix.copy(basis(f.u, f.up, f.n).setPosition(new Vector3(...f.n).multiplyScalar(0.5))); + cube.add(mesh); + this.faces.push(mesh); + } + const edges = new LineSegments(new EdgesGeometry(new BoxGeometry(1, 1, 1)), new LineBasicMaterial({ color: 0x8b93a3 })); + cube.add(edges); + // Small world axes at the cube's corner. + for (const [d, c] of [[[1, 0, 0], 0xe0584f], [[0, 1, 0], 0x5fbf5a], [[0, 0, 1], 0x4f8ce0]] as [Vec3, number][]) { + const g = new BoxGeometry(d[0] ? 0.55 : 0.025, d[1] ? 0.55 : 0.025, d[2] ? 0.55 : 0.025); + const m = new Mesh(g, new MeshBasicMaterial({ color: c })); + m.position.set(-0.5 + d[0] * 0.275, -0.5 + d[1] * 0.275, -0.5 + d[2] * 0.275); + cube.add(m); + } + this.hover.visible = false; + this.hover.matrixAutoUpdate = false; + this.hover.renderOrder = 5; + this.scene.add(cube, this.hover, new AmbientLight(0xffffff, 1.6)); + const light = new DirectionalLight(0xffffff, 1.2); + light.position.set(0.5, -1, 2); + this.camera.add(light); + this.scene.add(this.camera); + + const rollL = button("⟲", "Rotate view 90° left", () => view.cam.rollBy(Math.PI / 2)); + const rollR = button("⟳", "Rotate view 90° right", () => view.cam.rollBy(-Math.PI / 2)); + rollL.className = "vc-roll left"; + rollR.className = "vc-roll right"; + this.el.append(rollL, rollR); + this.wire(); + view.frameHooks.add(() => this.render()); + } + + private wire(): void { + let last: { x: number; y: number } | null = null; + this.canvas.addEventListener("pointerdown", (e) => { + last = { x: e.clientX, y: e.clientY }; + this.dragged = false; + this.canvas.setPointerCapture(e.pointerId); + }); + this.canvas.addEventListener("pointermove", (e) => { + if (last) { + const dx = e.clientX - last.x; + const dy = e.clientY - last.y; + if (Math.abs(dx) + Math.abs(dy) > 1) this.dragged = true; + if (this.dragged) { + this.view.cam.orbit(dx * 2, dy * 2); + this.view.requestRender(); + } + last = { x: e.clientX, y: e.clientY }; + return; + } + this.setHover(this.zoneAt(e)); + }); + this.canvas.addEventListener("pointerleave", () => this.setHover(null)); + this.canvas.addEventListener("pointerup", (e) => { + last = null; + if (this.dragged) return; + const zone = this.zoneAt(e); + if (!zone) return; + const face = FACES.find((f) => f.n.every((v, i) => v === zone[i])); + const n = new Vector3(...zone).normalize().toArray() as Vec3; + // Faces get an upright view; edges/corners keep the current spin. + this.view.cam.lookAlong(n, face?.u); + this.view.requestRender(); + }); + } + + /** Zone under the pointer as a vector of -1/0/1 per axis (face, edge or corner). */ + private zoneAt(e: PointerEvent): Vec3 | null { + const r = this.canvas.getBoundingClientRect(); + const ndc = new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); + this.raycaster.setFromCamera(ndc, this.camera); + const hit = this.raycaster.intersectObjects(this.faces, false)[0]; + if (!hit) return null; + const p = hit.point; + // Matches the texture: outer 0.2 of each face is an edge/corner band. + const z = (v: number) => (v > 0.3 ? 1 : v < -0.3 ? -1 : 0); + return [z(p.x), z(p.y), z(p.z)]; + } + + private setHover(zone: Vec3 | null): void { + this.hover.visible = !!zone; + this.canvas.style.cursor = zone ? "pointer" : "grab"; + if (zone) { + // A small tile at the zone, on the face of the axis with a ±1 that faces us most. + const n = new Vector3(...zone); + const dir = new Vector3(0, 0, 1).applyQuaternion(this.camera.quaternion); + const axes = [0, 1, 2].filter((i) => zone[i] !== 0).sort((a, b) => Math.abs(dir.getComponent(b)) - Math.abs(dir.getComponent(a))); + const k = axes[0]; + const f = FACES.find((x) => x.n[k] === zone[k])!; + // Matches zoneAt(): the middle 0.6 of each axis is "face", the outer 0.2 "edge". + const size = [0, 1, 2].map((i) => (zone[i] === 0 ? 0.6 : 0.2)); + const center = n.clone().multiplyScalar(0.4); + center.setComponent(k, zone[k] * 0.502); + const u = new Vector3(...f.u); + const up = new Vector3(...f.up); + const su = Math.abs(u.dot(new Vector3(size[0], size[1], size[2]))); + const sv = Math.abs(up.dot(new Vector3(size[0], size[1], size[2]))); + this.hover.matrix.copy(basis(f.u, f.up, f.n).multiply(new Matrix4().makeScale(su, sv, 1)).setPosition(center)); + } + this.lastKey = ""; + } + + private render(): void { + const main = this.view.camera; + const key = main.quaternion.toArray().map((x) => x.toFixed(4)).join() + this.hover.visible + this.hover.matrix.elements[12]; + if (key === this.lastKey) return; + this.lastKey = key; + this.camera.quaternion.copy(main.quaternion); + this.camera.position.set(0, 0, 3).applyQuaternion(main.quaternion); + this.camera.updateMatrixWorld(); + this.renderer.render(this.scene, this.camera); + } +} + +function basis(u: Vec3, up: Vec3, n: Vec3): Matrix4 { + return new Matrix4().makeBasis(new Vector3(...u), new Vector3(...up), new Vector3(...n)); +} + +function labelTexture(text: string): CanvasTexture { + const c = document.createElement("canvas"); + c.width = c.height = 128; + const g = c.getContext("2d")!; + g.fillStyle = "#4a505c"; + g.fillRect(0, 0, 128, 128); + g.strokeStyle = "#6b7383"; + g.lineWidth = 6; + g.strokeRect(3, 3, 122, 122); + // Zone borders: the middle is the face view, the outer bands edges (45°), the corners iso views. + g.strokeStyle = "rgba(160, 170, 190, 0.35)"; + g.lineWidth = 2; + for (const v of [25.6, 102.4]) { + g.beginPath(); + g.moveTo(v, 0); + g.lineTo(v, 128); + g.moveTo(0, v); + g.lineTo(128, v); + g.stroke(); + } + g.fillStyle = "#e9ecf1"; + g.font = `600 ${text.length > 5 ? 22 : 26}px system-ui, sans-serif`; + g.textAlign = "center"; + g.textBaseline = "middle"; + g.fillText(text, 64, 66); + const t = new CanvasTexture(c); + t.colorSpace = SRGBColorSpace; + return t; +} + +function button(text: string, title: string, run: () => void): HTMLButtonElement { + const b = document.createElement("button"); + b.textContent = text; + b.title = title; + b.addEventListener("click", (e) => { + e.stopPropagation(); + run(); + }); + return b; +} diff --git a/src/view/viewport.ts b/src/view/viewport.ts new file mode 100644 index 0000000..0d9516d --- /dev/null +++ b/src/view/viewport.ts @@ -0,0 +1,1109 @@ +import { + CanvasTexture, + AmbientLight, + BackSide, + Box3, + BufferAttribute, + BufferGeometry, + Color, + DirectionalLight, + DoubleSide, + EdgesGeometry, + Float32BufferAttribute, + FrontSide, + Group, + HemisphereLight, + Line, + LineBasicMaterial, + LineDashedMaterial, + LineSegments, + Matrix4, + Mesh, + MeshBasicMaterial, + MeshStandardMaterial, + Object3D, + Path, + Plane, + PlaneGeometry, + Points, + PointsMaterial, + Raycaster, + Scene, + Shape, + ShapeGeometry, + SRGBColorSpace, + TextureLoader, + Vector2, + Vector3, + WebGLRenderer, +} from "three"; +import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js"; +import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js"; +import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js"; +import type { ImageFeature, PlaneDef, SketchEntity, SketchFeature, Vec2, Vec3 } from "../doc/types"; +import { FRONT, GROUND, RIGHT, planeY } from "../geom"; +import type { BodyMesh, ConstructionInfo, EdgeInfo, FaceInfo } from "../kernel/protocol"; +import { settings } from "../settings"; +import { pointsOf } from "../sketch/constraints"; +import { entityPolylines } from "../sketch/curves"; +import { arrangement } from "../sketch/regions"; +import { CameraController } from "./camera"; +import { AdaptiveGrid } from "./grid"; + +export type PickHit = + | { kind: "face"; body: string; face: number; point: Vec3 } + | { kind: "edge"; body: string; edge: number; point: Vec3 } + | { kind: "vertex"; body: string; vertex: number; point: Vec3 } + | { kind: "profile"; sketch: string; region: number; point: Vec3 } + | { kind: "curve"; sketch: string; entity: string; point: Vec3 } + | { kind: "point"; sketch: string; entity: string; p: string; point: Vec3 } + | { kind: "image"; id: string; point: Vec3 } + | { kind: "plane"; id: string; point: Vec3 } + | { kind: "axis"; id: string; point: Vec3 }; + +export type Highlight = + | { kind: "face"; body: string; face: number } + | { kind: "edge"; body: string; edge: number } + | { kind: "vertex"; body: string; vertex: number } + | { kind: "body"; body: string } + | { kind: "profile"; sketch: string; region: number } + | { kind: "curve"; sketch: string; entity: string } + | { kind: "point"; sketch: string; entity: string; p: string } + | { kind: "image"; id: string } + | { kind: "plane"; id: string } + | { kind: "axis"; id: string }; + +const WORLD_AXIS_DIRS: Record = { X: [1, 0, 0], Y: [0, 1, 0], Z: [0, 0, 1] }; + +/** Round dots for points (three.js draws points as squares; squares are kept for midpoints). */ +let dotTexture: CanvasTexture | null = null; +export function dotMaterial(opts: { color: number; size: number; depthTest?: boolean; opacity?: number }): PointsMaterial { + if (!dotTexture) { + const c = document.createElement("canvas"); + c.width = c.height = 64; + const g = c.getContext("2d")!; + g.fillStyle = "#fff"; + g.beginPath(); + g.arc(32, 32, 30, 0, Math.PI * 2); + g.fill(); + dotTexture = new CanvasTexture(c); + } + return new PointsMaterial({ color: opts.color, size: opts.size, sizeAttenuation: false, depthTest: opts.depthTest ?? false, map: dotTexture, alphaTest: 0.5, transparent: true, opacity: opts.opacity ?? 1 }); +} + +export interface PickOptions { + edgeTolPx?: number; + profiles?: boolean; + bodies?: boolean; + edges?: boolean; + curves?: boolean | string; + planes?: boolean; + axes?: boolean; + /** The world X/Y/Z axes count as axes (ids "X", "Y", "Z") — for axis/direction slots. */ + worldAxes?: boolean; + vertices?: boolean; + images?: boolean; + /** Planes win even when a body is in front (picking a sketch/section plane). */ + planesFirst?: boolean; +} + +/** A sketch as drawn: its own curves plus the face outline it sits on (if any). */ +export type SketchView = SketchFeature & { boundary?: SketchEntity[] }; + +/** The three origin planes, addressable like construction planes. */ +export const ORIGIN_PLANES: Record = { XY: GROUND, XZ: FRONT, YZ: RIGHT }; + +const COLORS = { + body: 0xb9bec7, + edge: 0x23262b, + hover: 0x7fb2ff, + select: 0x2f7bff, + sketch: 0xe8e8e8, + sketchActive: 0xffc23d, + construction: 0x9aa3b5, + profile: 0x4d8dff, + plane: 0x8fb4ff, + cap: 0xff8fb8, +}; + +interface BodyView { + data: BodyMesh; + mesh: Mesh; + cap: Mesh; + edges: LineSegments; + hidden: LineSegments; + /** Unique edge endpoints (the body's vertices). */ + vertices: Vector3[]; +} + +export class Viewport { + readonly renderer: WebGLRenderer; + readonly scene = new Scene(); + readonly cam: CameraController; + readonly overlay = new Group(); + readonly grid = new AdaptiveGrid(); + /** Called before each render, e.g. to keep handles a constant screen size. */ + readonly frameHooks = new Set<() => void>(); + private bodiesGroup = new Group(); + private sketchGroup = new Group(); + private constructionGroup = new Group(); + private imageGroup = new Group(); + private highlightGroup = new Group(); + private axesGroup: Object3D; + private bodies = new Map(); + private profileMeshes: Mesh[] = []; + private curveLines: { sketch: string; entity: string; pts: Vector3[] }[] = []; + private planeMeshes: Mesh[] = []; + private axisLines: { id: string; a: Vector3; b: Vector3 }[] = []; + private raycaster = new Raycaster(); + private dirty = true; + private light = new DirectionalLight(0xffffff, 1.6); + private lineMaterials: LineMaterial[] = []; + private sketches: SketchView[] = []; + private construction: { planes: ConstructionInfo[]; axes: ConstructionInfo[] } = { planes: [], axes: [] }; + private showOriginPlanes = false; + private clip: Plane | null = null; + private bodyMat: MeshStandardMaterial; + private capMat: MeshBasicMaterial; + private edgeMat: LineBasicMaterial; + private hiddenMat: LineDashedMaterial; + + constructor(readonly canvas: HTMLCanvasElement) { + this.renderer = new WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true }); + this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + this.renderer.localClippingEnabled = true; + this.cam = new CameraController(1); + this.scene.background = new Color(0x2b2d31); + + this.scene.add(new HemisphereLight(0xffffff, 0x3a3d44, 1.1)); + this.scene.add(new AmbientLight(0xffffff, 0.25)); + this.scene.add(this.light, this.light.target); + + this.bodyMat = new MeshStandardMaterial({ color: COLORS.body, metalness: 0.05, roughness: 0.55, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1, side: FrontSide }); + // Section caps: back faces seen through the cut, drawn flat — reads as a solid cut. + this.capMat = hatched(new MeshBasicMaterial({ color: COLORS.cap, side: BackSide })); + this.edgeMat = new LineBasicMaterial({ color: COLORS.edge }); + this.hiddenMat = new LineDashedMaterial({ color: 0x6b7280, dashSize: 2, gapSize: 2, depthTest: false, transparent: true, opacity: 0.7 }); + + this.axesGroup = makeAxes(); + this.scene.add(this.grid.mesh, this.axesGroup, this.imageGroup, this.bodiesGroup, this.constructionGroup, this.sketchGroup, this.highlightGroup, this.overlay); + + settings.onChange(() => this.applySettings()); + this.applySettings(); + new ResizeObserver(() => this.resize()).observe(canvas); + this.resize(); + const loop = (t: number) => { + if (this.cam.tick(t)) this.dirty = true; + if (this.tickPulse(t)) this.dirty = true; + if (this.dirty) this.render(); + requestAnimationFrame(loop); + }; + requestAnimationFrame(loop); + } + + get width(): number { + return this.canvas.clientWidth; + } + get height(): number { + return this.canvas.clientHeight; + } + get camera() { + return this.cam.camera; + } + + requestRender(): void { + this.dirty = true; + } + + private resize(): void { + const w = this.canvas.clientWidth; + const h = this.canvas.clientHeight; + if (!w || !h) return; + this.renderer.setSize(w, h, false); + this.cam.setAspect(w / h); + this.lineMaterials.forEach((m) => m.resolution.set(w, h)); + this.dirty = true; + } + + private render(): void { + this.dirty = false; + const cam = this.camera; + this.light.position.copy(cam.position).add(new Vector3(0, 0, this.cam.distance * 0.5)); + this.light.target.position.copy(this.cam.target); + this.grid.update(this.cam.worldPerPixel(this.height), this.cam.target, this.cam.distance, this.cam.camera.position); + this.layoutOriginPlanes(); + this.frameHooks.forEach((f) => f()); + this.renderer.render(this.scene, cam); + } + + private applySettings(): void { + const s = settings.value; + this.grid.mesh.visible = s.showGrid; + this.grid.locked = s.gridLocked; + this.grid.lockedStep = s.gridStep; + this.axesGroup.visible = s.showAxes; + this.cam.animate = s.animateCamera; + this.cam.setOrtho(s.ortho); + const xray = s.shader === "xray"; + for (const m of this.allBodyMats()) { + m.transparent = xray; + m.opacity = xray ? 0.35 : 1; + m.depthWrite = !xray; + m.side = xray ? DoubleSide : FrontSide; + m.needsUpdate = true; + } + this.applyHidden(); + } + + // ---------------------------------------------------------------- bodies + + private openMats: LineMaterial[] = []; + + /** Body colour → its surface and section-cap materials (copies of the shared ones). */ + private colorMats = new Map(); + private bodyColors: Record = {}; + + private matsFor(id: string): { body: MeshStandardMaterial; cap: MeshBasicMaterial } { + const hex = this.bodyColors[id]; + if (!hex) return { body: this.bodyMat, cap: this.capMat }; + let m = this.colorMats.get(hex); + if (!m) { + const body = this.bodyMat.clone(); + body.color.set(hex); + // The cut face is the body's colour, a little darker, so it reads as the same part. + const cap = hatched(this.capMat.clone()); + cap.color.set(hex).multiplyScalar(0.72); + m = { body, cap }; + this.colorMats.set(hex, m); + } + return m; + } + + /** Every body surface material (shared + coloured), for settings that apply to all. */ + private allBodyMats(): MeshStandardMaterial[] { + return [this.bodyMat, ...[...this.colorMats.values()].map((m) => m.body)]; + } + + setBodyColors(colors: Record): void { + this.bodyColors = { ...colors }; + for (const [id, b] of this.bodies) { + const m = this.matsFor(id); + b.mesh.material = m.body; + b.cap.material = m.cap; + } + this.applyClip(); + this.applySettings(); + } + + setBodies(meshes: BodyMesh[]): void { + for (const b of this.bodies.values()) { + b.mesh.geometry.dispose(); + b.edges.geometry.dispose(); + } + this.openMats.forEach((m) => this.releaseLineMaterial(m)); + this.openMats = []; + this.bodies.clear(); + this.bodiesGroup.clear(); + for (const data of meshes) { + const g = new BufferGeometry(); + g.setAttribute("position", new BufferAttribute(data.positions, 3)); + g.setAttribute("normal", new BufferAttribute(data.normals, 3)); + g.setIndex(new BufferAttribute(data.indices, 1)); + g.computeBoundingSphere(); + const mats = this.matsFor(data.id); + const mesh = new Mesh(g, mats.body); + mesh.userData.body = data.id; + const cap = new Mesh(g, mats.cap); + const eg = new BufferGeometry(); + eg.setAttribute("position", new BufferAttribute(data.edgePositions, 3)); + const edges = new LineSegments(eg, this.edgeMat); + const hidden = new LineSegments(eg, this.hiddenMat); + hidden.computeLineDistances(); + hidden.renderOrder = 5; + this.bodiesGroup.add(mesh, cap, edges, hidden); + const vertices: Vector3[] = []; + for (const e of data.edges) { + for (const p of [e.start, e.end]) { + const v = new Vector3(...p); + if (!vertices.some((q) => q.distanceToSquared(v) < 1e-12)) vertices.push(v); + } + } + this.bodies.set(data.id, { data, mesh, cap, edges, hidden, vertices }); + // Open (non-watertight) edges stand out in orange. + if (data.openEdges?.length) { + const seg: number[] = []; + for (const i of data.openEdges) { + const g = data.edgeGroups.find((x) => x.edge === i); + if (g) seg.push(...Array.from(data.edgePositions.slice(g.start * 3, (g.start + g.count) * 3))); + } + if (seg.length) { + const mat = this.lineMaterial(0xff9a3d, 3, true); + this.openMats.push(mat); + const l = new LineSegments2(new LineSegmentsGeometry().setPositions(seg), mat); + l.renderOrder = 3; + this.bodiesGroup.add(l); + } + } + } + this.applyClip(); + this.applySettings(); + this.applyHidden(); + } + + // ------------------------------------------------------- hidden/isolate + + private hiddenIds = new Set(); + + /** Bodies hidden from Items or by Isolate: not drawn, not pickable. */ + setHidden(ids: Iterable): void { + this.hiddenIds = new Set(ids); + this.applyHidden(); + } + + isHidden(id: string): boolean { + return this.hiddenIds.has(id); + } + + private applyHidden(): void { + for (const [id, b] of this.bodies) { + const vis = !this.hiddenIds.has(id); + b.mesh.visible = vis && settings.value.shader !== "wireframe"; + b.cap.visible = vis && !!this.clip && settings.value.shader === "shaded"; + b.edges.visible = vis && (settings.value.showEdges || settings.value.shader === "wireframe"); + b.hidden.visible = vis && (settings.value.showHiddenEdges || settings.value.shader === "wireframe"); + } + this.dirty = true; + } + + private visibleBodies(): BodyView[] { + return [...this.bodies.entries()].filter(([id]) => !this.hiddenIds.has(id)).map(([, b]) => b); + } + + vertexOf(body: string, i: number): Vec3 | undefined { + return this.bodies.get(body)?.vertices[i]?.toArray() as Vec3 | undefined; + } + + body(id: string): BodyMesh | undefined { + return this.bodies.get(id)?.data; + } + + get bodyList(): BodyMesh[] { + return [...this.bodies.values()].map((b) => b.data); + } + + bounds(): Box3 { + const box = new Box3(); + // Each part on its own, so one broken piece (NaN) can't spoil the whole fit. + const add = (o: Object3D) => { + const b = new Box3().expandByObject(o); + if (!b.isEmpty() && [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].every((v) => Number.isFinite(v) && Math.abs(v) < 1e8)) box.union(b); + }; + for (const b of this.visibleBodies()) add(b.mesh); + this.sketchGroup.children.forEach(add); + this.imageMeshes.forEach((m) => m.visible && add(m)); + return box; + } + + // --------------------------------------------------------------- section + + /** Cut the view with a plane (keeps the side the normal points away from). */ + setSection(plane: PlaneDef | null): void { + this.clip = plane ? new Plane().setFromNormalAndCoplanarPoint(new Vector3(...plane.normal).negate(), new Vector3(...plane.origin)) : null; + this.applyClip(); + this.applySettings(); + } + + private applyClip(): void { + const planes = this.clip ? [this.clip] : []; + for (const m of [this.bodyMat, this.capMat, this.edgeMat, this.hiddenMat, ...[...this.colorMats.values()].flatMap((c) => [c.body, c.cap])]) { + m.clippingPlanes = planes; + m.needsUpdate = true; + } + this.dirty = true; + } + + // -------------------------------------------------------------- sketches + + private sketchMats: LineMaterial[] = []; + private sketchPoints: { sketch: string; entity: string; p: string; pos: Vector3 }[] = []; + + setSketches(sketches: SketchView[], activeId?: string): void { + this.sketches = sketches; + this.sketchGroup.traverse((o) => { + if (o instanceof Mesh || o instanceof Line || o instanceof LineSegments2 || o instanceof Points) o.geometry.dispose(); + }); + this.sketchGroup.clear(); + this.sketchMats.forEach((m) => this.releaseLineMaterial(m)); + this.sketchMats = []; + this.profileMeshes = []; + this.curveLines = []; + this.sketchPoints = []; + const wpp = this.cam.worldPerPixel(this.height); + for (const s of sketches) { + const active = s.id === activeId; + const m = planeMatrix(s.plane, this.cam.distance * 1e-5); + // Clean 2px lines; the sketch being edited is brighter and on top. + const solid: number[] = []; + const dashed: number[] = []; + for (const e of s.entities) { + for (const poly of entityPolylines(e)) { + const pts = poly.map((p) => new Vector3(p[0], p[1], 0).applyMatrix4(m)); + const into = e.construction ? dashed : solid; + for (let i = 0; i < pts.length - 1; i++) into.push(...pts[i].toArray(), ...pts[i + 1].toArray()); + this.curveLines.push({ sketch: s.id, entity: e.id, pts }); + } + if (active) for (const q of pointsOf(e)) this.sketchPoints.push({ sketch: s.id, entity: e.id, p: q.p, pos: new Vector3(q.at[0], q.at[1], 0).applyMatrix4(m) }); + } + if (solid.length) { + const mat = this.lineMaterial(active ? 0xffffff : COLORS.sketch, active ? 2.2 : 1.6, !active); + this.sketchMats.push(mat); + const l = new LineSegments2(new LineSegmentsGeometry().setPositions(solid), mat); + l.renderOrder = 2; + this.sketchGroup.add(l); + } + if (dashed.length) { + const mat = this.lineMaterial(COLORS.construction, 1.4, !active); + mat.dashed = true; + mat.dashSize = wpp * 6; + mat.gapSize = wpp * 4; + this.sketchMats.push(mat); + const l = new LineSegments2(new LineSegmentsGeometry().setPositions(dashed), mat); + l.computeLineDistances(); + l.renderOrder = 2; + this.sketchGroup.add(l); + } + if (active && this.sketchPoints.length) { + const dots = new Points(new BufferGeometry().setFromPoints(this.sketchPoints.map((q) => q.pos)), dotMaterial({ color: 0xffffff, size: 8 })); + dots.renderOrder = 4; + this.sketchGroup.add(dots); + } + const fillMat = new MeshBasicMaterial({ + color: COLORS.profile, + transparent: true, + opacity: active ? 0.16 : 0.1, + side: DoubleSide, + depthWrite: false, + polygonOffset: true, + polygonOffsetFactor: -2, + polygonOffsetUnits: -2, + }); + // Regions include the face outline, so a line across a face splits it in two. + for (const r of arrangement([...s.entities, ...(s.boundary ?? [])]).regions) { + const shape = new Shape(r.outer.poly.map((p) => new Vector2(p[0], p[1]))); + for (const h of r.holes) shape.holes.push(new Path(h.poly.map((p) => new Vector2(p[0], p[1])))); + const fill = new Mesh(new ShapeGeometry(shape), fillMat); + fill.applyMatrix4(m); + fill.userData = { sketch: s.id, region: r.index, area: r.area }; + fill.renderOrder = 1; + this.sketchGroup.add(fill); + this.profileMeshes.push(fill); + } + } + this.dirty = true; + } + + // ------------------------------------------------ construction + images + + setConstruction(planes: ConstructionInfo[], axes: ConstructionInfo[]): void { + this.construction = { planes, axes }; + this.rebuildPlanes(); + } + + /** Show the XY/XZ/YZ origin planes as pickable squares (sketch/section pick). */ + setOriginPlanesVisible(on: boolean): void { + this.showOriginPlanes = on; + this.rebuildPlanes(); + } + + private rebuildPlanes(): void { + this.constructionGroup.traverse((o) => { + if (o instanceof Mesh || o instanceof Line) o.geometry.dispose(); + }); + this.constructionGroup.clear(); + this.planeMeshes = []; + this.axisLines = []; + // Origin planes (shown only while picking a plane) draw through bodies so they can always be picked. + const mat = (color: number, o: number, onTop: boolean) => new MeshBasicMaterial({ color, transparent: true, opacity: o, side: DoubleSide, depthWrite: false, depthTest: !onTop }); + // Origin planes take the colour of the axis they face: XY blue (Z), XZ green (Y), YZ red (X). + const AXIS_TINT: Record = { XY: 0x4f8ce0, XZ: 0x5fbf5a, YZ: 0xe0584f }; + const addPlane = (id: string, p: PlaneDef, size: number, origin: boolean) => { + const color = origin ? (AXIS_TINT[id] ?? COLORS.plane) : COLORS.plane; + const mesh = new Mesh(new PlaneGeometry(1, 1), mat(color, origin ? 0.35 : 0.16, origin)); + mesh.userData = { plane: id, origin, size }; + mesh.matrixAutoUpdate = false; + mesh.matrix.copy(planeMatrix(p).multiply(new Matrix4().makeScale(size, size, 1))); + mesh.renderOrder = origin ? 8 : 3; + const border = new LineSegments( + new BufferGeometry().setFromPoints([[-0.5, -0.5], [0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [0.5, 0.5], [-0.5, 0.5], [-0.5, 0.5], [-0.5, -0.5]].map(([x, y]) => new Vector3(x, y, 0))), + new LineBasicMaterial({ color, transparent: true, opacity: 0.8, depthTest: !origin }), + ); + border.renderOrder = mesh.renderOrder; + mesh.add(border); + this.constructionGroup.add(mesh); + this.planeMeshes.push(mesh); + }; + if (this.showOriginPlanes) for (const [id, p] of Object.entries(ORIGIN_PLANES)) addPlane(id, p, 1, true); + for (const c of this.construction.planes) addPlane(c.id, c.plane, 1, false); + for (const a of this.construction.axes) { + const o = new Vector3(...a.plane.origin); + const d = new Vector3(...a.plane.normal); + const L = 1e4; + const geo = new BufferGeometry().setFromPoints([o.clone().addScaledVector(d, -L), o.clone().addScaledVector(d, L)]); + const line = new Line(geo, new LineDashedMaterial({ color: 0xffb454, dashSize: 4, gapSize: 3 })); + line.computeLineDistances(); + this.constructionGroup.add(line); + this.axisLines.push({ id: a.id, a: o.clone().addScaledVector(d, -L), b: o.clone().addScaledVector(d, L) }); + } + this.dirty = true; + } + + private planeSizes = new Map(); + + /** History hover: what a step works on, as dashed lines seen through everything. */ + private stepGroup = new Group(); + + setStepHover(t: { bodies: string[]; lines: Vec3[][] } | null): void { + this.stepGroup.traverse((o) => { + if (o instanceof LineSegments || o instanceof Line) { + o.geometry.dispose(); + (o.material as LineDashedMaterial).dispose(); + } + }); + this.stepGroup.clear(); + if (t) { + if (!this.stepGroup.parent) this.scene.add(this.stepGroup); + const wpp = this.cam.worldPerPixel(this.height); + const mat = () => new LineDashedMaterial({ color: 0xffa31a, dashSize: wpp * 7, gapSize: wpp * 5, depthTest: false, transparent: true }); + for (const id of t.bodies) { + const b = this.bodies.get(id); + if (!b) continue; + const geo = new BufferGeometry(); + geo.setAttribute("position", new BufferAttribute(b.data.edgePositions, 3)); + const ls = new LineSegments(geo, mat()); + ls.computeLineDistances(); + ls.renderOrder = 40; + this.stepGroup.add(ls); + } + for (const pl of t.lines) { + if (pl.length < 2) continue; + const ln = new Line(new BufferGeometry().setFromPoints(pl.map((p) => new Vector3(...p))), mat()); + ln.computeLineDistances(); + ln.renderOrder = 40; + this.stepGroup.add(ln); + } + } + this.requestRender(); + } + + /** + * On-screen helpers that are alive (handles, gimbals, value boxes, copy + * toggles). Back in plain selection, any the selection doesn't own are + * leftovers and get cleared (no ghost arrows or dots). + */ + readonly helpers = new Set<{ dispose(): void }>(); + + clearHelpers(keep: Iterable): void { + const k = new Set(keep); + for (const h of [...this.helpers]) if (!k.has(h)) h.dispose(); + } + + /** Origin planes stay ~90 px on screen; construction planes keep their first size. */ + private layoutOriginPlanes(): void { + const wpp = this.cam.worldPerPixel(this.height); + for (const m of this.planeMeshes) { + const id = m.userData.plane as string; + const p = ORIGIN_PLANES[id] ?? this.construction.planes.find((c) => c.id === id)?.plane; + if (!p) continue; + // A construction plane keeps the size it was first shown at: it doesn't + // grow and shrink while the model is edited. + let size = m.userData.origin ? wpp * 90 : this.planeSizes.get(id); + if (size === undefined) { + size = Math.max(wpp * 160, this.bounds().getSize(new Vector3()).length() * 0.6); + this.planeSizes.set(id, size); + } + // Origin planes sit in their quadrant (like a corner), the rest are centred. + const off = m.userData.origin ? size / 2 : 0; + const mm = planeMatrix({ ...p, origin: p.origin }).multiply(new Matrix4().makeTranslation(off, off, 0)).multiply(new Matrix4().makeScale(size, size, 1)); + m.matrix.copy(mm); + m.matrixWorldNeedsUpdate = true; + } + } + + planeOf(id: string): PlaneDef | undefined { + return ORIGIN_PLANES[id] ?? this.construction.planes.find((c) => c.id === id)?.plane; + } + + axisOf(id: string): ConstructionInfo | undefined { + const w = WORLD_AXIS_DIRS[id]; + if (w) return { id, name: `${id} axis`, plane: { origin: [0, 0, 0], normal: w, xDir: w[2] ? [1, 0, 0] : [0, 0, 1] } }; + return this.construction.axes.find((a) => a.id === id); + } + + /** A world axis as a segment long enough to cover the view. */ + private worldAxisLine(id: string): { id: string; a: Vector3; b: Vector3 } | null { + const w = WORLD_AXIS_DIRS[id]; + if (!w || !settings.value.showAxes) return null; + const L = Math.max(this.cam.distance * 4, 100); + const d = new Vector3(...w); + return { id, a: d.clone().multiplyScalar(-L), b: d.clone().multiplyScalar(L) }; + } + + setImages(images: ImageFeature[]): void { + this.imageGroup.traverse((o) => { + if (o instanceof Mesh) o.geometry.dispose(); + }); + this.imageGroup.clear(); + const loader = new TextureLoader(); + this.imageMeshes = []; + for (const img of images) { + // Textures are cached by source so live moves/scales don't reload them. + let tex = this.textures.get(img.src); + if (!tex) { + tex = loader.load(img.src, () => this.requestRender()); + tex.colorSpace = SRGBColorSpace; + this.textures.set(img.src, tex); + } + const mesh = new Mesh(new PlaneGeometry(img.width, img.height), new MeshBasicMaterial({ map: tex, transparent: true, opacity: img.opacity, side: DoubleSide, depthWrite: false })); + mesh.applyMatrix4(planeMatrix(img.plane, -this.cam.distance * 1e-5)); + mesh.renderOrder = 0; + mesh.userData.image = img.id; + this.imageGroup.add(mesh); + this.imageMeshes.push(mesh); + } + this.dirty = true; + } + + private imageMeshes: Mesh[] = []; + private textures = new Map(); + + // ------------------------------------------------------------ highlights + + private lastSelKey = ""; + private pulse: { t0: number; mats: { m: MeshBasicMaterial | LineMaterial | PointsMaterial; base: number }[] } | null = null; + + setHighlights(selected: Highlight[], hover: Highlight | null): void { + this.highlightGroup.traverse((o) => { + if (o instanceof Mesh || o instanceof LineSegments2) o.geometry.dispose(); + }); + this.highlightGroup.clear(); + const selKey = JSON.stringify(selected); + const fresh = selKey !== this.lastSelKey && selected.length > 0; + this.lastSelKey = selKey; + this.lineMaterials = this.lineMaterials.filter((m) => m.userData.keep); + let width = 4; + const fatLines = (pts: number[], color: number) => { + const geo = new LineSegmentsGeometry().setPositions(pts); + const mat = new LineMaterial({ color, linewidth: width, depthTest: false }); + mat.resolution.set(this.width, this.height); + this.lineMaterials.push(mat); + const line = new LineSegments2(geo, mat); + line.renderOrder = 4; + this.highlightGroup.add(line); + }; + const add = (h: Highlight, color: number, opacity: number) => { + if (h.kind === "profile") { + const src = this.profileMeshes.find((m) => m.userData.sketch === h.sketch && m.userData.region === h.region); + if (!src) return; + const m = new Mesh(src.geometry.clone(), overlayMat(color, opacity + 0.15)); + m.applyMatrix4(src.matrix); + m.renderOrder = 3; + this.highlightGroup.add(m); + return; + } + if (h.kind === "curve") { + const pts: number[] = []; + for (const c of this.curveLines.filter((c) => c.sketch === h.sketch && c.entity === h.entity)) { + for (let i = 0; i < c.pts.length - 1; i++) pts.push(...c.pts[i].toArray(), ...c.pts[i + 1].toArray()); + } + if (pts.length) fatLines(pts, color); + return; + } + if (h.kind === "point") { + const q = this.sketchPoints.find((s) => s.sketch === h.sketch && s.entity === h.entity && s.p === h.p); + if (!q) return; + const dot = new Points(new BufferGeometry().setFromPoints([q.pos]), dotMaterial({ color, size: 13 })); + dot.renderOrder = 6; + this.highlightGroup.add(dot); + return; + } + if (h.kind === "image") { + const src = this.imageMeshes.find((m) => m.userData.image === h.id); + if (!src) return; + const box = new LineSegments(new EdgesGeometry(src.geometry), new LineBasicMaterial({ color, depthTest: false })); + box.applyMatrix4(src.matrix); + box.renderOrder = 6; + this.highlightGroup.add(box); + const m = new Mesh(src.geometry.clone(), overlayMat(color, opacity * 0.5)); + m.applyMatrix4(src.matrix); + this.highlightGroup.add(m); + return; + } + if (h.kind === "plane") { + const src = this.planeMeshes.find((m) => m.userData.plane === h.id); + if (!src) return; + // Just a tint (the plane stays see-through), so it doesn't cover the model. + const mat = overlayMat(color, Math.min(0.22, opacity * 0.5)); + // Planes are picked through bodies, so their highlight must show through too. + mat.depthTest = false; + const m = new Mesh(src.geometry.clone(), mat); + m.matrixAutoUpdate = false; + m.matrix.copy(src.matrix); + m.renderOrder = 9; + this.highlightGroup.add(m); + return; + } + if (h.kind === "axis") { + const a = this.axisLines.find((x) => x.id === h.id) ?? this.worldAxisLine(h.id); + if (a) fatLines([...a.a.toArray(), ...a.b.toArray()], color); + return; + } + const b = this.bodies.get(h.body); + if (!b) return; + if (h.kind === "vertex") { + const v = b.vertices[h.vertex]; + if (!v) return; + const dot = new Points(new BufferGeometry().setFromPoints([v]), dotMaterial({ color, size: 12 })); + dot.renderOrder = 6; + this.highlightGroup.add(dot); + return; + } + if (h.kind === "body" || h.kind === "face") { + const groups = h.kind === "body" ? b.data.faceGroups : b.data.faceGroups.filter((g) => g.face === h.face); + const idx: number[] = []; + for (const g of groups) for (let i = g.start; i < g.start + g.count; i++) idx.push(b.data.indices[i]); + const geo = new BufferGeometry(); + geo.setAttribute("position", b.mesh.geometry.getAttribute("position")); + geo.setIndex(idx); + const m = new Mesh(geo, overlayMat(color, opacity)); + m.renderOrder = 3; + this.highlightGroup.add(m); + // Outline the face/body with its edges so it reads clearly. + const outline: number[] = []; + b.data.edges.forEach((e, i) => { + if (h.kind === "face" && !edgeOnFace(e, b.data.faces[h.face])) return; + const g = b.data.edgeGroups.find((x) => x.edge === i); + if (g) outline.push(...Array.from(b.data.edgePositions.slice(g.start * 3, (g.start + g.count) * 3))); + }); + const w = width; + width = 2; + if (outline.length) fatLines(outline, color); + width = w; + } else { + const g = b.data.edgeGroups.find((e) => e.edge === h.edge); + if (g) fatLines(Array.from(b.data.edgePositions.slice(g.start * 3, (g.start + g.count) * 3)), color); + } + }; + width = 5; + if (hover) add(hover, COLORS.hover, 0.3); + width = 4; + const firstSel = this.highlightGroup.children.length; + for (const s of selected) add(s, COLORS.select, 0.42); + // A newly selected thing flashes briefly, so it's obvious what was picked. + if (fresh) { + const mats: { m: MeshBasicMaterial | LineMaterial | PointsMaterial; base: number }[] = []; + this.highlightGroup.children.slice(firstSel).forEach((o) => { + const m = (o as Mesh).material as MeshBasicMaterial | LineMaterial | PointsMaterial; + if (!m) return; + m.transparent = true; + mats.push({ m, base: m.opacity }); + }); + this.pulse = { t0: performance.now(), mats }; + } + this.dirty = true; + } + + /** Advance the selection flash; returns true while it runs. */ + private tickPulse(now: number): boolean { + const p = this.pulse; + if (!p) return false; + const k = Math.min(1, (now - p.t0) / 420); + const boost = Math.sin(k * Math.PI) * 0.5; + for (const { m, base } of p.mats) m.opacity = Math.min(1, base + boost); + if (k >= 1) this.pulse = null; + return true; + } + + // --------------------------------------------------------------- picking + + private setRay(x: number, y: number): void { + const ndc = new Vector2((x / this.width) * 2 - 1, -(y / this.height) * 2 + 1); + this.raycaster.setFromCamera(ndc, this.camera); + } + + /** Pick what's under the pointer. Edges and curves win within the tolerance. */ + pick(x: number, y: number, opts: PickOptions = {}): PickHit | null { + const { edgeTolPx = 8, profiles = true, bodies = true, edges = true, curves = false, planes = true, axes = true, vertices = edges, planesFirst = false } = opts; + this.setRay(x, y); + if (planes && planesFirst) { + const hit = this.raycaster.intersectObjects(this.planeMeshes.filter((m) => m.userData.origin), false)[0]; + if (hit) return { kind: "plane", id: hit.object.userData.plane, point: hit.point.toArray() as Vec3 }; + } + const visibleBodies = bodies && settings.value.shader !== "wireframe"; + const meshes = visibleBodies ? this.visibleBodies().map((b) => b.mesh) : []; + const faceHit = this.raycaster.intersectObjects(meshes, false).find((h) => !this.clip || this.clip.distanceToPoint(h.point) >= 0); + const faceDist = faceHit ? faceHit.distance : Infinity; + const near = this.cam.distance * 1e-3; + + if (bodies && vertices) { + const v = this.pickVertex(x, y, edgeTolPx, faceDist); + if (v) return v; + } + if (curves) { + const only = typeof curves === "string" ? curves : undefined; + // Points first: endpoints sit on curves, and are what you usually mean. + let bestPt: { d: number; q: { sketch: string; entity: string; p: string; pos: Vector3 } } | null = null; + for (const q of this.sketchPoints) { + if (only && q.sketch !== only) continue; + const s = this.toScreen(q.pos); + if (!s) continue; + const d = Math.hypot(s[0] - x, s[1] - y); + if (d < edgeTolPx && (!bestPt || d < bestPt.d)) bestPt = { d, q }; + } + if (bestPt) return { kind: "point", sketch: bestPt.q.sketch, entity: bestPt.q.entity, p: bestPt.q.p, point: bestPt.q.pos.toArray() as Vec3 }; + const c = this.pickCurve(x, y, edgeTolPx, only); + if (c) return c; + } + if (profiles) { + const ph = this.raycaster.intersectObjects(this.profileMeshes, false).filter((h) => h.distance <= faceDist + near); + if (ph.length) { + // Smallest region under the pointer at the nearest depth. + const d0 = ph[0].distance; + const best = ph.filter((h) => Math.abs(h.distance - d0) < near).sort((a, b) => a.object.userData.area - b.object.userData.area)[0]; + return { kind: "profile", sketch: best.object.userData.sketch, region: best.object.userData.region, point: best.point.toArray() as Vec3 }; + } + } + if (bodies && edges) { + // Over a face, an edge has to be nearer to win (else small faces are + // hard to hit between their edges when zoomed out). + const edge = this.pickEdge(x, y, faceHit ? Math.max(5, edgeTolPx * 0.6) : edgeTolPx, faceDist); + if (edge) return edge; + } + if (faceHit && faceHit.faceIndex != null) { + const body = faceHit.object.userData.body as string; + const data = this.bodies.get(body)!.data; + const tri = faceHit.faceIndex * 3; + const g = data.faceGroups.find((g) => tri >= g.start && tri < g.start + g.count); + if (g) return { kind: "face", body, face: g.face, point: faceHit.point.toArray() as Vec3 }; + } + if (opts.images !== false) { + const hit = this.raycaster.intersectObjects(this.imageMeshes, false)[0]; + if (hit && hit.distance <= faceDist) return { kind: "image", id: hit.object.userData.image, point: hit.point.toArray() as Vec3 }; + } + if (axes) { + // World axes in short pieces: a far end behind the camera has no screen position. + const world: { id: string; a: Vector3; b: Vector3 }[] = []; + for (const id of opts.worldAxes ? ["X", "Y", "Z"] : []) { + const w = this.worldAxisLine(id); + if (!w) continue; + const n = 64; + for (let k = 0; k < n; k++) world.push({ id, a: w.a.clone().lerp(w.b, k / n), b: w.a.clone().lerp(w.b, (k + 1) / n) }); + } + for (const a of [...this.axisLines, ...world]) { + const sa = this.toScreen(a.a); + const sb = this.toScreen(a.b); + if (sa && sb && distToSeg(x, y, sa, sb) < edgeTolPx) return { kind: "axis", id: a.id, point: a.a.toArray() as Vec3 }; + } + } + if (planes) { + const hit = this.raycaster.intersectObjects(this.planeMeshes, false)[0]; + if (hit && hit.distance <= faceDist) return { kind: "plane", id: hit.object.userData.plane, point: hit.point.toArray() as Vec3 }; + } + return null; + } + + private pickCurve(x: number, y: number, tol: number, onlySketch?: string): PickHit | null { + let best: { d: number; c: { sketch: string; entity: string; pts: Vector3[] }; p: Vector3 } | null = null; + for (const c of this.curveLines) { + if (onlySketch && c.sketch !== onlySketch) continue; + for (let i = 0; i < c.pts.length - 1; i++) { + const sa = this.toScreen(c.pts[i]); + const sb = this.toScreen(c.pts[i + 1]); + if (!sa || !sb) continue; + const d = distToSeg(x, y, sa, sb); + if (d < tol && (!best || d < best.d)) best = { d, c, p: c.pts[i] }; + } + } + return best ? { kind: "curve", sketch: best.c.sketch, entity: best.c.entity, point: best.p.toArray() as Vec3 } : null; + } + + /** Distance of a point along the view direction (works for ortho and perspective). */ + private depthOf(w: Vector3): number { + return this.cam.ortho ? w.clone().sub(this.camera.position).dot(this.cam.viewDir()) : w.distanceTo(this.camera.position); + } + + private pickVertex(x: number, y: number, tolPx: number, faceDist: number): PickHit | null { + let best: { d: number; body: string; vertex: number; p: Vector3 } | null = null; + for (const [id, b] of this.bodies) { + if (this.hiddenIds.has(id)) continue; + b.vertices.forEach((v, i) => { + if (this.clip && this.clip.distanceToPoint(v) < 0) return; + const s = this.toScreen(v); + if (!s) return; + const d = Math.hypot(s[0] - x, s[1] - y); + if (d > tolPx || (best && d >= best.d)) return; + if (this.depthOf(v) > faceDist + this.cam.distance * 0.01) return; + best = { d, body: id, vertex: i, p: v }; + }); + } + const hit = best as { d: number; body: string; vertex: number; p: Vector3 } | null; + return hit ? { kind: "vertex", body: hit.body, vertex: hit.vertex, point: hit.p.toArray() as Vec3 } : null; + } + + private pickEdge(x: number, y: number, tolPx: number, faceDist: number): PickHit | null { + let best: { d: number; body: string; edge: number; point: Vector3 } | null = null; + const a = new Vector3(); + const b = new Vector3(); + const camPos = this.camera.position; + const viewDir = this.cam.viewDir(); + for (const [id, { data }] of this.bodies) { + if (this.hiddenIds.has(id)) continue; + const p = data.edgePositions; + for (const g of data.edgeGroups) { + for (let i = g.start; i < g.start + g.count; i += 2) { + a.set(p[i * 3], p[i * 3 + 1], p[i * 3 + 2]); + b.set(p[i * 3 + 3], p[i * 3 + 4], p[i * 3 + 5]); + if (this.clip && this.clip.distanceToPoint(a) < 0 && this.clip.distanceToPoint(b) < 0) continue; + const sa = this.toScreen(a); + const sb = this.toScreen(b); + if (!sa || !sb) continue; + const t = segParam(x, y, sa, sb); + const d = Math.hypot(sa[0] + (sb[0] - sa[0]) * t - x, sa[1] + (sb[1] - sa[1]) * t - y); + if (d > tolPx || (best && d >= best.d)) continue; + const w = a.clone().lerp(b, t); + // Hidden edges (behind the face under the pointer) are not pickable. + const depth = this.cam.ortho ? w.clone().sub(camPos).dot(viewDir) : w.distanceTo(camPos); + if (depth > faceDist + this.cam.distance * 0.01) continue; + best = { d, body: id, edge: g.edge, point: w }; + } + } + } + return best ? { kind: "edge", body: best.body, edge: best.edge, point: best.point.toArray() as Vec3 } : null; + } + + /** Intersection of the pointer ray with a plane, or null if parallel. */ + rayToPlane(x: number, y: number, plane: PlaneDef): Vec3 | null { + this.setRay(x, y); + const n = new Vector3(...plane.normal); + const o = new Vector3(...plane.origin); + const r = this.raycaster.ray; + const denom = n.dot(r.direction); + if (Math.abs(denom) < 1e-9) return null; + const t = o.sub(r.origin).dot(n) / denom; + if (t < 0 && !this.cam.ortho) return null; + return r.origin.clone().addScaledVector(r.direction, t).toArray() as Vec3; + } + + /** World point → CSS pixel coords, or null when behind the camera. */ + toScreen(v: Vector3 | Vec3): [number, number] | null { + const p = Array.isArray(v) ? new Vector3(...v) : v.clone(); + p.project(this.camera); + if (p.z > 1 || p.z < -1) return null; + return [((p.x + 1) / 2) * this.width, ((1 - p.y) / 2) * this.height]; + } + + /** Point under the pointer for zooming: model surface, else ground, else target depth. */ + worldUnder(x: number, y: number): Vector3 { + this.setRay(x, y); + const hit = this.raycaster.intersectObjects([...this.bodies.values()].map((b) => b.mesh), false)[0]; + if (hit) return hit.point; + const g = this.rayToPlane(x, y, GROUND); + if (g && new Vector3(...g).distanceTo(this.camera.position) < this.cam.distance * 20) return new Vector3(...g); + const r = this.raycaster.ray; + return r.origin.clone().addScaledVector(r.direction, this.cam.target.clone().sub(r.origin).dot(r.direction)); + } + + /** Line material that tracks viewport resolution (for overlays). */ + lineMaterial(color: number, width: number, depthTest = false): LineMaterial { + const m = new LineMaterial({ color, linewidth: width, depthTest }); + m.resolution.set(this.width, this.height); + m.userData.keep = true; + this.lineMaterials.push(m); + return m; + } + + releaseLineMaterial(m: LineMaterial): void { + this.lineMaterials = this.lineMaterials.filter((x) => x !== m); + m.dispose(); + } + + /** PNG of the current view. */ + screenshot(): Promise { + this.render(); + return new Promise((resolve) => this.canvas.toBlob(resolve, "image/png")); + } + + get sketchList(): SketchView[] { + return this.sketches; + } +} + +/** Matrix taking sketch-local (u, v, w) into world space. */ +export function planeMatrix(p: PlaneDef, lift = 0): Matrix4 { + const x = new Vector3(...p.xDir); + const y = new Vector3(...planeY(p)); + const z = new Vector3(...p.normal); + const o = new Vector3(...p.origin).addScaledVector(z, lift); + return new Matrix4().makeBasis(x, y, z).setPosition(o); +} + +export function sketchToWorld(p: PlaneDef, uv: Vec2, lift = 0): Vector3 { + return new Vector3(uv[0], uv[1], 0).applyMatrix4(planeMatrix(p, lift)); +} + +/** Does an edge lie on a face? (flat faces: all three sample points on its plane). */ +export function edgeOnFace(e: EdgeInfo, f: FaceInfo): boolean { + if (!f.plane) { + // Curved faces: an edge belongs if its midpoint is close to the face centre region. + return false; + } + return [e.start, e.end, e.mid].every((p) => Math.abs((p[0] - f.center[0]) * f.normal[0] + (p[1] - f.center[1]) * f.normal[1] + (p[2] - f.center[2]) * f.normal[2]) < 1e-5 * (1 + Math.sqrt(f.area))); +} + +function overlayMat(color: number, opacity: number): MeshBasicMaterial { + return new MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false, side: DoubleSide, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 }); +} + +function segParam(x: number, y: number, a: [number, number], b: [number, number]): number { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const l2 = dx * dx + dy * dy; + if (l2 < 1e-9) return 0; + return Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l2)); +} + +function distToSeg(x: number, y: number, a: [number, number], b: [number, number]): number { + const t = segParam(x, y, a, b); + return Math.hypot(a[0] + (b[0] - a[0]) * t - x, a[1] + (b[1] - a[1]) * t - y); +} + +function makeAxes(): Object3D { + const g = new Group(); + const L = 1e6; + const axis = (to: Vec3, color: number) => { + const geo = new BufferGeometry(); + geo.setAttribute("position", new Float32BufferAttribute([0, 0, 0, ...to], 3)); + // Transparent + later render order so the axes draw over the coplanar grid. + const line = new LineSegments(geo, new LineBasicMaterial({ color, transparent: true })); + line.renderOrder = 1; + return line; + }; + g.add(axis([L, 0, 0], 0xe0584f), axis([0, L, 0], 0x5fbf5a), axis([0, 0, L], 0x4f8ce0)); + return g; +} + +/** + * Section caps get thin diagonal lines (fixed on screen), so a cut reads as a + * cut and not as another face of the body. + */ +function hatched(m: M): M { + m.onBeforeCompile = (shader) => { + shader.fragmentShader = shader.fragmentShader.replace( + "#include ", + `#include + float hatchK = mod(gl_FragCoord.x + gl_FragCoord.y, 9.0); + if (hatchK < 1.6) gl_FragColor.rgb *= 0.62;`, + ); + }; + m.customProgramCacheKey = () => "hatched"; + return m; +} diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..05c71b3 --- /dev/null +++ b/start.bat @@ -0,0 +1,32 @@ +@echo off +rem Starts the supergeometry.app dev server and opens it in Chrome. +title supergeometry.app dev server +cd /d "%~dp0" + +rem Node may not be on PATH in older terminals right after installing it. +where npm >nul 2>nul || set "PATH=%PATH%;C:\Program Files\nodejs" +where npm >nul 2>nul || (echo Node.js not found. Install it from https://nodejs.org & pause & exit /b 1) + +rem Already running? Just open the browser. +powershell -NoProfile -Command "try { Invoke-WebRequest http://localhost:5173 -UseBasicParsing -TimeoutSec 2 | Out-Null; exit 0 } catch { exit 1 }" +if %errorlevel%==0 ( + call :open + exit /b 0 +) + +if not exist node_modules ( + echo Installing dependencies, first run only... + call npm install || (pause & exit /b 1) +) + +rem Open Chrome in the background as soon as the server answers. +start "" /b powershell -NoProfile -WindowStyle Hidden -Command "for ($i=0; $i -lt 60; $i++) { try { Invoke-WebRequest http://localhost:5173 -UseBasicParsing -TimeoutSec 2 | Out-Null; break } catch { Start-Sleep 1 } }; try { Start-Process chrome 'http://localhost:5173' } catch { Start-Process 'http://localhost:5173' }" + +echo Starting supergeometry.app at http://localhost:5173 (close this window or press Ctrl+C to stop) +call npm run dev -- --port 5173 --strictPort +pause +exit /b + +:open +powershell -NoProfile -Command "try { Start-Process chrome 'http://localhost:5173' } catch { Start-Process 'http://localhost:5173' }" +exit /b diff --git a/tests/align.test.ts b/tests/align.test.ts new file mode 100644 index 0000000..7f54e75 --- /dev/null +++ b/tests/align.test.ts @@ -0,0 +1,63 @@ +// Run: npx tsx tests/align.test.ts +import assert from "node:assert/strict"; +import type { SketchEntity } from "../src/doc/types"; +import { alignLine, joinCollinear } from "../src/sketch/edit"; + +type LineE = Extract; +const L = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b }); +const close = (p: number[], q: number[]) => assert.ok(Math.hypot(p[0] - q[0], p[1] - q[1]) < 1e-9, `${p} vs ${q}`); + +// A rectangle's right side aligns onto a vertical line further right; top and bottom stretch. +const rect = [L("b", [0, 0], [10, 0]), L("r", [10, 0], [10, 5]), L("t", [10, 5], [0, 5]), L("l", [0, 5], [0, 0])]; +const target = L("x", [14, -3], [14, 9]); +const out = alignLine([...rect, target], "r", target)!; +const get = (id: string) => out.find((e) => e.id === id) as LineE; +close(get("r").a, [14, 0]); +close(get("r").b, [14, 5]); +close(get("b").b, [14, 0]); +close(get("t").a, [14, 5]); +close(get("l").a, [0, 5]); +console.log("ok align stretches neighbours"); + +// A free tilted line lands on the target's axis. +const free = alignLine([L("f", [0, 1], [5, 3]), L("y", [0, 0], [10, 0])], "f", L("y", [0, 0], [10, 0]))!; +const f = free[0] as LineE; +close(f.a, [0, 0]); +close(f.b, [5, 0]); +console.log("ok align free line"); + +const j = joinCollinear([L("1", [0, 0], [4, 0]), L("2", [4, 0], [9, 0]), L("3", [4, 0], [4, 5])], "1")!; +assert.equal(j.removed, "2"); +const one = j.entities.find((e) => e.id === "1") as LineE; +close(one.a, [0, 0]); +close(one.b, [9, 0]); +assert.equal(j.entities.length, 2); +assert.equal(joinCollinear([L("1", [0, 0], [4, 0]), L("3", [4, 0], [4, 5])], "1"), null); +console.log("ok join collinear"); + +// Splines: Extend/Join with lines, chain offsets through them. +{ + const { joinEnds, offsetChain, splineEnds } = await import("../src/sketch/edit"); + const sp: SketchEntity = { id: "s", kind: "spline", points: [[0, 0], [10, 5], [20, 0], [30, 8]], closed: false, mode: "fit" }; + const wall = L("w", [35, -10], [35, 20]); + const j = joinEnds([sp, wall], { id: "s", at: [29, 7] }, { id: "w", at: [35, 15] })!; + const s2 = j.find((e) => e.id === "s")!; + const w2 = j.find((e) => e.id === "w") as LineE; + close(splineEnds(s2)![1], w2.b); + assert.ok(Math.abs(w2.b[0] - 35) < 1e-9); + const down = L("m", [10, -10], [10, -5]); + const j2 = joinEnds([sp, down], { id: "m", at: [10, -5] }, { id: "s", at: [12, 4] })!; + close((j2.find((e) => e.id === "m") as LineE).b, [10, 5]); + const loop = [sp, L("a", [30, 8], [30, -20]), L("b", [30, -20], [0, -20]), L("c", [0, -20], [0, 0])]; + const off = offsetChain(loop, "a", 2)!; + assert.equal(off.length, 8); + // The offset outline stays closed: each piece starts where the one before ends. + const made = off.slice(4); + const ends = made.map((e) => (e.kind === "spline" ? splineEnds(e)! : [(e as LineE).a, (e as LineE).b])); + for (let i = 0; i < ends.length; i++) { + const a = ends[i][1]; + const nexts = ends.map((x) => x[0]).concat(ends.map((x) => x[1])); + assert.ok(nexts.some((q, k) => k % ends.length !== i && Math.hypot(q[0] - a[0], q[1] - a[1]) < 1e-6), `gap after piece ${i}`); + } + console.log("ok spline join / extend / chain offset"); +} diff --git a/tests/constraints.test.ts b/tests/constraints.test.ts new file mode 100644 index 0000000..f1b13ee --- /dev/null +++ b/tests/constraints.test.ts @@ -0,0 +1,99 @@ +// Run: npx tsx tests/constraints.test.ts +import assert from "node:assert/strict"; +import type { SketchConstraint, SketchEntity } from "../src/doc/types"; +import { solve, sizeOf } from "../src/sketch/constraints"; +import { angleLines, filletConstraints, filletCorner } from "../src/sketch/edit"; +import { arcFrom3 } from "../src/sketch/curves"; + +const L = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b }); +// A slightly crooked quad that constraints should square up. +const quad = [L("l1", [0, 0], [10.3, 0.4]), L("l2", [10.3, 0.4], [10, 5.2]), L("l3", [10, 5.2], [-0.2, 5]), L("l4", [-0.2, 5], [0, 0])]; +const coin = (a: string, pa: string, b: string, pb: string): SketchConstraint => ({ id: a + b, type: "coincident", pts: [{ e: a, p: pa }, { e: b, p: pb }] }); +const rect: SketchConstraint[] = [ + coin("l1", "b", "l2", "a"), + coin("l2", "b", "l3", "a"), + coin("l3", "b", "l4", "a"), + coin("l4", "b", "l1", "a"), + { id: "h1", type: "horizontal", curves: ["l1"] }, + { id: "h2", type: "horizontal", curves: ["l3"] }, + { id: "v1", type: "vertical", curves: ["l2"] }, + { id: "v2", type: "vertical", curves: ["l4"] }, + { id: "fx", type: "fix", pts: [{ e: "l1", p: "a" }], at: [0, 0] }, +]; + +const checks: [string, () => void][] = [ + ["rectangle squares up", () => { + const r = solve(quad, rect); + assert.ok(r.ok, `error ${r.error}`); + const [l1, l2] = r.entities as any[]; + assert.ok(Math.abs(l1.a[1] - l1.b[1]) < 1e-6 && Math.abs(l2.a[0] - l2.b[0]) < 1e-6); + }], + ["width dimension drives the rectangle", () => { + const r = solve(quad, [...rect, { id: "w", type: "dim", curves: ["l1"], prop: "length", value: 25 }, { id: "h", type: "dim", curves: ["l2"], prop: "length", value: 8 }]); + assert.ok(r.ok, `error ${r.error}`); + assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - 25) < 1e-6); + assert.ok(Math.abs(sizeOf(r.entities[1], "length")! - 8) < 1e-6); + }], + ["drag a corner keeps it rectangular", () => { + const base = solve(quad, rect).entities; + const r = solve(base, rect, { drag: [{ ref: { e: "l2", p: "b" }, to: [20, 12] }] }); + assert.ok(r.ok, `error ${r.error}`); + const l2 = r.entities[1] as any; + assert.ok(Math.abs(l2.b[0] - 20) < 0.05 && Math.abs(l2.b[1] - 12) < 0.05, JSON.stringify(l2.b)); + }], + ["tangent line to circle", () => { + const es: SketchEntity[] = [{ id: "c", kind: "circle", center: [0, 0], radius: 5 }, L("t", [-10, 6], [10, 7])]; + const r = solve(es, [{ id: "tg", type: "tangent", curves: ["t", "c"] }, { id: "h", type: "horizontal", curves: ["t"] }]); + assert.ok(r.ok, `error ${r.error}`); + const t = r.entities[1] as any; + const c = r.entities[0] as any; + // Either may move: the line must sit exactly one radius from the centre. + assert.ok(Math.abs(Math.abs(t.a[1] - c.center[1]) - c.radius) < 1e-5); + }], + ["perpendicular + equal", () => { + const es = [L("a", [0, 0], [10, 1]), L("b", [0, 0], [2, 7])]; + const r = solve(es, [{ id: "p", type: "perpendicular", curves: ["a", "b"] }, { id: "e", type: "equal", curves: ["a", "b"] }, coin("a", "a", "b", "a")]); + assert.ok(r.ok, `error ${r.error}`); + assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - sizeOf(r.entities[1], "length")!) < 1e-6); + }], +]; + +checks.push( + ["equal: the first picked line keeps its length", () => { + const es = [L("p", [0, 0], [10, 0]), L("q", [0, 5], [20, 5])]; + const r = solve(es, [{ id: "e", type: "equal", curves: ["p", "q"] }], { fixed: new Set(["p"]) }); + assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - 10) < 1e-6 && Math.abs(sizeOf(r.entities[1], "length")! - 10) < 1e-6); + }], + ["fillet on a joined corner stays tangent after solving", () => { + const es = [L("h", [0, 0], [20, 0]), L("v", [20, 0], [20, 20])]; + const cs: SketchConstraint[] = [coin("h", "b", "v", "a"), { id: "hh", type: "horizontal", curves: ["h"] }, { id: "vv", type: "vertical", curves: ["v"] }]; + const before = new Set(es.map((e) => e.id)); + const next = filletCorner(es, [20, 0], 4, 1e-6)!; + const fc = filletConstraints(next, cs, before); + const r = solve(next, fc); + assert.ok(r.ok, "solves"); + const arc = r.entities.find((e) => e.kind === "arc") as any; + const c = arcFrom3(arc.a, arc.m, arc.b)!; + assert.ok(Math.abs(c.r - 4) < 1e-6 && Math.abs(c.c[0] - 16) < 1e-6 && Math.abs(c.c[1] - 4) < 1e-6, JSON.stringify(c)); + }], + ["angle between lines: second turns about its end nearest the first", () => { + const es = [L("p", [0, 0], [20, 0]), L("q", [5, 1], [5, 11])]; + const r = angleLines(es, "p", "q", 30)!; + const q = r.entities[1] as any; + assert.deepEqual(q.a, [5, 1]); + const ang = (Math.atan2(q.b[1] - q.a[1], q.b[0] - q.a[0]) * 180) / Math.PI; + assert.ok(Math.abs(Math.abs(ang) - 30) < 1e-9 || Math.abs(Math.abs(ang) - 150) < 1e-9, `angle ${ang}`); + }], +); + +let failed = 0; +for (const [name, fn] of checks) { + try { + fn(); + console.log("ok ", name); + } catch (e) { + failed++; + console.log("FAIL", name, "—", (e as Error).message); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/edit.test.ts b/tests/edit.test.ts new file mode 100644 index 0000000..ee0589d --- /dev/null +++ b/tests/edit.test.ts @@ -0,0 +1,125 @@ +// Run: npx tsx tests/edit.test.ts +import assert from "node:assert/strict"; +import type { SketchEntity } from "../src/doc/types"; +import { connectedChain, extend, filletCorner, filletEnds, joinEnds, offsetChain, splitEntity, mirrorXf, offsetEntity, transformEntity, trim } from "../src/sketch/edit"; +import { arrangement } from "../src/sketch/regions"; + +const kinds = (es: SketchEntity[]) => es.map((e) => e.kind).sort().join(","); +const checks: [string, () => void][] = [ + ["trim circle crossed by a line → arc remains", () => { + const es: SketchEntity[] = [{ id: "c", kind: "circle", center: [0, 0], radius: 10 }, { id: "l", kind: "line", a: [-20, 0], b: [20, 0] }]; + const out = trim(es, "c", [0, 10]); + assert.equal(kinds(out), "arc,line"); + assert.equal(arrangement(out).regions.length, 1); // half disc + }], + ["trim middle of a line between two crossings", () => { + const es: SketchEntity[] = [{ id: "l", kind: "line", a: [0, 0], b: [30, 0] }, { id: "v1", kind: "line", a: [10, -5], b: [10, 5] }, { id: "v2", kind: "line", a: [20, -5], b: [20, 5] }]; + const out = trim(es, "l", [15, 0]); + assert.equal(out.filter((e) => e.kind === "line").length, 4); + }], + ["trim one side of a rect", () => { + const es: SketchEntity[] = [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }]; + const out = trim(es, "r", [0, 5]); + assert.equal(out.length, 3); + }], + ["fillet a rect corner", () => { + const es: SketchEntity[] = [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }]; + const out = filletCorner(es, [10, 5], 2, 0.5)!; + assert.equal(kinds(out), "arc,line,line,line,line"); + const r = arrangement(out).regions; + assert.equal(r.length, 1); + assert.ok(Math.abs(r[0].area - (200 - (4 - Math.PI)) ) < 0.05, `area ${r[0].area}`); + }], + ["offset rect outward", () => { + const o = offsetEntity({ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }, 2)!; + assert.deepEqual([o.kind, (o as any).w, (o as any).h], ["rect", 24, 14]); + }], + ["extend a line to a circle", () => { + const es: SketchEntity[] = [{ id: "l", kind: "line", a: [-5, 0], b: [0, 0] }, { id: "c", kind: "circle", center: [20, 0], radius: 5 }]; + const out = extend(es, "l", [0, 0])!; + const l = out.find((e) => e.id === "l") as any; + assert.ok(Math.abs(l.b[0] - 15) < 0.05, `x=${l.b[0]}`); + }], + ["join two lines into a corner (picked halves)", () => { + const es: SketchEntity[] = [{ id: "h", kind: "line", a: [0, 0], b: [10, 0] }, { id: "v", kind: "line", a: [20, 5], b: [20, 15] }]; + const out = joinEnds(es, { id: "h", at: [8, 0] }, { id: "v", at: [20, 7] })!; + const h = out.find((e) => e.id === "h") as any; + const v = out.find((e) => e.id === "v") as any; + assert.deepEqual([h.a, h.b, v.a, v.b].map((p) => p.map((x: number) => Math.round(x * 1e6) / 1e6)), [[0, 0], [20, 0], [20, 0], [20, 15]]); + assert.equal(arrangement(out).regions.length, 0); + }], + ["join line to arc: arc follows its circle", () => { + // Quarter arc of radius 10 around the origin, from (10,0) to (0,10); a line below it. + const es: SketchEntity[] = [{ id: "a", kind: "arc", a: [10, 0], m: [7.0710678, 7.0710678], b: [0, 10] }, { id: "l", kind: "line", a: [-20, -5], b: [-12, -5] }]; + const out = joinEnds(es, { id: "a", at: [1, 9.9] }, { id: "l", at: [-13, -5] })!; + const a = out.find((e) => e.id === "a") as any; + const l = out.find((e) => e.id === "l") as any; + const meet = [-Math.sqrt(75), -5]; + assert.ok(Math.hypot(a.b[0] - meet[0], a.b[1] - meet[1]) < 1e-6 && Math.hypot(l.b[0] - meet[0], l.b[1] - meet[1]) < 1e-6, JSON.stringify([a.b, l.b])); + assert.ok(Math.abs(Math.hypot(...(a.m as [number, number])) - 10) < 1e-6 && a.m[1] > 0, "mid stays on the circle, upper side"); + }], + ["both halves of one arc close it into a circle", () => { + const es: SketchEntity[] = [{ id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }]; + const out = joinEnds(es, { id: "a", at: [9, 3] }, { id: "a", at: [-9, 3] })!; + assert.equal(out[0].kind, "circle"); + }], + ["split a line at its middle", () => { + const out = splitEntity([{ id: "l", kind: "line", a: [0, 0], b: [10, 0] }], "l", "l2")!; + assert.deepEqual(out.map((e: any) => [e.id, e.a, e.b]), [["l", [0, 0], [5, 0]], ["l2", [5, 0], [10, 0]]]); + }], + ["split an arc at a tapped point", () => { + const out = splitEntity([{ id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], "a", "a2", [7.07, 7.07])! as any[]; + assert.ok(Math.hypot(out[0].b[0] - 7.0710678, out[0].b[1] - 7.0710678) < 1e-3 && out[1].a === out[0].b); + assert.ok(Math.abs(Math.hypot(...(out[0].m as [number, number])) - 10) < 1e-9 && out[0].m[1] > 0); + }], + ["fillet two separate lines picked by halves", () => { + const es: SketchEntity[] = [{ id: "h", kind: "line", a: [0, 0], b: [10, 0] }, { id: "v", kind: "line", a: [20, 5], b: [20, 15] }]; + const out = filletEnds(es, { id: "h", at: [8, 0] }, { id: "v", at: [20, 7] }, 3)!; + assert.equal(kinds(out), "arc,line,line"); + const h = out.find((e) => e.id === "h") as any; + assert.ok(Math.abs(h.b[0] - 17) < 1e-6, `h ends at ${h.b}`); + }], + ["chain: a square of four lines is found and closed", () => { + const sq: SketchEntity[] = [{ id: "1", kind: "line", a: [0, 0], b: [10, 0] }, { id: "2", kind: "line", a: [10, 10], b: [10, 0] }, { id: "3", kind: "line", a: [10, 10], b: [0, 10] }, { id: "4", kind: "line", a: [0, 10], b: [0, 0] }]; + const c = connectedChain(sq, "3")!; + assert.equal(c.links.length, 4); + assert.ok(c.closed); + }], + ["offset a closed chain outward stays closed", () => { + const sq: SketchEntity[] = [{ id: "1", kind: "line", a: [0, 0], b: [10, 0] }, { id: "2", kind: "line", a: [10, 10], b: [10, 0] }, { id: "3", kind: "line", a: [10, 10], b: [0, 10] }, { id: "4", kind: "line", a: [0, 10], b: [0, 0] }]; + const out = offsetChain(sq, "1", 1)!; + const regions = arrangement(out.slice(4)).regions; + assert.equal(regions.length, 1); + assert.ok(Math.abs(regions[0].area - 144) < 1e-6, `area ${regions[0].area}`); + }], + ["offset a rounded chain (line–arc–line) inward", () => { + // U shape closed: bottom line, right arc, top line, left line. + const es: SketchEntity[] = [ + { id: "b", kind: "line", a: [0, 0], b: [10, 0] }, + { id: "r", kind: "arc", a: [10, 0], m: [15, 5], b: [10, 10] }, + { id: "t", kind: "line", a: [10, 10], b: [0, 10] }, + { id: "l", kind: "line", a: [0, 10], b: [0, 0] }, + ]; + const out = offsetChain(es, "t", -1)!; + const regions = arrangement(out.slice(4)).regions; + assert.equal(regions.length, 1); + const expect = 9 * 8 + (Math.PI * 16) / 2; // 9 x 8 box + half disc of radius 4 + assert.ok(Math.abs(regions[0].area - expect) < 0.05, `area ${regions[0].area} vs ${expect}`); + }], + ["mirror a rect keeps size", () => { + const m = transformEntity({ id: "r", kind: "rect", center: [10, 0], w: 4, h: 2, rotation: 0 }, mirrorXf([0, -1], [0, 1]), true) as any; + assert.ok(Math.abs(m.center[0] + 10) < 1e-9 && Math.abs(m.w - 4) < 1e-9); + }], +]; + +let failed = 0; +for (const [name, fn] of checks) { + try { + fn(); + console.log("ok ", name); + } catch (e) { + failed++; + console.log("FAIL", name, "—", (e as Error).message); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/engine.test.ts b/tests/engine.test.ts new file mode 100644 index 0000000..70f7d11 --- /dev/null +++ b/tests/engine.test.ts @@ -0,0 +1,192 @@ +// Run: npx tsx tests/engine.test.ts — every feature type through the real engine. +import opencascade from "replicad-opencascadejs"; +import { setOC } from "replicad"; +import type { Feature, PlaneDef } from "../src/doc/types"; +import { exportBodies, regenerate } from "../src/kernel/engine"; +import { arrangement, regionRef } from "../src/sketch/regions"; +import { primitiveCage } from "../src/freeform/cage"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] }; +const sketch = (id: string, plane: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane, entities }); +const regions = (entities: any[]) => arrangement(entities).regions.map(regionRef); + +const rect = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 20, rotation: 0 }]; +const circle = [{ id: "c", kind: "circle", center: [30, 10], radius: 5 }]; +const base: Feature[] = [ + sketch("s1", XY, rect), + { id: "e1", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "s1", regions: regions(rect) }, distance: 10, mode: "auto" }, +]; + +const tests: [string, Feature[], (r: Awaited>) => string][] = [ + ["extrude", base, (r) => `${r.bodies.length} body, ${r.bodies[0].faces.length} faces`], + ["revolve 360 around Z offset", [sketch("s2", XZ, circle), { id: "rv", name: "Revolve", type: "revolve", source: { kind: "profile", sketch: "s2", regions: regions(circle) }, axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`], + ["sweep circle along line", [ + sketch("s3", XY, [{ id: "c", kind: "circle", center: [0, 0], radius: 2 }]), + sketch("s4", XZ, [{ id: "p", kind: "line", a: [0, 0], b: [0, 30] }]), + { id: "sw", name: "Sweep", type: "sweep", source: { kind: "profile", sketch: "s3", regions: regions([{ id: "c", kind: "circle", center: [0, 0], radius: 2 }]) }, path: { kind: "sketch", sketch: "s4", entities: ["p"] }, mode: "new" }, + ], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`], + ["loft rect → circle", [ + sketch("l1", XY, rect), + sketch("l2", { ...XY, origin: [0, 0, 30] }, [{ id: "c", kind: "circle", center: [0, 0], radius: 8 }]), + { id: "lo", name: "Loft", type: "loft", sections: [{ kind: "profile", sketch: "l1", regions: regions(rect) }, { kind: "profile", sketch: "l2", regions: regions([{ id: "c", kind: "circle", center: [0, 0], radius: 8 }]) }], ruled: false, mode: "new" }, + ], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`], + ["shell open top", [...base, { id: "sh", name: "Shell", type: "shell", body: "e1", faces: [{ body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }], thickness: 2 }], (r) => `${r.bodies[0].faces.length} faces`], + ["split by plane x=0", [...base, { id: "sp", name: "Split", type: "split", body: "e1", plane: { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } }], (r) => `${r.bodies.length} bodies`], + ["mirror copy", [...base, { id: "mi", name: "Mirror", type: "transform", bodies: ["e1"], copy: true, op: { kind: "mirror", plane: { origin: [30, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } } }], (r) => `${r.bodies.length} bodies`], + ["linear pattern x3", [...base, { id: "lp", name: "Pattern", type: "transform", bodies: ["e1"], copy: true, op: { kind: "linear", dir: [0, 1, 0], spacing: 30, count: 3 } }], (r) => `${r.bodies.length} bodies`], + ["circular pattern x4", [...base, { id: "cp", name: "Pattern", type: "transform", bodies: ["e1"], copy: true, op: { kind: "circular", axis: { origin: [60, 0, 0], dir: [0, 0, 1] }, count: 4, angle: 360 } }], (r) => `${r.bodies.length} bodies`], + ["move + rotate", [...base, { id: "mv", name: "Move", type: "transform", bodies: ["e1"], copy: false, op: { kind: "move", translate: [0, 0, 5], rotate: { origin: [0, 0, 0], axis: [0, 0, 1], angle: 45 } } }], (r) => `${r.bodies.length} body, zmin=${Math.min(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)).toFixed(1)}`], + ["scale x2", [...base, { id: "sc", name: "Scale", type: "transform", bodies: ["e1"], copy: false, op: { kind: "scale", center: [0, 0, 0], factor: 2 } }], (r) => `zmax=${Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)).toFixed(1)}`], + ["offset top face of its own body (+5 → 6 faces)", [...base, { id: "of", name: "Offset", type: "extrude", source: { kind: "face", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 } }, distance: 5, mode: "auto", target: "e1" }], (r) => { + const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)); + if (r.bodies[0].faces.length !== 6 || Math.abs(zmax - 15) > 1e-6) throw new Error(`${r.bodies[0].faces.length} faces, zmax ${zmax}`); + return `zmax=${zmax}`; + }], + ["move face: tilt top 10°", [...base, { id: "mf", name: "Move face", type: "moveFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, translate: [0, 0, 0], rotate: { origin: [0, 0, 10], axis: [0, 1, 0], angle: 10 } }], (r) => { + const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)); + if (Math.abs(zmax - (10 + 20 * Math.tan(Math.PI / 18))) > 1e-3) throw new Error(`zmax ${zmax}`); + return `zmax=${zmax.toFixed(2)}`; + }], + ["move edge up 5 (faces tilt)", [...base, { id: "me", name: "Move edge", type: "moveFace", edge: { body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }, translate: [0, 0, 5] }], (r) => { + const b = r.bodies[0]; + const zmax = Math.max(...Array.from(b.positions).filter((_, i) => i % 3 === 2)); + if (b.faces.length !== 6 || Math.abs(zmax - 15) > 1e-3) throw new Error(`${b.faces.length} faces, zmax ${zmax}`); + return `zmax=${zmax.toFixed(2)}`; + }], + ["move one corner of the box up 5 (only that corner rises)", [...base, { id: "mvv", name: "Move vertex", type: "moveFace", vertex: { body: "e1", at: [20, 10, 10] }, translate: [0, 0, 5] }], (r) => { + const b = r.bodies[0]; + const pos = b.positions; + let corner = -Infinity, other = -Infinity; + for (let i = 0; i < pos.length; i += 3) { + if (Math.hypot(pos[i] - 20, pos[i + 1] - 10) < 1e-6) corner = Math.max(corner, pos[i + 2]); + if (Math.hypot(pos[i] + 20, pos[i + 1] + 10) < 1e-6) other = Math.max(other, pos[i + 2]); + } + if (Math.abs(corner - 15) > 1e-6 || Math.abs(other - 10) > 1e-6 || b.openEdges.length) throw new Error(`corner ${corner}, opposite ${other}, open ${b.openEdges.length}`); + return `corner z=${corner.toFixed(2)}, opposite corner z=${other.toFixed(2)}`; + }], + ["move one corner along X: only the point moves, its edge neighbours stay", [...base, { id: "mvx", name: "Move vertex", type: "moveFace", vertex: { body: "e1", at: [20, 10, 10] }, translate: [5, 0, 0] }], (r) => { + const b = r.bodies[0]; + const pos = b.positions; + const has = (x: number, y: number, z: number) => { for (let i = 0; i < pos.length; i += 3) if (Math.hypot(pos[i] - x, pos[i + 1] - y, pos[i + 2] - z) < 1e-6) return true; return false; }; + // The corners next to it along the edges (below it and beside it) haven't moved. + if (!has(25, 10, 10) || !has(20, 10, 0) || !has(20, -10, 10) || has(25, 10, 0) || b.openEdges.length) throw new Error(`moved ${has(25, 10, 10)}, below ${has(20, 10, 0)}, open ${b.openEdges.length}`); + return `${b.faces.length} faces`; + }], + ["extrude (auto) through another body cuts a hole in it, no new body", [...base, + sketch("hole", { ...XY, origin: [0, 0, -5] }, [{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]), + { id: "he", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "hole", regions: regions([{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]) }, distance: 30, mode: "auto" }], (r) => { + if (r.bodies.length !== 1 || r.bodies[0].faces.length !== 7) throw new Error(`${r.bodies.length} bodies, ${r.bodies[0]?.faces.length} faces`); + return "1 body, 7 faces (hole through)"; + }], + ["extrude (new) through another body keeps both", [...base, + sketch("hole", { ...XY, origin: [0, 0, -5] }, [{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]), + { id: "he", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "hole", regions: regions([{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]) }, distance: 30, mode: "new" }], (r) => { + if (r.bodies.length !== 2) throw new Error(`${r.bodies.length} bodies`); + return "2 bodies"; + }], + ["delete fillet edge's face", [...base, + { id: "fi", name: "Fillet", type: "fillet", edges: [{ body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }], radius: 2 }, + { id: "dg", name: "Delete", type: "deleteGeom", body: "e1", faces: [], edges: [{ body: "e1", mid: [20, 0, 8], dir: [0, 1, 0], length: 20 }], vertices: [] }], (r) => { + if (r.bodies[0].faces.length !== 6) throw new Error(`${r.bodies[0].faces.length} faces`); + return "6 faces"; + }], + ["freeform sphere → one closed body", [{ id: "ff", name: "Freeform", type: "freeform", cage: primitiveCage("sphere") }], (r) => { + if (r.bodies.length !== 1 || r.bodies[0].openEdges.length) throw new Error(`${r.bodies.length} bodies, ${r.bodies[0]?.openEdges.length} open edges`); + return `${r.bodies[0].faces.length} faces`; + }], + ["scale the top face ×0.5 in its plane → tapered (sides tilt)", [...base, { id: "sf", name: "Scale Face", type: "scaleFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, u: [1, 0, 0], factors: [0.5, 0.5] }], (r) => { + const b = r.bodies[0]; + const top = b.faces.find((f) => f.normal[2] > 0.999)!; + if (Math.abs(top.area - 200) > 1e-3 || b.faces.length !== 6) throw new Error(`top area ${top.area}, ${b.faces.length} faces`); + return `top area ${top.area.toFixed(1)}`; + }], + ["replace the top face with a plane 5 higher", [...base, { id: "rf", name: "Replace", type: "replaceFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, plane: { origin: [0, 0, 15], normal: [0, 0, -1], xDir: [1, 0, 0] } }], (r) => { + const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)); + if (Math.abs(zmax - 15) > 1e-6 || r.bodies[0].faces.length !== 6) throw new Error(`zmax ${zmax}`); + return `zmax=${zmax}`; + }], + ["freeform: move, then stretch ×2 along X (rebuilt from the cage)", [ + { id: "ffx", name: "Freeform", type: "freeform", cage: primitiveCage("sphere") }, + { id: "mvx", name: "Move", type: "transform", bodies: ["ffx"], copy: false, op: { kind: "move", translate: [100, 0, 0] } }, + { id: "sx", name: "Scale XYZ", type: "transform", bodies: ["ffx"], copy: false, op: { kind: "scaleXYZ", center: [100, 0, 20], factors: [2, 1, 1] } }, + ], (r) => { + const xs = Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 0); + const ys = Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 1); + const w = Math.max(...xs) - Math.min(...xs); + const d = Math.max(...ys) - Math.min(...ys); + if (Math.abs(w / d - 2) > 0.02 || Math.abs((Math.max(...xs) + Math.min(...xs)) / 2 - 100) > 0.1) throw new Error(`w ${w} d ${d}`); + return `width ${w.toFixed(1)} vs depth ${d.toFixed(1)}`; + }], + ["construction plane offset from face", [...base, { id: "pl", name: "Plane", type: "plane", plane: XY, face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, offset: 5 }], (r) => `plane z=${r.planes[0]?.plane.origin[2]}`], +]; + +let failed = 0; +for (const [name, features, describe] of tests) { + try { + const r = await regenerate(features); + if (r.errors.length) throw new Error(r.errors.map((e) => `${e.featureId}: ${e.message}`).join("; ")); + console.log("ok ", name, "—", describe(r)); + } catch (e) { + failed++; + console.log("FAIL", name, "—", e instanceof Error ? e.message : e); + } +} +// A line across the top face splits it into two regions (with the face outline). +{ + const top = { body: "e1", center: [0, 0, 10] as [number, number, number], normal: [0, 0, 1] as [number, number, number], area: 800 }; + const plane: PlaneDef = { origin: [0, 0, 10], xDir: [1, 0, 0], normal: [0, 0, 1] }; + const line = [{ id: "l", kind: "line", a: [5, -15], b: [5, 15] }]; + const withSketch: Feature[] = [...base, { id: "sf", name: "sf", type: "sketch", plane, attachedTo: top, entities: line as any }]; + const r1 = await regenerate(withSketch); + const curves = [...line, ...(r1.sketchBoundaries.sf ?? [])] as any[]; + const regs = arrangement(curves).regions; + const small = regs.sort((a, b) => a.area - b.area)[0]; + const r2 = await regenerate([...withSketch, { id: "ex", name: "ex", type: "extrude", source: { kind: "profile", sketch: "sf", regions: [regionRef(small)] }, distance: 5, mode: "auto", target: "e1" }]); + // Top face is 40 × 20 (x −20…20); the line at x = 5 leaves 15 × 20 = 300 and 25 × 20 = 500. + const ok = regs.length === 2 && Math.round(small.area) === 300 && !r2.errors.length && r2.bodies[0].faces.length > 6; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "line across a face → 2 regions, extrude one:", regs.map((r) => Math.round(r.area)).join("/"), `${r2.bodies[0]?.faces.length} faces`, r2.errors.map((e) => e.message).join()); +} + +// A plain box edge can't be deleted: a readable error, the body stays. +{ + const r = await regenerate([...base, { id: "dg", name: "Delete", type: "deleteGeom", body: "e1", faces: [], edges: [{ body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }], vertices: [] }]); + const ok = r.errors.length === 1 && r.bodies.length === 1 && r.bodies[0].faces.length === 6; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "delete box edge refused:", r.errors.map((e) => e.message).join()); +} + +// Shell a freeform (open at its top patch): a closed, hollow body. +{ + const feats: Feature[] = [{ id: "ffs", name: "Freeform", type: "freeform", cage: primitiveCage("box") }]; + const b0 = (await regenerate(feats)).bodies[0]; + const top = b0.faces.reduce((bi, f, i) => (f.center[2] > b0.faces[bi].center[2] ? i : bi), 0); + const f = b0.faces[top]; + const r = await regenerate([...feats, { id: "shf", name: "Shell", type: "shell", body: "ffs", faces: [{ body: "ffs", center: f.center, normal: f.normal, area: f.area }], thickness: 2 }]); + const ok = !r.errors.length && r.bodies[0].faces.length > 40 && r.bodies[0].openEdges.length === 0; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "shell a freeform:", `${b0.faces.length} → ${r.bodies[0].faces.length} faces`, r.errors.map((e) => e.message).join()); +} + +// XYZ scale of an ordinary body: a clear message, the body stays. +{ + const r = await regenerate([...base, { id: "sx2", name: "Scale XYZ", type: "transform", bodies: ["e1"], copy: false, op: { kind: "scaleXYZ", center: [0, 0, 0], factors: [2, 1, 1] } }]); + const ok = r.errors.length === 1 && /freeform/.test(r.errors[0].message) && r.bodies.length === 1; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "XYZ scale on a regular body explains why not:", r.errors.map((e) => e.message).join()); +} + +// Closed solids report no open edges. +{ + const r = await regenerate(base); + const ok = r.bodies[0].openEdges.length === 0; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "closed box has no open edges:", r.bodies[0].openEdges.length); +} + +const stl = await exportBodies(base, "stl"); +console.log("ok export stl", stl.size, "bytes"); +process.exit(failed ? 1 : 0); diff --git a/tests/faceedit.test.ts b/tests/faceedit.test.ts new file mode 100644 index 0000000..b0e4f80 --- /dev/null +++ b/tests/faceedit.test.ts @@ -0,0 +1,90 @@ +// Run: npx tsx tests/faceedit.test.ts — direct face edits on real OpenCascade solids. +import opencascade from "replicad-opencascadejs"; +import { basicFaceExtrusion, makeCylinder, makeBox, measureVolume, setOC, Vector, type Shape3D } from "replicad"; +import { deleteFace, offsetFace, replaceFacePlane } from "../src/kernel/faceEdit"; +import { regionFaces } from "../src/kernel/sketchGeom"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); +const XY = { origin: [0, 0, 0] as [number, number, number], xDir: [1, 0, 0] as [number, number, number], normal: [0, 0, 1] as [number, number, number] }; +const near = (a: number, b: number, tol = 1e-3) => Math.abs(a - b) < tol * Math.max(1, Math.abs(b)); +const faceWith = (s: Shape3D, pred: (n: number[], c: number[], t: string) => boolean) => + s.faces.find((f) => pred(f.normalAt().toTuple(), f.center.toTuple(), f.geomType))!; + +const checks: [string, () => string][] = [ + ["box: offset top +5 keeps a box", () => { + const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D; + const r = offsetFace(box, faceWith(box, (n) => n[2] > 0.9), 5); + if (!near(measureVolume(r), 20 * 10 * 15) || r.faces.length !== 6) throw new Error(`vol ${measureVolume(r)} faces ${r.faces.length}`); + return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`; + }], + ["D-shape: flat face pushed out extends the round side", () => { + // Half disc (radius 10) extruded; push the flat side outward by 3. + const es: any[] = [{ id: "l", kind: "line", a: [-10, 0], b: [10, 0] }, { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }]; + const f = regionFaces(es, XY, arrangement(es).regions.map(regionRef))[0]; + const d = basicFaceExtrusion(f, new Vector([0, 0, 5])) as Shape3D; + const flat = faceWith(d, (n, _c, t) => t === "PLANE" && n[1] < -0.9); + const r = offsetFace(d, flat, 3); + // Extending the arc downward by 3 (not a prism): faces stay 4, and the round face continues the circle. + const round = r.faces.filter((x) => x.geomType === "CYLINDRE"); + if (r.faces.length !== 4 || round.length !== 1) throw new Error(`${r.faces.length} faces, ${round.length} round`); + return `${r.faces.length} faces, vol ${measureVolume(r).toFixed(1)}`; + }], + ["cylinder radius 5 → 7", () => { + const c = makeCylinder(5, 10) as Shape3D; + const r = offsetFace(c, faceWith(c, (_n, _c, t) => t === "CYLINDRE"), 2); + if (!near(measureVolume(r), Math.PI * 49 * 10, 2e-3)) throw new Error(`vol ${measureVolume(r)}`); + return `vol ${measureVolume(r).toFixed(1)}`; + }], + ["hole radius 3 → 2 (offset +1 adds material)", () => { + const plate = (makeBox([-10, -10, 0], [10, 10, 4]) as Shape3D).cut(makeCylinder(3, 4) as Shape3D); + const wall = faceWith(plate, (_n, _c, t) => t === "CYLINDRE"); + const r = offsetFace(plate, wall, 1); + if (!near(measureVolume(r), 400 * 4 - Math.PI * 4 * 4, 2e-3)) throw new Error(`vol ${measureVolume(r)}`); + return `vol ${measureVolume(r).toFixed(1)}`; + }], + ["delete a fillet face → sharp box", () => { + const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D; + const fil = box.fillet(2, (e) => e.inDirection("Y").ofCurveType("LINE").containsPoint([20, 5, 10])); + const ff = faceWith(fil, (_n, _c, t) => t === "CYLINDRE"); + const r = deleteFace(fil, ff); + if (!near(measureVolume(r), 2000)) throw new Error(`vol ${measureVolume(r)}, faces ${r.faces.length}`); + return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`; + }], + ["delete an inside-corner fillet → sharp L again (no extra block)", () => { + // L-shape: a 20×20×10 block with a 10×10 notch out of one corner, inner edge filleted. + const L = (makeBox([0, 0, 0], [20, 20, 10]) as Shape3D).cut(makeBox([10, 10, -1], [21, 21, 11]) as Shape3D); + const fil = L.fillet(3, (e) => e.inDirection("Z").containsPoint([10, 10, 5])); + const before = measureVolume(L); + const ff = faceWith(fil, (_n, _c, t) => t === "CYLINDRE"); + const r = deleteFace(fil, ff); + if (!near(measureVolume(r), before)) throw new Error(`vol ${measureVolume(r)} vs ${before} (filleted ${measureVolume(fil)})`); + return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`; + }], + ["delete a hole wall → solid plate", () => { + const plate = (makeBox([-10, -10, 0], [10, 10, 4]) as Shape3D).cut(makeCylinder(3, 4) as Shape3D); + const r = deleteFace(plate, faceWith(plate, (_n, _c, t) => t === "CYLINDRE")); + if (!near(measureVolume(r), 1600)) throw new Error(`vol ${measureVolume(r)}`); + return `vol ${measureVolume(r).toFixed(1)}`; + }], + ["tilt the top face 10° about its edge", () => { + const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D; + const a = (10 * Math.PI) / 180; + // Plane through the top edge at x=0, tilted down towards +x. + const r = replaceFacePlane(box, faceWith(box, (n) => n[2] > 0.9), { origin: [0, 5, 10], normal: [Math.sin(a), 0, Math.cos(a)], xDir: [1, 0, 0] }); + const expect = 20 * 10 * 10 - 0.5 * 20 * (20 * Math.tan(a)) * 10; + if (!near(measureVolume(r), expect, 2e-3)) throw new Error(`vol ${measureVolume(r)} vs ${expect}`); + return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`; + }], +]; + +let failed = 0; +for (const [name, fn] of checks) { + try { + console.log("ok ", name, "—", fn()); + } catch (e) { + failed++; + console.log("FAIL", name, "—", e instanceof Error ? e.message : e); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/filletedit.test.ts b/tests/filletedit.test.ts new file mode 100644 index 0000000..74ad743 --- /dev/null +++ b/tests/filletedit.test.ts @@ -0,0 +1,68 @@ +// Run: npx tsx tests/filletedit.test.ts — moving faces next to big fillets keeps the fillets +// (no tunnels carved through the body by an extended fillet cylinder). +import opencascade from "replicad-opencascadejs"; +import { setOC } from "replicad"; +import type { Feature, PlaneDef } from "../src/doc/types"; +import { regenerate } from "../src/kernel/engine"; +import type { BodyMesh } from "../src/kernel/protocol"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +const rect = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 30, rotation: 0 }]; +const R = 8; +const base: Feature[] = [ + { id: "s", name: "s", type: "sketch", plane: XY, entities: rect as any }, + { id: "b", name: "b", type: "extrude", source: { kind: "profile", sketch: "s", regions: arrangement(rect as any).regions.map(regionRef) }, distance: 20, mode: "new" }, + // A big fillet along the top back edge. + { id: "f", name: "f", type: "fillet", edges: [{ body: "b", mid: [0, 15, 20], dir: [1, 0, 0], length: 40 }], radius: R }, +]; +const corner = R * R * (1 - Math.PI / 4); // material a fillet takes off, per unit length + +function volume(b: BodyMesh): number { + const p = b.positions; + const ix = b.indices; + let v = 0; + for (let i = 0; i < ix.length; i += 3) { + const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3]; + v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6; + } + return v; +} + +let failed = 0; +async function check(name: string, extra: Feature[], expected: number, cylinders = 1): Promise { + const r = await regenerate([...base, ...extra]); + const b = r.bodies[0]; + const v = b ? volume(b) : NaN; + const cyl = b ? b.faces.filter((f) => f.type !== "PLANE").length : -1; + const ok = !r.errors.length && (Number.isNaN(expected) ? v > 20000 && v < 30000 : Math.abs(v - expected) < expected * 0.005) && cyl === cylinders && b.openEdges.length === 0; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", name, `vol ${v.toFixed(1)} (want ${expected.toFixed(1)}), round faces ${cyl}`, r.errors.map((e) => e.message).join("; ")); +} + +const faceRef = async (pick: (f: { center: number[]; normal: number[] }) => boolean) => { + const r = await regenerate(base); + const f = r.bodies[0].faces.find(pick)!; + return { body: "b", center: f.center, normal: f.normal, area: f.area } as any; +}; +const offset = (id: string, face: any, d: number): Feature => ({ id, name: id, type: "extrude", source: { kind: "face", face }, distance: d, mode: "auto", target: "b" } as Feature); + +await check("filleted box as built", [], 24000 - 40 * corner); +const top = await faceRef((f) => f.normal[2] > 0.99); +await check("top face (fillet runs into it) up 5", [offset("o1", top, 5)], 40 * 30 * 25 - 40 * corner); +await check("top face down 4", [offset("o1", top, -4)], 40 * 30 * 16 - 40 * corner); +const side = await faceRef((f) => f.normal[0] > 0.99); +await check("side face (fillet ends on it) out 5", [offset("o2", side, 5)], 45 * 30 * 20 - 45 * corner); +await check("side face in 6", [offset("o2", side, -6)], 34 * 30 * 20 - 34 * corner); +const back = await faceRef((f) => f.normal[1] > 0.99); +await check("back face (fillet runs into it) out 3", [offset("o3", back, 3)], 40 * 33 * 20 - 40 * corner); +const front = await faceRef((f) => f.normal[1] < -0.99); +await check("front face (no fillet) out 5", [offset("o4", front, 5)], 40 * 35 * 20 - 40 * corner); + +// A corner next to the fillet, pulled up: the faces around it tilt, the fillet stays one round face. +await check("front-right-top corner up 4", [{ id: "mv", name: "mv", type: "moveFace", vertex: { body: "b", at: [20, -15, 20] }, translate: [0, 0, 4] } as Feature], NaN); +await check("edge next to it (front top) up 3", [{ id: "me", name: "me", type: "moveFace", edge: { body: "b", mid: [0, -15, 20], dir: [1, 0, 0], length: 40 }, translate: [0, 0, 3] } as Feature], NaN); + +process.exit(failed ? 1 : 0); diff --git a/tests/freeform.test.ts b/tests/freeform.test.ts new file mode 100644 index 0000000..13dc755 --- /dev/null +++ b/tests/freeform.test.ts @@ -0,0 +1,124 @@ +// Run: npx tsx tests/freeform.test.ts — cages, subdivision and the cage → solid conversion. +import assert from "node:assert/strict"; +import opencascade from "replicad-opencascadejs"; +import { measureVolume, setOC, type Shape3D } from "replicad"; +import { boundaryEdges, boxCage, bridgeLoops, cageEdgeKey, cageEdges, cylinderCage, deleteFaces, fillLoop, holeLoops, isClosed, planeCage, sphereCage, subdivide } from "../src/freeform/cage"; +import { cageToShape } from "../src/kernel/freeform"; +import { evalSurface, interpolateGrid } from "../src/freeform/bspline"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const checks: [string, () => string][] = [ + ["cages are closed (box, cylinder, sphere) / open (plane)", () => { + assert.ok(isClosed(boxCage())); + assert.ok(isClosed(cylinderCage())); + assert.ok(isClosed(sphereCage())); + assert.ok(!isClosed(planeCage())); + return `box ${boxCage().verts.length} pts, cylinder ${cylinderCage().faces.length} faces`; + }], + ["subdivision: every face becomes a 9×9 grid sharing its borders", () => { + const s = subdivide(boxCage(), 3); + assert.equal(s.n, 8); + assert.equal(s.grids.length, 24); + // Euler characteristic of a closed surface: V − E + F = 2. + const F = s.grids.length * 64; + const E = (F * 4) / 2; + assert.equal(s.points.length - E + F, 2); + return `${s.points.length} points`; + }], + ["patch surfaces pass through their grid points", () => { + const s = subdivide(sphereCage(40), 3); + const g = s.grids[5].map((row) => row.map((i) => s.points[i])); + const poles = interpolateGrid(g); + let worst = 0; + for (let i = 0; i <= 8; i++) + for (let j = 0; j <= 8; j++) { + const q = evalSurface(poles, i / 8, j / 8); + worst = Math.max(worst, Math.hypot(q[0] - g[i][j][0], q[1] - g[i][j][1], q[2] - g[i][j][2])); + } + assert.ok(worst < 1e-9, `off by ${worst}`); + return `max error ${worst.toExponential(1)}`; + }], + ["sphere cage → near-spherical solid of ~diameter 40", () => { + const solid = cageToShape(sphereCage(40)); + const v = measureVolume(solid); + const ideal = (4 / 3) * Math.PI * 20 ** 3; + const bb = solid.boundingBox; + assert.ok(Math.abs(v - ideal) / ideal < 0.12, `volume ${v} vs ${ideal}`); + return `vol ${v.toFixed(0)} (sphere ${ideal.toFixed(0)}), ${solid.faces.length} faces, size ${bb.width.toFixed(1)}`; + }], + ["box cage → closed solid", () => { + const solid = cageToShape(boxCage([40, 40, 40], 2)); + const v = measureVolume(solid); + assert.ok(v > 20000 && v < 64000, `volume ${v}`); + return `vol ${v.toFixed(0)}, ${solid.faces.length} faces`; + }], + ["cylinder cage → closed solid", () => { + const solid = cageToShape(cylinderCage(40, 40)); + const v = measureVolume(solid); + assert.ok(v > 20000, `volume ${v}`); + return `vol ${v.toFixed(0)}`; + }], + ["moving a cage point bulges the shape", () => { + const c = sphereCage(40); + const top = c.verts.reduce((best, p, i) => (p[2] > c.verts[best][2] ? i : best), 0); + const before = cageToShape(c).boundingBox.depth; + c.verts[top] = [c.verts[top][0], c.verts[top][1], c.verts[top][2] + 20]; + const after = cageToShape(c).boundingBox.depth; + assert.ok(after > before + 5, `${before} → ${after}`); + return `height ${before.toFixed(1)} → ${after.toFixed(1)}`; + }], + ["plane surface thickened up / down / both → solids of the same volume", () => { + const vols = (["up", "down", "both"] as const).map((side) => { + const s = cageToShape(planeCage([60, 60], 4), 3, { thickness: 2, side }); + const bb = s.boundingBox; + return { v: measureVolume(s), zmin: bb.bounds[0][2], zmax: bb.bounds[1][2] }; + }); + for (const x of vols) assert.ok(Math.abs(x.v - vols[0].v) / vols[0].v < 0.02 && x.v > 1000, JSON.stringify(vols)); + assert.ok(vols[0].zmin > -0.01 && vols[1].zmax < 0.01 && vols[2].zmin < -0.9 && vols[2].zmax > 0.9, JSON.stringify(vols)); + return vols.map((x) => `${x.v.toFixed(0)} [${x.zmin.toFixed(1)}…${x.zmax.toFixed(1)}]`).join(", "); + }], + ["delete a face, then fill the hole again → closed solid", () => { + const box = boxCage([40, 40, 40], 2); + const holed = deleteFaces(box, [0]); + assert.ok(!isClosed(holed)); + const rim = new Set(boundaryEdges(holed).map(([a, b]) => cageEdgeKey(a, b))); + const loops = holeLoops(holed, rim); + assert.equal(loops.length, 1); + const filled = fillLoop(holed, loops[0])!; + assert.ok(isClosed(filled)); + const v = measureVolume(cageToShape(filled)); + assert.ok(v > 0, `volume ${v}`); + return `hole of ${loops[0].length} edges filled, vol ${v.toFixed(0)}`; + }], + ["two facing holes bridged → closed (tunnel)", () => { + // Box, 3 per side: remove the middle top and middle bottom quads → a hole through. + const box = boxCage([40, 40, 40], 3); + const holed = deleteFaces(box, [4, 13]); + const loops = holeLoops(holed, new Set(boundaryEdges(holed).map(([a, b]) => cageEdgeKey(a, b)))); + assert.equal(loops.length, 2); + const tube = bridgeLoops(holed, loops[0], loops[1])!; + assert.ok(isClosed(tube)); + const solid = cageToShape(tube); + const full = measureVolume(cageToShape(box)); + // A real hole through: less than the full box, but most of it is still there. + assert.ok(measureVolume(solid) > full * 0.5 && measureVolume(solid) < full * 0.97, `volume ${measureVolume(solid)} vs box ${full}`); + return `${tube.faces.length} faces, vol ${measureVolume(solid).toFixed(0)}`; + }], + ["plane cage → open surface (a shell, no volume)", () => { + const sheet = cageToShape(planeCage([60, 60], 4)) as Shape3D; + assert.equal(sheet.faces.length, 16); + return `${sheet.faces.length} faces, ${cageEdges(planeCage()).length} cage edges`; + }], +]; + +let failed = 0; +for (const [name, fn] of checks) { + try { + console.log("ok ", name, "—", fn()); + } catch (e) { + failed++; + console.log("FAIL", name, "—", e instanceof Error ? e.message : e); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/kernel.test.ts b/tests/kernel.test.ts new file mode 100644 index 0000000..0e2c649 --- /dev/null +++ b/tests/kernel.test.ts @@ -0,0 +1,38 @@ +// Run: npx tsx tests/kernel.test.ts — checks sketch regions become valid solids. +import opencascade from "replicad-opencascadejs"; +import { basicFaceExtrusion, measureArea, setOC, Vector } from "replicad"; +import type { PlaneDef, SketchEntity } from "../src/doc/types"; +import { regionFaces } from "../src/kernel/sketchGeom"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); +const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +const FRONT: PlaneDef = { origin: [0, 0, 5], xDir: [1, 0, 0], normal: [0, -1, 0] }; + +const cases: [string, SketchEntity[], PlaneDef][] = [ + ["rect", [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }], XY], + ["ring", [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 20, rotation: 0 }, { id: "c", kind: "circle", center: [0, 0], radius: 5 }], XY], + ["circles crossing", [{ id: "a", kind: "circle", center: [0, 0], radius: 10 }, { id: "b", kind: "circle", center: [10, 0], radius: 10 }], FRONT], + ["D", [{ id: "l", kind: "line", a: [-10, 0], b: [10, 0] }, { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], XY], + ["ellipse", [{ id: "e", kind: "ellipse", center: [3, 2], rx: 10, ry: 5, rotation: 0.3 }], XY], + ["ellipse cut by line", [{ id: "e", kind: "ellipse", center: [0, 0], rx: 10, ry: 5, rotation: 0 }, { id: "l", kind: "line", a: [0, -10], b: [0, 10] }], XY], + ["spline", [{ id: "s", kind: "spline", points: [[0, 0], [10, 0], [12, 8], [0, 10]], closed: true, mode: "fit" }], XY], + ["rotated rect + circle overlap", [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 20, rotation: 0.4 }, { id: "c", kind: "circle", center: [10, 0], radius: 6 }], XY], +]; + +let failed = 0; +for (const [name, entities, plane] of cases) { + try { + const arr = arrangement(entities); + const faces = regionFaces(entities, plane, arr.regions.map(regionRef)); + const out = faces.map((f, i) => { + const s = basicFaceExtrusion(f, new Vector(plane.normal).multiply(5)); + return `${measureArea(f).toFixed(2)}/${arr.regions[i].area.toFixed(2)}:${s.faces.length}f`; + }); + console.log("ok ", name, out.join(" ")); + } catch (e) { + failed++; + console.log("FAIL", name, e instanceof Error ? e.message : e); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/loft.test.ts b/tests/loft.test.ts new file mode 100644 index 0000000..3731145 --- /dev/null +++ b/tests/loft.test.ts @@ -0,0 +1,92 @@ +// Run: npx tsx tests/loft.test.ts — lofts in many arrangements, and a spline revolve. +import opencascade from "replicad-opencascadejs"; +import { setOC } from "replicad"; +import type { ExtrudeSource, Feature, PlaneDef } from "../src/doc/types"; +import { regenerate } from "../src/kernel/engine"; +import type { BodyMesh } from "../src/kernel/protocol"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const plane = (z: number, flip = false): PlaneDef => ({ origin: [0, 0, z], xDir: [1, 0, 0], normal: flip ? [0, 0, -1] : [0, 0, 1] }); +const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] }; +const sketch = (id: string, p: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane: p, entities }); +const prof = (id: string, entities: any[]): ExtrudeSource => ({ kind: "profile", sketch: id, regions: arrangement(entities).regions.map(regionRef) }); +const loft = (sections: ExtrudeSource[], ruled = false): Feature => ({ id: "lo", name: "Loft", type: "loft", sections, ruled, mode: "new" }); + +const rect = (w: number, h: number, rot = 0) => [{ id: "r", kind: "rect", center: [0, 0], w, h, rotation: rot }]; +const circle = (r: number, c: [number, number] = [0, 0]) => [{ id: "c", kind: "circle", center: c, radius: r }]; +const hexagon = [{ id: "h", kind: "polygon", center: [0, 0], radius: 10, sides: 6, angle: 0.3 }]; +const blob = [{ id: "s", kind: "spline", points: [[10, 0], [4, 8], [-9, 5], [-7, -6], [3, -9]], closed: true, mode: "fit" }]; + +function volume(b: BodyMesh): number { + const p = b.positions; + const ix = b.indices; + let v = 0; + for (let i = 0; i < ix.length; i += 3) { + const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3]; + v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6; + } + return v; +} + +let failed = 0; +async function check(name: string, feats: Feature[], lo: number, hi: number): Promise { + const r = await regenerate(feats); + const b = r.bodies.find((x) => x.id === "lo" || x.id === "rv") ?? r.bodies[r.bodies.length - 1]; + const v = b ? volume(b) : NaN; + const ok = !r.errors.length && !!b && b.openEdges.length === 0 && v > lo && v < hi; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", name, `vol=${v.toFixed(0)} (${lo}..${hi}) faces=${b?.faces.length} open=${b?.openEdges.length}`, r.errors.map((e) => e.message).join("; ")); +} + +// Prism-like bounds: between the smaller and the larger section × height. +await check("rect → circle", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30), circle(8)), loft([prof("a", rect(40, 20)), prof("b", circle(8))])], 200 * 30, 800 * 30); +await check("circle → circle, shifted sideways", [sketch("a", plane(0), circle(10)), sketch("b", plane(30), circle(5, [15, 0])), loft([prof("a", circle(10)), prof("b", circle(5, [15, 0]))])], 78 * 30, 315 * 30); +await check("rect → rect turned 45°", [sketch("a", plane(0), rect(20, 20)), sketch("b", plane(30), rect(20, 20, Math.PI / 4)), loft([prof("a", rect(20, 20)), prof("b", rect(20, 20, Math.PI / 4))])], 300 * 30, 400 * 30 + 1); +await check("three sections rect → circle → rect", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), circle(8)), sketch("c", plane(40), rect(30, 30)), loft([prof("a", rect(30, 30)), prof("b", circle(8)), prof("c", rect(30, 30))])], 200 * 40, 900 * 40); +await check("picked top first", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30), circle(8)), loft([prof("b", circle(8)), prof("a", rect(40, 20))])], 200 * 30, 800 * 30); +await check("middle picked last (out of order)", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), circle(8)), sketch("c", plane(40), rect(30, 30)), loft([prof("a", rect(30, 30)), prof("c", rect(30, 30)), prof("b", circle(8))])], 200 * 40, 900 * 40); +await check("plane facing down (reversed wire)", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30, true), circle(8)), loft([prof("a", rect(40, 20)), prof("b", circle(8))])], 200 * 30, 800 * 30); +await check("hexagon → circle", [sketch("a", plane(0), hexagon), sketch("b", plane(25), circle(6)), loft([prof("a", hexagon), prof("b", circle(6))])], 113 * 25, 260 * 25); +await check("spline blob → circle", [sketch("a", plane(0), blob), sketch("b", plane(25), circle(5)), loft([prof("a", blob), prof("b", circle(5))])], 78 * 25, 400 * 25); +await check("ruled rect → smaller rect", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), rect(10, 10)), loft([prof("a", rect(30, 30)), prof("b", rect(10, 10))], true)], 100 * 20, 900 * 20); +await check("box top face → circle", [ + sketch("a", plane(0), rect(30, 30)), + { id: "e", name: "Extrude", type: "extrude", source: prof("a", rect(30, 30)), distance: 10, mode: "new" }, + sketch("b", plane(40), circle(6)), + { id: "lo", name: "Loft", type: "loft", sections: [{ kind: "face", face: { body: "e", center: [0, 0, 10], normal: [0, 0, 1], area: 900 } }, prof("b", circle(6))], ruled: false, mode: "new" }, +], 113 * 30, 900 * 30); +await check("tilted planes (not parallel)", [sketch("a", plane(0), rect(20, 20)), sketch("b", { origin: [0, 0, 30], xDir: [1, 0, 0], normal: [0, Math.sin(0.4), Math.cos(0.4)] }, circle(8)), loft([prof("a", rect(20, 20)), prof("b", circle(8))])], 200 * 25, 400 * 35); + +// A vase: spline side + straight bottom, top and axis, turned about Z. +const vase = [ + { id: "sp", kind: "spline", points: [[10, 0], [14, 10], [8, 25], [12, 40]], closed: false, mode: "fit" }, + { id: "t", kind: "line", a: [12, 40], b: [0, 40] }, + { id: "ax", kind: "line", a: [0, 40], b: [0, 0] }, + { id: "bt", kind: "line", a: [0, 0], b: [10, 0] }, +]; +{ + const feats: Feature[] = [sketch("v", XZ, vase), { id: "rv", name: "Revolve", type: "revolve", source: prof("v", vase), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }]; + await check("spline vase revolve", feats, Math.PI * 8 * 8 * 40, Math.PI * 14 * 14 * 40); + // The spline side is one smooth face (not a stack of strips from a fitted curve). + const r = await regenerate(feats); + const side = r.bodies[0].faces.filter((f) => f.type !== "PLANE").length; + const ok = side === 1; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", "vase side is one face:", side); +} + +// A thread: a small triangle turned 5 times while moving 10 along the axis (pitch 2). +{ + const tri = [{ id: "tr", kind: "polyline", closed: true, points: [[10, 0], [11.2, 0.7], [10, 1.4]] }]; + const area = (1.2 * 1.4) / 2; + const ideal = area * 2 * Math.PI * 10.4 * 5; + await check("thread: 5 turns, travel 10", [sketch("t", XZ, tri), { id: "rv", name: "Revolve", type: "revolve", source: prof("t", tri), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 1800, travel: 10, mode: "new" } as Feature], ideal * 0.9, ideal * 1.1); + // A spring the other way round (negative travel). + const disc = [{ id: "d", kind: "circle", center: [15, 0], radius: 1 }]; + const ideal2 = Math.PI * 2 * Math.PI * 15 * 3; + await check("spring: 3 turns, travel -12", [sketch("t", XZ, disc), { id: "rv", name: "Revolve", type: "revolve", source: prof("t", disc), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 1080, travel: -12, mode: "new" } as Feature], ideal2 * 0.9, ideal2 * 1.1); +} + +process.exit(failed ? 1 : 0); diff --git a/tests/offsetcurved.test.ts b/tests/offsetcurved.test.ts new file mode 100644 index 0000000..15e9a1d --- /dev/null +++ b/tests/offsetcurved.test.ts @@ -0,0 +1,69 @@ +// Run: npx tsx tests/offsetcurved.test.ts — Offset Face on flat faces bordered by curved +// (sloped) faces: the curved neighbours carry on, it isn't a straight extrude. +import opencascade from "replicad-opencascadejs"; +import { setOC } from "replicad"; +import type { Feature, PlaneDef } from "../src/doc/types"; +import { regenerate } from "../src/kernel/engine"; +import type { BodyMesh } from "../src/kernel/protocol"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] }; +const sketch = (id: string, plane: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane, entities }); +const prof = (id: string, entities: any[]) => ({ kind: "profile" as const, sketch: id, regions: arrangement(entities).regions.map(regionRef) }); + +function volume(b: BodyMesh): number { + const p = b.positions; + const ix = b.indices; + let v = 0; + for (let i = 0; i < ix.length; i += 3) { + const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3]; + v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6; + } + return v; +} + +let failed = 0; +async function offsetTop(name: string, feats: Feature[], body: string, d: number, want: (v0: number) => [number, number]): Promise { + const r0 = await regenerate(feats); + const b0 = r0.bodies.find((b) => b.id === body)!; + const top = b0.faces.reduce((bi, f, i) => (f.normal[2] > 0.99 && (b0.faces[bi].normal[2] <= 0.99 || f.center[2] > b0.faces[bi].center[2]) ? i : bi), 0); + const f = b0.faces[top]; + const r = await regenerate([...feats, { id: "of", name: "of", type: "extrude", source: { kind: "face", face: { body, center: f.center, normal: f.normal, area: f.area } }, distance: d, mode: "auto", target: body } as Feature]); + const b = r.bodies.find((x) => x.id === body)!; + const v0 = volume(b0); + const v = volume(b); + const zmax = Math.max(...Array.from(b.positions).filter((_, i) => i % 3 === 2)); + const [lo, hi] = want(v0); + const ok = !r.errors.length && v > lo && v < hi && b.openEdges.length === 0 && Math.abs(zmax - (f.center[2] + d)) < 1e-3; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", name, `vol ${v0.toFixed(0)} → ${v.toFixed(0)} (${lo.toFixed(0)}..${hi.toFixed(0)}), top z ${zmax.toFixed(2)}`, r.errors.map((e) => e.message).join("; ")); +} + +// A cone (frustum r 20 → 10 over 20): the top carries on up the cone. +const trap = [{ id: "t", kind: "polyline", closed: true, points: [[0, 0], [20, 0], [10, 20], [0, 20]] }]; +const cone: Feature[] = [sketch("c", XZ, trap), { id: "cone", name: "cone", type: "revolve", source: prof("c", trap), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }]; +const frustum = (r1: number, r2: number, h: number) => ((Math.PI * h) / 3) * (r1 * r1 + r1 * r2 + r2 * r2); +// Up 5: top radius 7.5 at z 25 (a straight extrude would keep radius 10). +await offsetTop("cone top up 5", cone, "cone", 5, () => [frustum(20, 7.5, 25) * 0.99, frustum(20, 7.5, 25) * 1.01]); +await offsetTop("cone top down 4", cone, "cone", -4, () => [frustum(20, 12, 16) * 0.99, frustum(20, 12, 16) * 1.01]); + +// A loft (square → circle): the circle face carries on along the lofted side. +const sq = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 40, rotation: 0 }]; +const ci = [{ id: "c", kind: "circle", center: [0, 0], radius: 10 }]; +const lofted: Feature[] = [sketch("a", XY, sq), sketch("b", { ...XY, origin: [0, 0, 30] }, ci), { id: "lo", name: "lo", type: "loft", sections: [prof("a", sq), prof("b", ci)], ruled: false, mode: "new" } as Feature]; +await offsetTop("loft top up 3", lofted, "lo", 3, (v0) => [v0 + 3 * 100, v0 + 3 * 314]); + +// A vase (revolved spline): the rim carries on. +const vase = [ + { id: "sp", kind: "spline", points: [[10, 0], [14, 10], [8, 25], [12, 40]], closed: false, mode: "fit" }, + { id: "t", kind: "line", a: [12, 40], b: [0, 40] }, + { id: "ax", kind: "line", a: [0, 40], b: [0, 0] }, + { id: "bt", kind: "line", a: [0, 0], b: [10, 0] }, +]; +const vaseF: Feature[] = [sketch("v", XZ, vase), { id: "rv", name: "rv", type: "revolve", source: prof("v", vase), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }]; +await offsetTop("vase rim up 2", vaseF, "rv", 2, (v0) => [v0 + 2 * Math.PI * 100, v0 + 2 * Math.PI * 196]); + +process.exit(failed ? 1 : 0); diff --git a/tests/regions.test.ts b/tests/regions.test.ts new file mode 100644 index 0000000..18fc342 --- /dev/null +++ b/tests/regions.test.ts @@ -0,0 +1,44 @@ +// Run: npx tsx tests/regions.test.ts +import assert from "node:assert/strict"; +import type { SketchEntity } from "../src/doc/types"; +import { arrangement } from "../src/sketch/regions"; + +const rect = (id: string, cx: number, cy: number, w: number, h: number): SketchEntity => ({ id, kind: "rect", center: [cx, cy], w, h, rotation: 0 }); +const line = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b }); +const summary = (es: SketchEntity[]) => + arrangement(es) + .regions.map((r) => `${r.area.toFixed(2)}${r.holes.length ? `(h${r.holes.length})` : ""}`) + .sort(); + +const cases: [string, SketchEntity[], string[]][] = [ + ["single rect", [rect("a", 0, 0, 20, 10)], ["200.00"]], + // Areas are of the display polygons (96 segments per circle), not exact. + ["circle in rect → ring + disk", [rect("a", 0, 0, 40, 20), { id: "c", kind: "circle", center: [0, 0], radius: 5 }], ["721.52(h1)", "78.48"]], + ["two overlapping rects → 3", [rect("a", 0, 0, 20, 20), rect("b", 10, 10, 20, 20)], ["100.00", "300.00", "300.00"]], + ["four lines → square", [line("1", [0, 0], [10, 0]), line("2", [10, 0], [10, 10]), line("3", [10, 10], [0, 10]), line("4", [0, 10], [0, 0])], ["100.00"]], + ["line through rect → 2", [rect("a", 0, 0, 20, 10), line("l", [0, -10], [0, 10])], ["100.00", "100.00"]], + ["D shape (arc + line)", [line("l", [-10, 0], [10, 0]), { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], ["156.97"]], + ["dangling line ignored", [rect("a", 0, 0, 20, 10), line("l", [10, 0], [30, 0])], ["200.00"]], + ["line ending inside splits nothing", [rect("a", 0, 0, 20, 10), line("l", [0, 0], [30, 0])], ["200.00"]], + ["ellipse", [{ id: "e", kind: "ellipse", center: [0, 0], rx: 10, ry: 5, rotation: 0.3 }], ["156.97"]], + ["construction ignored", [rect("a", 0, 0, 20, 10), { ...line("l", [0, -10], [0, 10]), construction: true }], ["200.00"]], + ["closed spline", [{ id: "s", kind: "spline", points: [[0, 0], [10, 0], [10, 10], [0, 10]], closed: true, mode: "fit" }], ["*"]], + ["two circles crossing → 3", [{ id: "c1", kind: "circle", center: [0, 0], radius: 10 }, { id: "c2", kind: "circle", center: [10, 0], radius: 10 }], ["*", "*", "*"]], + // Lines drawn over a face's outline (the rect): the doubled edges count once. + ["lines on a rect's edges → 2", [rect("f", 0, 0, 20, 10), line("1", [-10, -5], [0, -5]), line("2", [0, -5], [0, 5]), line("3", [0, 5], [-10, 5]), line("4", [-10, 5], [-10, -5])], ["100.00", "100.00"]], + ["partly overlapping lines → square", [line("1", [0, 0], [10, 0]), line("1b", [3, 0], [14, 0]), line("2", [10, 0], [10, 10]), line("3", [10, 10], [0, 10]), line("4", [0, 10], [0, 0])], ["100.00"]], +]; + +let failed = 0; +for (const [name, es, expected] of cases) { + const got = summary(es); + try { + assert.equal(got.length, expected.length); + expected.forEach((e, i) => e === "*" || assert.equal(got[i], e)); + console.log("ok ", name, got.join(" ")); + } catch { + failed++; + console.log("FAIL", name, "got", got.join(" "), "expected", expected.join(" ")); + } +} +process.exit(failed ? 1 : 0); diff --git a/tests/shell.test.ts b/tests/shell.test.ts new file mode 100644 index 0000000..5d7b9df --- /dev/null +++ b/tests/shell.test.ts @@ -0,0 +1,63 @@ +// Run: npx tsx tests/shell.test.ts — Shell on shapes with many faces. +import opencascade from "replicad-opencascadejs"; +import { setOC } from "replicad"; +import type { Feature, PlaneDef } from "../src/doc/types"; +import { regenerate } from "../src/kernel/engine"; +import type { BodyMesh } from "../src/kernel/protocol"; +import { arrangement, regionRef } from "../src/sketch/regions"; + +setOC(await (opencascade as unknown as () => Promise)()); + +const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] }; +const sketch = (id: string, entities: any[], p = XY): Feature => ({ id, name: id, type: "sketch", plane: p, entities }); +const extrude = (id: string, sk: string, entities: any[], d: number, mode: "new" | "auto" = "new"): Feature => ({ id, name: id, type: "extrude", source: { kind: "profile", sketch: sk, regions: arrangement(entities).regions.map(regionRef) }, distance: d, mode }); + +function volume(b: BodyMesh): number { + const p = b.positions; + const ix = b.indices; + let v = 0; + for (let i = 0; i < ix.length; i += 3) { + const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3]; + v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6; + } + return v; +} + +let failed = 0; +/** Shell the body's top-most face and check it hollowed (volume went well down) and stayed closed. */ +async function check(name: string, feats: Feature[], body: string, t = 1): Promise { + const r0 = await regenerate(feats); + const b0 = r0.bodies.find((b) => b.id === body)!; + // The biggest upward face (the lid you'd open). + const top = b0.faces.reduce((bi, f, i) => (f.normal[2] > 0.99 && (b0.faces[bi].normal[2] <= 0.99 || f.area > b0.faces[bi].area) ? i : bi), 0); + const f = b0.faces[top]; + const r = await regenerate([...feats, { id: "sh", name: "Shell", type: "shell", body, faces: [{ body, center: f.center, normal: f.normal, area: f.area }], thickness: t }]); + const b = r.bodies.find((x) => x.id === body); + const v0 = volume(b0); + const v = b ? volume(b) : NaN; + const ok = !r.errors.length && !!b && v < v0 * 0.8 && v > 0 && b.openEdges.length === 0; + if (!ok) failed++; + console.log(ok ? "ok " : "FAIL", name, `${b0.faces.length} faces, vol ${v0.toFixed(0)} → ${v.toFixed(0)}`, r.errors.map((e) => e.message).join("; ")); +} + +const box = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 30, rotation: 0 }]; +const base = [sketch("s", box), extrude("b", "s", box, 20)]; +const edgesOfBox = (z: number) => [ + { body: "b", mid: [0, -15, z], dir: [1, 0, 0], length: 40 }, { body: "b", mid: [0, 15, z], dir: [1, 0, 0], length: 40 }, + { body: "b", mid: [-20, 0, z], dir: [0, 1, 0], length: 30 }, { body: "b", mid: [20, 0, z], dir: [0, 1, 0], length: 30 }, +]; +const verticals = [[-20, -15], [20, -15], [20, 15], [-20, 15]].map(([x, y]) => ({ body: "b", mid: [x, y, 10], dir: [0, 0, 1], length: 20 })); + +await check("plain box", base, "b"); +await check("box, vertical edges rounded", [...base, { id: "f", name: "f", type: "fillet", edges: verticals as any, radius: 4 }], "b"); +await check("box, every edge rounded", [...base, { id: "f1", name: "f", type: "fillet", edges: verticals as any, radius: 4 }, { id: "f2", name: "f", type: "fillet", edges: [{ body: "b", mid: [0, -15, 0], dir: [1, 0, 0], length: 32 }] as any, radius: 2 }], "b"); +await check("box, bottom edges chamfered", [...base, { id: "c", name: "c", type: "chamfer", edges: edgesOfBox(0) as any, radius: 2 }], "b"); +// Many small faces: a box with ribs joined on top, then a 24-sided column. +const ribs = Array.from({ length: 6 }, (_, i) => ({ id: `k${i}`, kind: "rect", center: [-15 + i * 6, 0], w: 2, h: 30, rotation: 0 })); +await check("box with 6 ribs joined", [...base, sketch("s2", ribs, { ...XY, origin: [0, 0, 20] }), { ...extrude("j", "s2", ribs, 5, "auto"), target: "b" } as any], "b"); +const poly = [{ id: "p", kind: "polygon", center: [0, 0], radius: 20, sides: 24, angle: 0 }]; +await check("24-sided prism", [sketch("s", poly), extrude("b", "s", poly, 20)], "b"); +const star = [{ id: "st", kind: "polyline", closed: true, points: Array.from({ length: 20 }, (_, i) => { const a = (i / 20) * Math.PI * 2; const r = i % 2 ? 9 : 20; return [r * Math.cos(a), r * Math.sin(a)]; }) }]; +await check("10-point star prism", [sketch("s", star), extrude("b", "s", star, 15)], "b", 0.8); + +process.exit(failed ? 1 : 0); diff --git a/tests/svg.test.ts b/tests/svg.test.ts new file mode 100644 index 0000000..e19c3e8 --- /dev/null +++ b/tests/svg.test.ts @@ -0,0 +1,53 @@ +// Run: npx tsx tests/svg.test.ts — SVG → sketch curves. +import assert from "node:assert/strict"; +import { parseSVG } from "../src/io/svg"; +import { arrangement } from "../src/sketch/regions"; + +const near = (a: number, b: number, tol = 1e-6) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(b)); +const checks: [string, () => string][] = [ + ["mm units from width + viewBox; rect / circle become those shapes", () => { + const { entities, size } = parseSVG(` + `); + const kinds = entities.map((e) => e.kind).sort().join(","); + assert.equal(kinds, "circle,rect"); + const r = entities.find((e) => e.kind === "rect") as any; + const c = entities.find((e) => e.kind === "circle") as any; + // 200 user units = 100 mm → 0.5 mm each. + assert.ok(near(r.w, 40) && near(r.h, 20) && near(c.radius, 10), JSON.stringify([r, c])); + assert.equal(arrangement(entities).regions.length, 2); + return `size ${size.map((v) => v.toFixed(1)).join(" × ")} mm`; + }], + ["path with lines, a cubic, an arc and close → one closed region", () => { + const { entities } = parseSVG(` + `); + const kinds = entities.map((e) => e.kind); + assert.ok(kinds.includes("spline") && kinds.includes("arc") && kinds.includes("line"), kinds.join()); + const regions = arrangement(entities).regions; + assert.equal(regions.length, 1); + return `${entities.length} curves, area ${regions[0].area.toFixed(0)} mm²`; + }], + ["relative commands, implicit repeats, groups with transforms; y flips up", () => { + const { entities } = parseSVG(` + `); + assert.equal(entities.length, 4); + // A 10 px square → 2.646 mm; the drawing is centred on the origin. + const xs = entities.flatMap((e: any) => [e.a[0], e.b[0]]); + assert.ok(near(Math.max(...xs) - Math.min(...xs), (10 * 25.4) / 96), String(xs)); + assert.equal(arrangement(entities).regions.length, 1); + return "ok"; + }], + ["text is skipped with a clear message when nothing else is there", () => { + assert.throws(() => parseSVG(`Hi`), /converted to paths/); + return "ok"; + }], +]; +let failed = 0; +for (const [name, fn] of checks) { + try { + console.log("ok ", name, "—", fn()); + } catch (e) { + failed++; + console.log("FAIL", name, "—", e instanceof Error ? e.message : e); + } +} +process.exit(failed ? 1 : 0); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c57bd5c --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "isolatedModules": true, + "resolveJsonModule": true, + "types": ["vite/client"] + }, + "include": ["src"] +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..d1e8256 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,13 @@ +import { readFileSync } from "node:fs"; +import { defineConfig } from "vite"; + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string }; + +export default defineConfig({ + // Relative base so the build works from any static host sub-path (GitHub Pages etc.). + base: "./", + define: { __APP_VERSION__: JSON.stringify(pkg.version) }, + worker: { format: "es" }, + optimizeDeps: { exclude: ["replicad-opencascadejs"] }, + build: { target: "es2022", chunkSizeWarningLimit: 4000 }, +}); diff --git a/wrangler.jsonc b/wrangler.jsonc new file mode 100644 index 0000000..956d686 --- /dev/null +++ b/wrangler.jsonc @@ -0,0 +1,11 @@ +// Cloudflare deployment: a static site (no server code). `npm run build` +// writes the app to dist/, and `npx wrangler deploy` publishes that folder. +{ + "name": "supergeometry-app", + "compatibility_date": "2026-10-01", + "assets": { + "directory": "./dist", + // Any unknown path opens the app itself. + "not_found_handling": "single-page-application" + } +}