diff --git a/FEATURES.md b/FEATURES.md index 30747f0..d0a54e4 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -8,7 +8,7 @@ edit those columns by hand, then re-run the script. the feature-tree level) · `done` (regenerates, round-trips save/load, undo/redo, command + MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). -**Totals:** 1000 rows — not started: 841 · in progress: 131 · done: 28 · verified: 0 +**Totals:** 1000 rows — not started: 836 · in progress: 136 · done: 28 · verified: 0 ## Platform (SPEC §2–§6, §8–§9) @@ -88,11 +88,11 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.1/entities/rectangle/center` | ↳ center | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_rectangle | construction diagonal + midpoint centre | | `7.1/entities/rectangle/3-point` | ↳ 3-point | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_rectangle | DOF 5 tested | | `7.1/entities/rectangle/parallelogram` | ↳ parallelogram | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_rectangle | DOF 6 tested | -| `7.1/entities/slot` | Entities: slot | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_slot | straight and center-point slots; arc slots not started | +| `7.1/entities/slot` | Entities: slot | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_slot | all four slot types; curved slots have editable tangent/concentric geometry and desktop previews | | `7.1/entities/slot/straight` | ↳ straight | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_slot | DOF 5, exact area tested; golden 102 | | `7.1/entities/slot/center` | ↳ center | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_slot | | -| `7.1/entities/slot/arc` | ↳ arc | not started | ForgeSketch | — | — | | -| `7.1/entities/slot/3-point-arc` | ↳ 3-point arc | not started | ForgeSketch | — | — | | +| `7.1/entities/slot/arc` | ↳ arc | in progress | ForgeSketch | Tests/ForgeCommandsTests/ArcSlotTests.swift, Tests/ForgeUITests/ArcSlotWorkflowTests.swift | execute:sketch.add_arc_slot | center/start/end/width; constraints, preview, extrusion, undo and persistence; grouped slot relations pending | +| `7.1/entities/slot/3-point-arc` | ↳ 3-point arc | in progress | ForgeSketch | Tests/ForgeCommandsTests/ArcSlotTests.swift, Tests/ForgeUITests/ArcSlotWorkflowTests.swift | execute:sketch.add_arc_slot | minor/major clockwise/counter-clockwise arcs selected by through point; grouped slot relations pending | | `7.1/entities/circle` | Entities: circle | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_circle | round-trips document.save/open (golden test); not yet a feature-tree item (M2) | | `7.1/entities/circle/center` | ↳ center | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_circle | | | `7.1/entities/circle/perimeter` | ↳ perimeter | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_circle(through) | | @@ -125,14 +125,14 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.1/tools/offset/bi-directional` | ↳ bi-directional | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.offset(bidirectional) | | | `7.1/tools/offset/cap-ends` | ↳ cap ends | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.offset(cap_ends) | line caps only (arc caps NOT IMPLEMENTED) | | `7.1/tools/offset/construction` | ↳ construction | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.offset(make_base_construction) | | -| `7.1/tools/convert-entities` | Tools: convert entities | not started | ForgeSketch | — | — | | +| `7.1/tools/convert-entities` | Tools: convert entities | in progress | ForgeCommands / ForgeUI | Tests/ForgeCommandsTests/SketchConvertTests.swift, Tests/ForgeUITests/SketchPlacementWorkflowTests.swift | convert_entities | Exact detached projections of lines and parallel circles/arcs and face boundaries; fixed/editable and construction options; desktop model picking. Associative links, oblique circles, ellipses and splines remain pending. | | `7.1/tools/intersection-curve` | Tools: intersection curve | not started | ForgeSketch | — | — | | | `7.1/tools/silhouette-entities` | Tools: silhouette entities | not started | ForgeSketch | — | — | | | `7.1/tools/mirror` | Tools: mirror | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift, Tests/GoldenModelTests/Models/017_mirrored_profile_extruded.json | execute:sketch.mirror | copies with symmetric relations (circles/arcs as wholes); ellipses copied unrelated; not yet a feature-tree item (M2) | | `7.1/tools/mirror/static-dynamic` | ↳ static + dynamic | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.mirror | static mirror only; dynamic mirror (mirror while sketching) NOT IMPLEMENTED | | `7.1/tools/linear-circular-sketch-patterns` | Tools: linear/circular sketch patterns | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.pattern_linear, execute:sketch.pattern_circular | instances tied to the seed by equal/parallel; spacing/angle not yet driven by dimensions | | `7.1/tools/move-copy-rotate-scale-stretch` | Tools: move/copy/rotate/scale/stretch | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.move, execute:sketch.rotate, execute:sketch.scale | move/copy/rotate/scale done at sketch level; stretch NOT IMPLEMENTED | -| `7.1/tools/split-entities` | Tools: split entities | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.split | lines, arcs, circles, ellipses, partial ellipses; splines NOT IMPLEMENTED; not yet a feature-tree item (M2) | +| `7.1/tools/split-entities` | Tools: split entities | in progress | ForgeSketch / ForgeUI | Tests/ForgeUITests/SketchSplitWorkflowTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.split | Desktop click splitting with circle/ellipse two-point workflow, preview, cancellation and undo; lines, arcs, circles, ellipses and partial ellipses. Splines remain pending. | | `7.1/tools/jog-line` | Tools: jog line | not started | ForgeSketch | — | — | | | `7.1/tools/sketch-picture` | Tools: sketch picture | not started | ForgeSketch | — | — | | | `7.1/tools/sketch-picture/with-scale-calibration` | ↳ with scale calibration | not started | ForgeSketch | — | — | | @@ -148,7 +148,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.1/tools/3d-sketch` | Tools: 3D sketch | not started | ForgeSketch | — | — | | | `7.1/tools/3d-sketch/with-plane-switching` | ↳ with plane switching | not started | ForgeSketch | — | — | | | `7.1/tools/3d-sketch/3d-sketch-on-plane` | ↳ 3D sketch on plane | not started | ForgeSketch | — | — | | -| `7.1/tools/sketch-on-face-surface` | Tools: sketch on face/surface | not started | ForgeSketch | — | — | | +| `7.1/tools/sketch-on-face-surface` | Tools: sketch on face/surface | in progress | ForgeCommands / ForgeUI | Tests/ForgeUITests/SketchPlacementWorkflowTests.swift, Tests/ForgeCommandsTests/FeatureTreeTests.swift | execute:sketch.create, repair_reference | Planar faces with persistent attachment, guided desktop entry and camera alignment; supports upstream regeneration and attachment repair. Missing support blocks dependent features; curved-face and 3D surface sketches remain pending. | | `7.1/tools/spline-tools` | Tools: spline tools | not started | ForgeSketch | — | — | | | `7.1/tools/spline-tools/tangency-curvature-handles` | ↳ tangency/curvature handles | not started | ForgeSketch | — | — | | | `7.1/tools/spline-tools/simplify` | ↳ simplify | not started | ForgeSketch | — | — | | @@ -325,7 +325,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.2/multibody/combine` | Multibody: combine | in progress | ForgeKernel | Tests/ForgeKernelTests/KernelTests.swift, Tests/GoldenModelTests | execute:body.boolean | kernel-level; Combine feature in M2/M3 | | `7.2/multibody/combine/add-subtract-common` | ↳ add/subtract/common | in progress | ForgeKernel | Tests/ForgeKernelTests/KernelTests.swift, Tests/GoldenModelTests | execute:body.boolean | | | `7.2/multibody/split` | Multibody: split | not started | ForgeModel | — | — | | -| `7.2/multibody/move-copy-body` | Multibody: move/copy body | in progress | ForgeCommands | Tests/ForgeCommandsTests/EngineTests.swift, Tests/GoldenModelTests/005 | execute:body.transform | | +| `7.2/multibody/move-copy-body` | Multibody: move/copy body | in progress | ForgeCommands / ForgeUI | Tests/ForgeUITests/BodyPlacementWorkflowTests.swift | execute:body.transform | Desktop translation, optional rotation about origin/XYZ or stored custom axis, copy, preview and feature editing. Multiple-body transforms and mate constraints remain pending. | | `7.2/multibody/delete-keep-body` | Multibody: delete/keep body | in progress | ForgeCommands | Tests/ForgeCommandsTests/EngineTests.swift | execute:body.delete | delete only | | `7.2/multibody/insert-part` | Multibody: insert part | not started | ForgeModel | — | — | | | `7.2/multibody/insert-into-new-part` | Multibody: insert into new part | not started | ForgeModel | — | — | | @@ -736,7 +736,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | ID | Feature | Status | Module | Test | MCP tool | Notes | |---|---|---|---|---|---|---| -| `7.12/measure` | Measure | in progress | ForgeKernel | Tests/ForgeKernelTests/KernelTests.swift, Tests/ForgeCommandsTests/EngineTests.swift | measure | body↔body minimum distance only | +| `7.12/measure` | Measure | in progress | ForgeKernel | Tests/ForgeCommandsTests/MeasurementTests.swift, Tests/ForgeUITests/MeasureWorkflowTests.swift | measure | bodies/faces/edges/vertices: size, radius, coordinates, minimum distance, closest points and XYZ deltas; angles/max/normal-distance modes pending | | `7.12/measure/all-modes` | ↳ all modes | not started | ForgeModel | — | — | | | `7.12/measure/point-to-point` | ↳ point-to-point | not started | ForgeModel | — | — | | | `7.12/measure/min-max-normal` | ↳ min/max/normal | not started | ForgeModel | — | — | | @@ -1116,7 +1116,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | ID | Feature | Status | Module | Test | MCP tool | Notes | |---|---|---|---|---|---|---| -| `D/hide-show` | Hide/show bodies, components, sketches, planes (display pane) | not started | ForgeModel | — | — | | +| `D/hide-show` | Hide/show bodies, components, sketches, planes (display pane) | in progress | ForgeModel | Tests/ForgeCommandsTests/VisibilityTests.swift, Tests/ForgeUITests/BodyVisibilityWorkflowTests.swift | execute:view.set_visibility, execute:view.isolate, execute:view.show_all | saved body visibility, temporary part-body isolation, undo and hidden-body picking exclusion; components/sketches/planes display pane pending | | `D/transparency` | Per-body/component transparency | not started | ForgeModel | — | — | | | `D/section-view-part` | Section view (dynamic display section in parts/assemblies) | not started | ForgeModel | — | — | | | `D/view-selector` | View selector cube, named/saved views, previous view | not started | ForgeModel | — | — | | diff --git a/PROGRESS.md b/PROGRESS.md index 34da6b6..53d5d0e 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -1,5 +1,71 @@ # Progress +## Session 11 — 2026-09-30 — Subentity measurement, visibility and curved slots + +- `query.measure` now resolves bodies, faces, edges and vertices, including persistent + face/edge references. One selection returns applicable length, area, volume, radius + or coordinates; pairs return minimum distance, closest points and XYZ displacement. + Desktop errors remain visible and async results cannot overwrite a newer selection. + Mixed body/sketch selections are rejected instead of silently dropping the sketch. +- Added typed hide/show/isolate/exit/show-all commands, shared desktop tree/ribbon and + macOS View/context actions. Hidden bodies are excluded from rendering, picking and + fit bounds; ordinary visibility persists while isolation restores prior visibility. + Display-only transactions now have undo records. Loading ignores unknown visibility + IDs without losing suppressed feature output state. Modeling and exports include all bodies. +- Added centerpoint and three-point arc slots with editable concentric/tangent geometry, + construction centerlines, four-click desktop previews, and construction support for + all four slot types. Switching slot types clears pending clicks. Validation rejects + degenerate arcs, collapsed widths and overlapping major-arc caps atomically. +- Curved-slot constraints use existing internal-row yield metadata so normal relations + remain independent after rotation; no solver algorithm changes. Tests exercise six + noncardinal orientations, 90-degree rotation, width edits and cap alignment. +- Added an analytically derived quarter-circle-slot golden model and a real MCP + create/extrude/measure/hide/isolate/save/open/rebuild workflow. + +Validation: final local build with tests and all **350 Swift tests** pass; all **32 golden +models**, **four MCP subprocess workflows**, and **three packaging regressions** pass. +Optimized Linux desktop/CLI and Windows frontend cross-platform builds pass. Native +platform runtime checks are delegated to CI with a virtual display; no windows were +opened on the user's desktop. Matrix synchronization and whitespace checks pass. + +Remaining scope: measurement angle/max/normal modes and sketch entity measurements; +grouped Fix Slot/Equal Slots relations; individual sketch/plane/component display panes; +associative conversion, advanced extrude conditions, configurations/equations, assemblies, +drawings and the rest of the declared matrix. This delivery does not complete SolidWorks parity. + +## Session 10 — 2026-09-30 — Face sketches and everyday modeling workflows + +- Added explicit Features-tab Sketch on Face entry on all desktops, selection-aware + sketch shortcuts and rejection of unsuitable selections instead of silent Front-plane + fallback. Tests use actual face ray picking, rectangle drawing and a 125 mm³ cut. +- Added exact model-edge/face-boundary conversion into detached sketch lines, circles + and arcs; fixed/editable and construction options, undo/dry-run/save/rebuild, desktop + model picking and a direct MCP alias. Associative links, oblique circles, ellipses + and splines remain pending. +- Added desktop Split Entities, including two-point closed-curve splitting, pending + guidance, cancellation, cross-sketch guards and undo/redo. +- Added Move/Copy Bodies translation/rotation/copy pages, live preview and feature + editing, preserving stored custom axes. Exposed Up To Vertex in both extrusion + directions so an inspector roundtrip cannot change the end condition to Blind. +- Added Normal To selected faces and standard/reference planes, and plane selection. + Review fixes wire both desktop trees into selection, retain valid plane references + through rebuilds, prune suppressed planes, and make primary Sketch use the clicked + standard/reference plane. Four additional engine/UI regressions cover these paths. +- Added shared Unicode Rename dialogs and body/feature/sketch tree actions. +- Fixed sketch attachment repair and rejection of dependent modeling from lost, + suppressed or rolled-back sketch supports, preventing stale geometry regeneration. +- The source-linked audit inventories all 1,000 matrix IDs and distinguishes hidden, + partial and absent workflows. Assemblies, drawings and hundreds of other declared + capabilities still remain. See docs/research/modeling-workflow-gaps.md. + +Validation: official Swift 6.4 build with tests and all **324 Swift tests** pass. +All **31 golden models**, **3 MCP subprocess workflows** (debug and optimized CLI), +three packaging regressions and native GTK menu/name-dialog regressions pass. +Windows frontend cross-platform build and optimized Linux desktop/CLI builds pass. +The Linux screenshot smoke check renders the new ribbon entry points. Native checks +must now use Xvfb: the GTK runner refuses to fall back to the user's live desktop. +Matrix synchronization and whitespace checks pass. Native macOS/Windows checks run in CI. + ## Session 9 — 2026-09-29 — PR #3 review fixes - Imported faces now receive distinct persistent base names at intake. Kernel history diff --git a/README.md b/README.md index 1f9bf94..9f91477 100644 --- a/README.md +++ b/README.md @@ -98,3 +98,34 @@ SolidWorks functionality and acceptance criteria. This remains an early part mod A script is JSON: `{"forge_script": 1, "commands": [{"command": "...", "params": {...}}], "expect": {"bodies": [{"body": "body-1", "volume_mm3": {"value": 1000, "tol": 1e-6}}]}}`. + +Select a planar part face and choose **Features → Sketch on Face** to draw directly +on it. **Normal To** aligns the view with a selected face or reference plane even +without opening a sketch. In sketch mode, **Select Model Geometry** lets you pick +part edges or faces; **Convert Entities** copies their projected boundaries into the +sketch. These are detached copies, not associative links; lines and parallel +circles/arcs are supported. **Split Entities** uses one click for lines/arcs and two +clicks on a closed circle/ellipse. + +**Move/Copy Bodies** provides translation and optional rotation, copy, preview and +feature editing. Extrusion pages support **Up To Vertex** with model-coordinate +inputs in either direction. Body and feature tree menus include **Rename** on all +platforms. Lost sketch supports now block dependent features; use +`feature.repair_reference` to attach the sketch to a replacement planar support. + +The [complete modeling gap inventory](docs/research/modeling-workflow-gaps.md) +accounts for all 1,000 matrix entries and documents remaining work. + +**Measure** accepts one face, edge, vertex or body for its size/coordinates, or two +for minimum distance and closest points. The MCP `measure` tool uses `from` and an +optional `to`; results use millimeters. Angle and maximum-distance modes remain pending. + +Use the body tree or **Features → Visibility** to hide/show bodies, isolate a selection, +exit isolation or show all bodies. Hidden bodies are excluded from drawing and picking; +they still participate in modeling, measurements and exports. Ordinary hidden state is +saved; isolation is temporary and restores the prior visibility when exited. + +The Slot tool offers straight, centerpoint straight, centerpoint arc and three-point arc +variants. Curved slots use center/start/end/width or start/end/through/width clicks, +respect construction mode and remain editable with sketch dimensions and relations. +The typed command is `sketch.add_arc_slot`; it rejects collapsed or self-overlapping slots. diff --git a/Sources/CForgeKernel/forge_kernel.cpp b/Sources/CForgeKernel/forge_kernel.cpp index dcbdb11..3480c27 100644 --- a/Sources/CForgeKernel/forge_kernel.cpp +++ b/Sources/CForgeKernel/forge_kernel.cpp @@ -1393,6 +1393,12 @@ int32_t fk_edge_info(const FKShape *shape, int32_t edgeIndex, FKEdgeInfo *out, F BRepAdaptor_Curve curve(edge); out->curveType = curveType(curve.GetType()); out->length = GCPnts_AbscissaPoint::Length(curve); + if (curve.GetType() == GeomAbs_Circle) { + const gp_Circ circle = curve.Circle(); + put3(out->circleCenter, circle.Location().XYZ()); + put3(out->circleAxis, circle.Axis().Direction().XYZ()); + out->circleRadius = circle.Radius(); + } put3(out->midpoint, curve.Value(0.5 * (curve.FirstParameter() + curve.LastParameter())).XYZ()); } else { out->curveType = FK_CURVE_OTHER; @@ -1434,6 +1440,40 @@ int32_t fk_edge_faces(const FKShape *shape, int32_t edgeIndex, int32_t *outFaces FK_END(-1) } +FKShape *fk_subshape(const FKShape *shape, int32_t kind, int32_t index, FKError *err) { + clearError(err); + if (!hasShape(shape, err)) return nullptr; + if (kind < 0 || kind > 2 || index < 0) { + setError(err, FK_ERR_INVALID_ARGUMENT, "invalid subshape kind or index"); + return nullptr; + } + FK_BEGIN + const TopAbs_ShapeEnum types[] = {TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX}; + TopTools_IndexedMapOfShape map; + TopExp::MapShapes(shape->shape, types[kind], map); + if (index >= map.Extent()) { + setError(err, FK_ERR_OUT_OF_RANGE, "subshape index out of range"); + return nullptr; + } + return wrap(map(index + 1)); + FK_END(nullptr) +} + +int32_t fk_vertex_position(const FKShape *shape, int32_t index, double outPoint[3], FKError *err) { + clearError(err); + if (!hasShape(shape, err) || !outPoint) return FK_ERR_INVALID_ARGUMENT; + FK_BEGIN + TopTools_IndexedMapOfShape vertices; + TopExp::MapShapes(shape->shape, TopAbs_VERTEX, vertices); + if (index < 0 || index >= vertices.Extent()) { + setError(err, FK_ERR_OUT_OF_RANGE, "vertex index out of range"); + return FK_ERR_OUT_OF_RANGE; + } + put3(outPoint, BRep_Tool::Pnt(TopoDS::Vertex(vertices(index + 1))).XYZ()); + return FK_OK; + FK_END(FK_ERR_KERNEL_EXCEPTION) +} + int32_t fk_distance(const FKShape *a, const FKShape *b, double *outDistance, double outPointA[3], double outPointB[3], FKError *err) { clearError(err); if (!hasShape(a, err) || !hasShape(b, err) || !outDistance) return FK_ERR_INVALID_ARGUMENT; diff --git a/Sources/CForgeKernel/include/forge_kernel.h b/Sources/CForgeKernel/include/forge_kernel.h index 58b61b1..de96db3 100644 --- a/Sources/CForgeKernel/include/forge_kernel.h +++ b/Sources/CForgeKernel/include/forge_kernel.h @@ -124,6 +124,10 @@ typedef struct FKEdgeInfo { double midpoint[3]; int32_t isDegenerate; int32_t adjacentFaces; + /* Analytic circle data, valid only for FK_CURVE_CIRCLE. */ + double circleCenter[3]; + double circleAxis[3]; + double circleRadius; } FKEdgeInfo; /* ---- library ---------------------------------------------------------- */ @@ -261,6 +265,11 @@ int32_t fk_face_info(const FKShape *shape, int32_t faceIndex, FKFaceInfo *out, F int32_t fk_edge_info(const FKShape *shape, int32_t edgeIndex, FKEdgeInfo *out, FKError *err); /* Indices of the faces adjacent to an edge (up to maxOut); returns count or -1. */ int32_t fk_edge_faces(const FKShape *shape, int32_t edgeIndex, int32_t *outFaces, int32_t maxOut, FKError *err); +/* Extract one face (kind 0), edge (1), or vertex (2), with the same indexed-map order + as face/edge info. Returned immutable shape handle is owned by the caller. */ +FKShape *fk_subshape(const FKShape *shape, int32_t kind, int32_t index, FKError *err); +int32_t fk_vertex_position(const FKShape *shape, int32_t index, double outPoint[3], FKError *err); + /* Minimum distance between two shapes; points receive the closest pair. */ int32_t fk_distance(const FKShape *a, const FKShape *b, double *outDistance, double outPointA[3], double outPointB[3], FKError *err); diff --git a/Sources/CForgeWin/app.cpp b/Sources/CForgeWin/app.cpp index 36f8a69..7b9dd34 100644 --- a/Sources/CForgeWin/app.cpp +++ b/Sources/CForgeWin/app.cpp @@ -1562,6 +1562,67 @@ static char *dup(const std::wstring &w) { return out; } +struct NameDialogState { + std::wstring title; + std::wstring name; +}; + +static INT_PTR CALLBACK nameDialogProc(HWND dialog, UINT message, WPARAM wp, LPARAM lp) { + if (message == WM_INITDIALOG) { + auto *state = reinterpret_cast(lp); + SetWindowLongPtrW(dialog, DWLP_USER, lp); + SetWindowTextW(dialog, state->title.c_str()); + auto control = [dialog](const wchar_t *kind, const wchar_t *text, DWORD style, + int id, int x, int y, int w, int h) { + RECT r = {x, y, x + w, y + h}; + MapDialogRect(dialog, &r); + HWND child = CreateWindowExW(kind == std::wstring(L"EDIT") ? WS_EX_CLIENTEDGE : 0, + kind, text, WS_CHILD | WS_VISIBLE | style, r.left, r.top, + r.right - r.left, r.bottom - r.top, dialog, reinterpret_cast(static_cast(id)), + GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); + return child; + }; + control(L"STATIC", L"Name:", 0, -1, 10, 8, 210, 12); + HWND edit = control(L"EDIT", state->name.c_str(), WS_TABSTOP | ES_AUTOHSCROLL, 100, 10, 22, 220, 15); + control(L"BUTTON", L"Rename", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 110, 48, 56, 16); + control(L"BUTTON", L"Cancel", WS_TABSTOP | BS_PUSHBUTTON, IDCANCEL, 174, 48, 56, 16); + SendMessageW(dialog, DM_SETDEFID, IDOK, 0); + SetFocus(edit); + SendMessageW(edit, EM_SETSEL, 0, -1); + return FALSE; // focus was explicitly assigned to the name field + } + if (message == WM_COMMAND && (LOWORD(wp) == IDOK || LOWORD(wp) == IDCANCEL)) { + if (LOWORD(wp) == IDOK) { + auto *state = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); + state->name = windowText(GetDlgItem(dialog, 100)); + } + EndDialog(dialog, LOWORD(wp)); + return TRUE; + } + if (message == WM_CLOSE) { + EndDialog(dialog, IDCANCEL); + return TRUE; + } + return FALSE; +} + +extern "C" char *fw_name_dialog(fw_app *a, const char *title, const char *current_name) { + // A zero-control template; controls are created in WM_INITDIALOG. The three + // terminating WORDs are the variable menu, class and title template fields. + struct alignas(DWORD) NameTemplate { + DLGTEMPLATE dialog; + WORD menu, windowClass, title; + } templ = {}; + templ.dialog.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; + templ.dialog.cx = 240; + templ.dialog.cy = 74; + NameDialogState state{fw_widen(title), fw_widen(current_name)}; + INT_PTR result = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &templ.dialog, a->hwnd, + nameDialogProc, reinterpret_cast(&state)); + return result == IDOK ? dup(state.name) : nullptr; +} + extern "C" char *fw_save_dialog(fw_app *a, const char *suggested_name) { wchar_t file[MAX_PATH] = {}; lstrcpynW(file, fw_widen(suggested_name).c_str(), MAX_PATH); diff --git a/Sources/CForgeWin/gtk/gtk_shell.c b/Sources/CForgeWin/gtk/gtk_shell.c index d134306..81571bc 100644 --- a/Sources/CForgeWin/gtk/gtk_shell.c +++ b/Sources/CForgeWin/gtk/gtk_shell.c @@ -1399,6 +1399,39 @@ int fw_confirm(fw_app *a, const char *title, const char *message, const char *ye return r.button == 1; } +static void onNameResponse(GtkDialog *dialog, int response, gpointer data) { + (void)dialog; + DialogResult *r = data; + r->button = response; + r->done = 1; +} + +char *fw_name_dialog(fw_app *a, const char *title, const char *current_name) { + GtkWidget *dialog = gtk_dialog_new_with_buttons(title ? title : "Rename", GTK_WINDOW(a->window), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + "Cancel", GTK_RESPONSE_CANCEL, "Rename", GTK_RESPONSE_ACCEPT, NULL); + GtkWidget *entry = gtk_entry_new(); + gtk_editable_set_text(GTK_EDITABLE(entry), current_name ? current_name : ""); + gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE); + gtk_widget_set_margin_start(entry, 16); + gtk_widget_set_margin_end(entry, 16); + gtk_widget_set_margin_top(entry, 16); + gtk_widget_set_margin_bottom(entry, 16); + gtk_widget_set_size_request(entry, 300, -1); + gtk_accessible_update_property(GTK_ACCESSIBLE(entry), GTK_ACCESSIBLE_PROPERTY_LABEL, "Name", -1); + gtk_box_append(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), entry); + gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); + DialogResult r = {0, GTK_RESPONSE_CANCEL, NULL}; + g_signal_connect(dialog, "response", G_CALLBACK(onNameResponse), &r); + gtk_window_present(GTK_WINDOW(dialog)); + gtk_widget_grab_focus(entry); + gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1); + wait(&r); + char *name = r.button == GTK_RESPONSE_ACCEPT ? strdup(gtk_editable_get_text(GTK_EDITABLE(entry))) : NULL; + gtk_window_destroy(GTK_WINDOW(dialog)); + return name; +} + void fw_message(fw_app *a, const char *title, const char *message, int error) { (void)error; GtkAlertDialog *d = gtk_alert_dialog_new("%s", title ? title : ""); diff --git a/Sources/CForgeWin/headless/headless.c b/Sources/CForgeWin/headless/headless.c index 97aa59b..36c4a19 100644 --- a/Sources/CForgeWin/headless/headless.c +++ b/Sources/CForgeWin/headless/headless.c @@ -68,3 +68,5 @@ uint8_t *fw_capture(fw_app *p0, int *width, int *height) { return NULL; } void fw_app_quit(fw_app *p0) { } char *fw_import_step_dialog(fw_app *a) { (void)a; return NULL; } + +char *fw_name_dialog(fw_app *a, const char *title, const char *current_name) { (void)a; (void)title; (void)current_name; return NULL; } diff --git a/Sources/CForgeWin/include/CForgeWin.h b/Sources/CForgeWin/include/CForgeWin.h index 9cd9cb0..50eb857 100644 --- a/Sources/CForgeWin/include/CForgeWin.h +++ b/Sources/CForgeWin/include/CForgeWin.h @@ -161,6 +161,8 @@ void fw_edit_hide(fw_app *); // MARK: dialogs (returned strings are freed with fw_free) int fw_confirm(fw_app *, const char *title, const char *message, const char *yes, const char *no); +// UTF-8 name, allocated with malloc; caller uses fw_free. NULL on cancel. +char *fw_name_dialog(fw_app *, const char *title, const char *current_name); char *fw_save_dialog(fw_app *, const char *suggested_name); /// A .forgepart document (a folder). char *fw_open_dialog(fw_app *); diff --git a/Sources/ForgeApp/FeatureTree.swift b/Sources/ForgeApp/FeatureTree.swift index d338f33..277cd87 100644 --- a/Sources/ForgeApp/FeatureTree.swift +++ b/Sources/ForgeApp/FeatureTree.swift @@ -52,12 +52,19 @@ struct FeatureTreeView: View { @ViewBuilder private var rows: some View { if !model.bodies.isEmpty { TreeRow(icon: .folder, title: "Solid Bodies (\(model.bodies.count))", depth: 1, disclosure: bodiesOpen) { bodiesOpen.toggle() } + .contextMenu { + Button("Show All Bodies") { Task { await model.showAllBodies() } } + if model.isIsolatingBodies { Button("Exit Isolation") { Task { await model.exitBodyIsolation() } } } + } if bodiesOpen { ForEach(model.bodies.filter { matches($0.name) }, id: \.id) { b in - TreeRow(icon: .part, title: b.name, depth: 2, selected: model.selection.contains(b.id)) { + TreeRow(icon: model.hiddenBodyIDs.contains(b.id) ? .hideShow : .part, title: b.name + (model.hiddenBodyIDs.contains(b.id) ? " (Hidden)" : ""), depth: 2, selected: model.selection.contains(b.id), muted: model.hiddenBodyIDs.contains(b.id)) { Task { await model.select(b.id, extend: !NSEvent.modifierFlags.intersection([.shift, .command, .control]).isEmpty) } } .contextMenu { + Button(model.hiddenBodyIDs.contains(b.id) ? "Show Body" : "Hide Body") { Task { await model.setBodiesVisible([b.id], model.hiddenBodyIDs.contains(b.id)) } } + Button("Isolate Body") { Task { await model.isolateBodies([b.id]) } } + Button("Rename…") { Task { await model.renameBody(b.id) } } Button("Mass Properties") { Task { await model.select(b.id, extend: false) @@ -76,8 +83,12 @@ struct FeatureTreeView: View { } } ForEach(StandardPlane.allCases.filter { matches($0.rawValue + " plane") }, id: \.self) { p in - TreeRow(icon: .plane, title: "\(p.rawValue.capitalized) Plane", depth: 1, iconTint: Theme.text3, - doubleAction: { Task { await model.newSketch(on: p) } }) {} + TreeRow(icon: .plane, title: "\(p.rawValue.capitalized) Plane", depth: 1, + selected: model.selection.contains("plane-" + p.rawValue), iconTint: Theme.text3, + doubleAction: { Task { await model.newSketch(on: p) } }) { + let extend = !NSEvent.modifierFlags.intersection([.shift, .command, .control]).isEmpty + Task { await model.select("plane-" + p.rawValue, extend: extend) } + } .contextMenu { Button("Sketch on \(p.rawValue.capitalized) Plane") { Task { await model.newSketch(on: p) } } } @@ -130,8 +141,6 @@ private struct FeatureNode: View { let feature: FeatureRow let rolledBack: Bool @State private var open = false - @State private var renaming = false - @State private var newName = "" var body: some View { let sketch = feature.isSketch ? nil : feature.sketchID.flatMap { id in model.sketches.first { $0.id == id } } @@ -148,14 +157,6 @@ private struct FeatureNode: View { } .contextMenu { menu } .help(feature.error.map { "\(feature.name): \($0)" } ?? (feature.command == "plane.create" ? "\(feature.name) — double-click to sketch on it" : "\(feature.name) — double-click to edit")) - .popover(isPresented: $renaming) { - HStack { - TextField("Name", text: $newName).textFieldStyle(.roundedBorder).frame(width: 180) - .onSubmit { rename() } - Button("Rename") { rename() }.buttonStyle(PanelButtonStyle(prominent: true)) - } - .padding(10) - } if let sketch, open || sketch.id == model.activeSketch { let row = model.features.first { $0.isSketch && $0.sketchID == sketch.id } FeatureChild(sketch: sketch, feature: row) @@ -196,8 +197,8 @@ private struct FeatureNode: View { } if feature.isSketch, let s = feature.sketchID { Task { await model.select(s, extend: !NSEvent.modifierFlags.intersection([.shift, .command, .control]).isEmpty) } - } else if !feature.createdBodies.isEmpty && feature.command != "plane.create" { - Task { await model.select(feature.createdBodies) } + } else { + model.treeSelect(feature, extend: !NSEvent.modifierFlags.intersection([.shift, .command, .control]).isEmpty) } } @@ -211,12 +212,6 @@ private struct FeatureNode: View { } } - private func rename() { - renaming = false - let n = newName - Task { await model.run("feature.rename", ["feature": .string(feature.id), "name": .string(n)]) } - } - @ViewBuilder private var menu: some View { if feature.command == "plane.create", let plane = feature.createdBodies.first { Button("Sketch") { Task { await model.newSketch(onPlaneOrFace: plane) } } @@ -237,10 +232,7 @@ private struct FeatureNode: View { if index + 1 < model.features.count { Button("Move Down") { Task { await model.moveFeature(feature.id, by: 1) } } } } Button("Rollback") { Task { await model.run("feature.rollback", ["before": .string(feature.id)]) } } - Button("Rename") { - newName = feature.name - renaming = true - } + Button("Rename…") { Task { await model.renameFeature(feature.id) } } if let e = feature.error { Divider() Button("What's Wrong?") { model.lastError = ForgeError(.referenceLost, "\(feature.name): \(e)") } @@ -265,6 +257,7 @@ private struct FeatureChild: View { .contextMenu { Button("Edit Sketch") { Task { await model.editSketch(sketch.id) } } if let feature { + Button("Rename…") { Task { await model.renameFeature(feature.id) } } Button("Delete", role: .destructive) { Task { await model.run("feature.delete", ["feature": .string(feature.id)]) } } } } diff --git a/Sources/ForgeApp/ForgeApp.swift b/Sources/ForgeApp/ForgeApp.swift index c366af8..c86d98a 100644 --- a/Sources/ForgeApp/ForgeApp.swift +++ b/Sources/ForgeApp/ForgeApp.swift @@ -68,11 +68,17 @@ struct ForgeApp: App { Button("Isometric") { model.setOrientation(.isometric) }.keyboardShortcut("7", modifiers: .control) Button("Dimetric") { model.setOrientation(.dimetric) } Button("Trimetric") { model.setOrientation(.trimetric) } - Button("Normal To") { model.normalToSketch() }.keyboardShortcut("8", modifiers: .control).disabled(model.activeSketch == nil) + Button("Normal To") { model.normalToSketch() }.keyboardShortcut("8", modifiers: .control).disabled(!model.canNormalTo) Divider() Button("Zoom to Fit (F)") { model.zoomToFit() } Button("Previous View") { model.previousView() } Divider() + Button("Hide Selected Bodies") { Task { await model.setBodiesVisible(model.selectedBodies, false) } }.disabled(model.selectedBodies.isEmpty) + Button("Show Selected Bodies") { Task { await model.setBodiesVisible(model.selectedBodies, true) } }.disabled(model.selectedBodies.isEmpty) + Button("Isolate Selected Bodies") { Task { await model.isolateBodies(model.selectedBodies) } }.disabled(model.selectedBodies.isEmpty) + Button("Exit Isolation") { Task { await model.exitBodyIsolation() } }.disabled(!model.isIsolatingBodies) + Button("Show All Bodies") { Task { await model.showAllBodies() } } + Divider() Toggle("Perspective", isOn: Binding(get: { model.display.perspective }, set: { model.setPerspective($0) })) Toggle("Planes", isOn: Binding(get: { model.display.planes }, set: { model.display.planes = $0; Task { await model.refresh() } })) Toggle("Sketch Relations", isOn: Binding(get: { model.display.relations }, set: { model.display.relations = $0 })) @@ -372,6 +378,20 @@ final class MacPlatform: PlatformServices { return alert.runModal() == .alertFirstButtonReturn } + func requestName(_ title: String, currentName: String) -> String? { + let alert = NSAlert() + alert.messageText = title + alert.addButton(withTitle: "Rename") + alert.addButton(withTitle: "Cancel") + let field = NSTextField(string: currentName) + field.frame = NSRect(x: 0, y: 0, width: 300, height: 24) + field.setAccessibilityLabel("Name") + alert.accessoryView = field + alert.window.initialFirstResponder = field + field.selectText(nil) + return alert.runModal() == .alertFirstButtonReturn ? field.stringValue : nil + } + func chooseSavePath(suggestedName name: String) -> String? { let panel = NSSavePanel() panel.nameFieldStringValue = name diff --git a/Sources/ForgeApp/PMPages.swift b/Sources/ForgeApp/PMPages.swift index 8b14295..8f456a8 100644 --- a/Sources/ForgeApp/PMPages.swift +++ b/Sources/ForgeApp/PMPages.swift @@ -46,7 +46,7 @@ struct OperationPage: View { case .chamfer where model.filletItems.isEmpty: "Select edges or faces to chamfer. Each click adds an item; click it again to remove it." case .shell: "Select the faces to remove. With none, the body becomes a closed hollow shell." case .draft: model.form.activeBox == "neutral" ? "Select the neutral plane: a planar face." : "Select the faces to draft (⇧-click adds)." - case .measure where model.selection.count != 2: "Select two entities to measure between." + case .measure where !(1...2).contains(model.selection.count): "Select one or two entities to measure." case .sketchMirror where model.form.mirrorAxis.isEmpty: "Select the entities to mirror and a line (ideally a centerline) to mirror about." case .sketchOffset, .sketchLinearPattern, .sketchCircularPattern, .sketchMove, .sketchRotate, .sketchScale: model.sketchSelection.isEmpty ? "Select the sketch entities in the view (⇧-click adds)." : nil @@ -74,7 +74,7 @@ struct OperationPage: View { .help("Reverse Direction") .disabled(model.form.endCondition == .midPlane || model.form.endCondition == .throughAllBoth) Picker("End condition", selection: $model.form.endCondition) { - ForEach(EndConditionUI.allCases.filter { op == .cutExtrude || !model.bodies.isEmpty || $0.needsDepth }, id: \.self) { + ForEach(EndConditionUI.allCases.filter { op == .cutExtrude || !model.bodies.isEmpty || $0.needsDepth || $0 == .upToVertex }, id: \.self) { Text($0.rawValue).tag($0) } } @@ -84,6 +84,11 @@ struct OperationPage: View { if model.form.endCondition.needsDepth { PMField(label: "Depth", text: $model.form.depth, unit: "mm", icon: .smartDimension, help: "mm, or with units: 0.5 in") } + if model.form.endCondition == .upToVertex { + PMField(label: "Vertex X", text: $model.form.vertexX, unit: "mm") + PMField(label: "Vertex Y", text: $model.form.vertexY, unit: "mm") + PMField(label: "Vertex Z", text: $model.form.vertexZ, unit: "mm") + } if op == .extrude && !model.bodies.isEmpty && model.editingFeatureCreatesBody != true { PMCheckbox(label: "Merge result", isOn: $model.form.merge) } @@ -101,10 +106,15 @@ struct OperationPage: View { if model.form.endCondition != .midPlane && model.form.endCondition != .throughAllBoth { PMCheckGroup(title: "Direction 2", isOn: $model.form.direction2) { Picker("End condition", selection: $model.form.endCondition2) { - ForEach([EndConditionUI.blind, .throughAll].filter { $0 == .blind || !model.bodies.isEmpty }, id: \.self) { Text($0.rawValue).tag($0) } + ForEach([EndConditionUI.blind, .throughAll, .upToVertex].filter { $0 != .throughAll || !model.bodies.isEmpty }, id: \.self) { Text($0.rawValue).tag($0) } } .labelsHidden() .pickerStyle(.menu) + if model.form.endCondition2 == .upToVertex { + PMField(label: "Vertex X", text: $model.form.vertex2X, unit: "mm") + PMField(label: "Vertex Y", text: $model.form.vertex2Y, unit: "mm") + PMField(label: "Vertex Z", text: $model.form.vertex2Z, unit: "mm") + } if model.form.endCondition2 == .blind { PMField(label: "Depth", text: $model.form.depth2, unit: "mm", icon: .smartDimension) } @@ -397,6 +407,26 @@ struct OperationPage: View { model.form.draftFaces = faces.filter { $0 != model.form.draftNeutral } } } + case .moveBody: + PMSection("Body") { + PMPicker(label: "Body", selection: $model.form.target, icon: .part) { ForEach(model.bodies, id: \.id) { Text($0.name).tag($0.id) } } + PMCheckbox(label: "Create copy", isOn: $model.form.bodyCopy) + } + PMSection("Translation") { + PMField(label: "X", text: $model.form.bodyDX, unit: "mm") + PMField(label: "Y", text: $model.form.bodyDY, unit: "mm") + PMField(label: "Z", text: $model.form.bodyDZ, unit: "mm") + } + PMCheckGroup(title: "Rotation", isOn: $model.form.bodyRotation) { + PMPicker(label: "Axis", selection: $model.form.bodyAxis) { + Text("X").tag("x"); Text("Y").tag("y"); Text("Z").tag("z") + if model.form.bodyAxis == "custom" { Text("Stored custom axis").tag("custom") } + } + PMField(label: "Angle", text: $model.form.bodyAngle, unit: "°") + PMField(label: "Origin X", text: $model.form.bodyOriginX, unit: "mm") + PMField(label: "Origin Y", text: $model.form.bodyOriginY, unit: "mm") + PMField(label: "Origin Z", text: $model.form.bodyOriginZ, unit: "mm") + } case .combine: PMSection("Operation Type") { PMTypeList(options: [(value: "fuse", icon: .combine, title: "Add"), (value: "cut", icon: .cutExtrude, title: "Subtract"), @@ -454,7 +484,7 @@ struct OperationPage: View { if let r = model.form.result { KeyValueList(value: r) } else { - Text(op == .measure ? "Select two faces, edges, vertices or bodies." : "Select a body.") + Text(op == .measure ? "Select one entity for its size, or two for their minimum distance." : "Select a body.") .font(.system(size: 12)).foregroundStyle(Theme.text2) } } @@ -593,9 +623,11 @@ struct SketchToolPage: View { PMSection("Options") { PMCheckbox(label: "For construction", isOn: $model.sketchState.forConstruction) } case .slot: PMSection("Slot Types") { - PMTypeList(options: [(value: SlotType.straight, icon: .slot, title: "Straight Slot"), (value: .center, icon: .slot, title: "Centerpoint Straight Slot")], - selection: $model.sketchState.slotType) + PMTypeList(options: [(value: SlotType.straight, icon: .slot, title: "Straight Slot"), (value: .center, icon: .slot, title: "Centerpoint Straight Slot"), + (value: .arc, icon: .slot, title: "Centerpoint Arc Slot"), (value: .threePointArc, icon: .slot, title: "3 Point Arc Slot")], + selection: Binding(get: { model.sketchState.slotType }, set: { model.chooseSlotType($0) })) } + PMSection("Options") { PMCheckbox(label: "For construction", isOn: $model.sketchState.forConstruction) } case .polygon: PMSection("Parameters") { PMField(label: "Sides", text: Binding(get: { String(model.sketchState.polygonSides) }, @@ -635,7 +667,7 @@ struct SketchToolPage: View { PMTypeList(options: [(value: TrimMode.power, icon: .trim, title: "Power trim"), (value: .closest, icon: .trim, title: "Trim to closest")], selection: $model.sketchState.trimMode) } - case .point, .extend, .dimension: + case .point, .extend, .split, .dimension: EmptyView() } } diff --git a/Sources/ForgeApp/Ribbon.swift b/Sources/ForgeApp/Ribbon.swift index ffbfbc0..ad11109 100644 --- a/Sources/ForgeApp/Ribbon.swift +++ b/Sources/ForgeApp/Ribbon.swift @@ -40,6 +40,13 @@ private struct FeaturesTab: View { var body: some View { let hasSketch = !model.sketches.isEmpty let hasBody = !model.bodies.isEmpty + RibbonGroup("Sketch") { + RibbonLarge(.sketch, model.sketchStartTitle, enabled: model.activeSketch == nil, + help: "Start a sketch on the selected planar face; use the Sketch tab to choose another plane") { + Task { await model.startSketchFromSelection() } + } + } + RibbonSeparator() RibbonGroup("Boss / Base") { RibbonLarge(.extrude, "Extruded\nBoss/Base", active: model.operation == .extrude, enabled: hasSketch, help: "Extrude a closed sketch profile into a new body") { model.begin(.extrude) } @@ -77,6 +84,7 @@ private struct FeaturesTab: View { } RibbonStack { RibbonSmall(.combine, "Combine", active: model.operation == .combine, enabled: model.bodies.count >= 2) { model.begin(.combine) } + RibbonSmall(.move, "Move/Copy Bodies", active: model.operation == .moveBody, enabled: hasBody) { model.begin(.moveBody) } RibbonSmall(.trash, "Delete Body", enabled: !model.selectedBodies.isEmpty) { let bodies = model.selectedBodies Task { for b in bodies { await model.run("body.delete", ["body": .string(b)]) } } @@ -102,6 +110,18 @@ private struct FeaturesTab: View { } } RibbonSeparator() + RibbonGroup("Visibility") { + RibbonStack { + RibbonSmall(.hideShow, "Hide Bodies", enabled: !model.selectedBodies.isEmpty) { Task { await model.setBodiesVisible(model.selectedBodies, false) } } + RibbonSmall(.hideShow, "Show Bodies", enabled: !model.selectedBodies.isEmpty) { Task { await model.setBodiesVisible(model.selectedBodies, true) } } + RibbonSmall(.part, "Isolate Bodies", active: model.isIsolatingBodies, enabled: !model.selectedBodies.isEmpty) { Task { await model.isolateBodies(model.selectedBodies) } } + } + RibbonStack { + RibbonSmall(.part, "Exit Isolation", enabled: model.isIsolatingBodies) { Task { await model.exitBodyIsolation() } } + RibbonSmall(.hideShow, "Show All Bodies", enabled: !model.hiddenBodyIDs.isEmpty || model.isIsolatingBodies) { Task { await model.showAllBodies() } } + } + } + RibbonSeparator() RibbonGroup("Primitives") { RibbonStack { ForEach([Primitive.box, .cylinder, .sphere]) { p in @@ -195,6 +215,15 @@ private struct SketchTab: View { } RibbonSeparator() RibbonGroup("Tools") { + RibbonStack { + RibbonSmall(.sketch, "Select Model Geometry", enabled: editing, help: "Stop drawing to select body edges or faces for Convert Entities") { model.selectModelGeometry() } + RibbonSmall(.trim, "Split Entities", active: st.tool == .split, enabled: editing, + help: "Split lines and arcs with one click; circles and ellipses with two") { tool(.split) } + RibbonSmall(.sketch, "Convert Entities", enabled: editing && !model.selectedModelGeometry.isEmpty, + help: "Project selected edges or face boundaries as fixed copies; copies do not follow later model edits") { + Task { await model.convertSelectedModelGeometry() } + } + } RibbonFlyout(icon: st.tool == .chamfer ? .sketchChamfer : .sketchFillet, title: "Sketch\nFillet", active: st.tool == .fillet || st.tool == .chamfer, enabled: editing, action: { tool(.fillet) }) { Button("Sketch Fillet") { model.chooseTool(.fillet) } diff --git a/Sources/ForgeApp/ViewportOverlays.swift b/Sources/ForgeApp/ViewportOverlays.swift index 40367fe..c1bce29 100644 --- a/Sources/ForgeApp/ViewportOverlays.swift +++ b/Sources/ForgeApp/ViewportOverlays.swift @@ -431,8 +431,13 @@ struct ContextToolbar: View { item(.fillet, "Fillet") { model.begin(.fillet) } item(.chamfer, "Chamfer") { model.begin(.chamfer) } } - if model.selection.count == 2 { item(.measure, "Measure") { model.begin(.measure) } } - if !model.selectedBodies.isEmpty { item(.massProps, "Mass Properties") { model.begin(.massProperties) } } + if (1...2).contains(model.selection.count) { item(.measure, "Measure") { model.begin(.measure) } } + if !model.selectedBodies.isEmpty { + item(.hideShow, "Hide Bodies") { Task { await model.setBodiesVisible(model.selectedBodies, false) } } + item(.part, "Isolate Bodies") { Task { await model.isolateBodies(model.selectedBodies) } } + item(.massProps, "Mass Properties") { model.begin(.massProperties) } + } + if model.isIsolatingBodies { item(.part, "Exit Isolation") { Task { await model.exitBodyIsolation() } } } item(.zoomFit, "Zoom to Fit") { model.zoomToFit() } } } @@ -506,12 +511,12 @@ struct ShortcutBar: View { private var entries: [Entry] { if model.activeSketch != nil { - let tools: [SketchTool] = [.line, .rectangle, .circle, .arc, .slot, .polygon, .spline, .ellipse, .point, .fillet, .chamfer, .trim, .extend, .dimension] + let tools: [SketchTool] = [.line, .rectangle, .circle, .arc, .slot, .polygon, .spline, .ellipse, .point, .fillet, .chamfer, .trim, .extend, .split, .dimension] return tools.map { t in Entry(icon: t.icon, title: t.title) { model.chooseTool(t) } } + [Entry(icon: .exitSketch, title: "Exit Sketch") { Task { await model.exitSketch() } }] } var out: [Entry] = [ - Entry(icon: .sketch, title: "Sketch on Front Plane") { Task { await model.newSketch(on: .front) } }, + Entry(icon: .sketch, title: model.sketchStartTitle) { Task { await model.startSketchFromSelection() } }, Entry(icon: .extrude, title: "Extruded Boss/Base") { model.begin(.extrude) }, Entry(icon: .revolve, title: "Revolved Boss/Base") { model.begin(.revolve) }, Entry(icon: .cutExtrude, title: "Extruded Cut") { model.begin(.cutExtrude) }, diff --git a/Sources/ForgeCommands/Commands/ArcSlotCommands.swift b/Sources/ForgeCommands/Commands/ArcSlotCommands.swift new file mode 100644 index 0000000..49af51f --- /dev/null +++ b/Sources/ForgeCommands/Commands/ArcSlotCommands.swift @@ -0,0 +1,140 @@ +import ForgeCore +import ForgeSketch +import Foundation + +/// A curved slot is the constant-width offset of an open circular centreline, +/// closed by semicircular ends. Both construction modes create the same editable geometry. +public enum SketchAddArcSlot: Command { + public enum Mode: String, Codable, Sendable, CaseIterable, SchemaEnum { + case center, threePoint = "three_point" + } + + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var sketch: String? + public var mode: Mode? + public var center: Point2? + public var start: Point2 + public var end: Point2 + public var through: Point2? + public var width: Length + public var clockwise: Bool? + public var construction: Bool? + + public static let fieldDocs: [String: FieldDoc] = [ + "sketch": sketchParamDoc, + "mode": FieldDoc("center: centre plus two centreline endpoints; three_point: endpoints plus a point traversed by the centreline", default: "center"), + "center": "Centre of the circular centreline (center mode only)", + "start": "Start of the slot centreline, at the first semicircular end centre", + "end": "End of the slot centreline, at the second semicircular end centre", + "through": "Point on the circular centreline between start and end (three_point mode only); selects the minor or major arc", + "width": "Full slot width, strictly smaller than the centreline diameter", + "clockwise": FieldDoc("Traverse from start to end clockwise (center mode only)", default: false), + "construction": constructionDoc, + ] + + public func validate() throws { + try requirePositive(width, "width") + switch mode ?? .center { + case .center: + guard center != nil, through == nil else { + throw ForgeError(.invalidParams, "center mode needs center, start and end; through is only valid in three_point mode") + } + case .threePoint: + guard through != nil, center == nil, clockwise == nil else { + throw ForgeError(.invalidParams, "three_point mode needs start, end and through; do not also give center or clockwise") + } + } + } + } + + public typealias Output = SketchEditResult + public static let name = "sketch.add_arc_slot" + public static let summary = "Add a centerpoint or three-point arc slot with concentric sides and tangent rounded ends" + public static let discussion = "Creates four boundary arcs and one construction centreline arc with six remaining degrees of freedom. Centre-mode endpoints must have the same radius; clockwise selects traversal. Three-point mode follows the arc through the supplied third point. Rejects coincident/collinear points, collapsed inner radii and overlapping end caps. Curves remain editable using ordinary sketch dimensions and relations; no grouped Fix Slot/Equal Slots relation is implied." + public static let category = CommandCategory.sketch + public static let undo = UndoBehavior.undoable + public static let errors: [ErrorCode] = [.invalidParams, .preconditionFailed, .sketchConflict, .sketchRedundant, .solverFailed] + public static let examples: [JSONValue] = [ + ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4], + ["mode": "three_point", "start": [20, 0], "end": [-20, 0], "through": [0, 20], "width": "4 mm"], + ] + + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { + var (doc, sketch) = try ctx.sketchForEdit(p.sketch) + let center: (Double, Double) + let clockwise: Bool + switch p.mode ?? .center { + case .center: + guard let c = p.center else { throw ForgeError(.invalidParams, "center is required") } + center = c.tuple + clockwise = p.clockwise ?? false + case .threePoint: + guard let through = p.through else { throw ForgeError(.invalidParams, "through is required") } + (center, _) = try Sketch.circumcircle(p.start.tuple, through.tuple, p.end.tuple) + let cross = (through.u - p.start.u) * (p.end.v - p.start.v) - (through.v - p.start.v) * (p.end.u - p.start.u) + clockwise = cross < 0 + } + let start = clockwise ? p.end.tuple : p.start.tuple + let end = clockwise ? p.start.tuple : p.end.tuple + let radius = hypot(start.0 - center.0, start.1 - center.1) + let endRadius = hypot(end.0 - center.0, end.1 - center.1) + let halfWidth = p.width.millimeters / 2 + let tolerance = max(1e-8, radius * 1e-9) + guard radius.isFinite, endRadius.isFinite, center.0.isFinite, center.1.isFinite, + radius > tolerance, abs(radius - endRadius) <= tolerance else { + throw ForgeError(.invalidParams, "arc slot endpoints must have the same positive distance from the center") + } + guard halfWidth.isFinite, halfWidth > 0, radius - halfWidth > tolerance else { + throw ForgeError(.invalidParams, "slot width must be smaller than twice the centreline radius") + } + var sweep = atan2(end.1 - center.1, end.0 - center.0) - atan2(start.1 - center.1, start.0 - center.0) + if sweep < 0 { sweep += 2 * .pi } + guard sweep > 1e-8, sweep < 2 * .pi - 1e-8 else { + throw ForgeError(.invalidParams, "arc slot start and end must be different points") + } + // For major arcs the end caps face one another across the omitted arc. Avoid a + // self-intersecting contour (and the zero-clearance touching case). For minor + // arcs the outward half-caps face away from one another and may be very close. + guard sweep <= .pi || hypot(end.0 - start.0, end.1 - start.1) > 2 * halfWidth + tolerance else { + throw ForgeError(.invalidParams, "arc slot end caps overlap; reduce width or sweep") + } + func radial(_ point: (Double, Double), _ distance: Double) -> (Double, Double) { + let length = hypot(point.0 - center.0, point.1 - center.1) + return (center.0 + (point.0 - center.0) * distance / length, + center.1 + (point.1 - center.1) * distance / length) + } + let a = radial(start, radius), b = radial(end, radius) + let outerA = radial(a, radius + halfWidth), outerB = radial(b, radius + halfWidth) + let innerA = radial(a, radius - halfWidth), innerB = radial(b, radius - halfWidth) + let construction = p.construction ?? false + // Internal equal-radius rows yield to the composite's joins/tangencies/dimensions + // during rank diagnosis, but remain enforced by the solver. This avoids duplicate + // radial rows and ill-conditioned pivots near cardinal orientations after fixing + // the centreline, without introducing any coordinate-axis-dependent relation. + let outer = sketch.addArc(center: center, start: outerA, end: outerB, construction: construction, radiusYieldsToRelations: true) + let endCap = sketch.addArc(center: b, start: outerB, end: innerB, construction: construction, radiusYieldsToRelations: true) + let inner = sketch.addArc(center: center, start: innerA, end: innerB, construction: construction, radiusYieldsToRelations: true) + let startCap = sketch.addArc(center: a, start: innerA, end: outerA, construction: construction, radiusYieldsToRelations: true) + let axis = sketch.addArc(center: center, start: a, end: b, construction: true, radiusYieldsToRelations: true) + func point(_ entity: String, _ index: Int) -> String { sketch.entities[entity]!.points[index] } + var relations: [String] = [] + func relate(_ kind: ConstraintKind, _ entities: [String]) throws { + relations.append(try sketch.addConstraint(kind, entities)) + } + try relate(.coincident, [point(outer, 2), point(endCap, 1)]) + try relate(.coincident, [point(endCap, 2), point(inner, 2)]) + try relate(.coincident, [point(inner, 1), point(startCap, 1)]) + try relate(.coincident, [point(startCap, 2), point(outer, 1)]) + try relate(.concentric, [outer, inner]) + try relate(.concentric, [outer, axis]) + try relate(.coincident, [point(axis, 1), point(startCap, 0)]) + // The axis equal-radius row yields to these exact endpoint joins: its radius + // equality follows from the concentric sides and four tangent semicircular caps. + try relate(.coincident, [point(axis, 2), point(endCap, 0)]) + try relate(.tangent, [outer, endCap]) + try relate(.tangent, [inner, endCap]) + try relate(.tangent, [outer, startCap]) + try relate(.tangent, [inner, startCap]) + return finish(&ctx, doc, &sketch, created: [outer, endCap, inner, startCap, axis], constraints: relations, infer: false) + } +} diff --git a/Sources/ForgeCommands/Commands/FeatureCommands.swift b/Sources/ForgeCommands/Commands/FeatureCommands.swift index 491e80a..4fbf0d6 100644 --- a/Sources/ForgeCommands/Commands/FeatureCommands.swift +++ b/Sources/ForgeCommands/Commands/FeatureCommands.swift @@ -147,6 +147,16 @@ public enum FeatureRepairReference: Command { var doc = try ctx.requireDocument() let i = try doc.featureIndex(p.feature) let before = doc.state(before: i, registry: ctx.registry) + if let sid = doc.features[i].sketchID, var sketch = doc.sketches[sid], sketch.placement == p.old { + // Sketch attachment is persisted on the sketch, not in its feature's params. + _ = try before.resolvePlacement(p.new) + sketch.placement = before.refPlanes[p.new]?.id ?? before.orderedRefPlanes.first(where: { $0.name == p.new })?.id + ?? before.persistentRef(p.new, defaultBody: nil, bareKind: nil).ref + doc.sketches[sid] = sketch + doc.regenerate(from: i, registry: ctx.registry) + ctx.document = doc + return FeatureTreeOutput(doc) + } guard before.referenceExists(p.new) else { throw ForgeError( .unknownEntity, "\(p.new) does not exist in the model before \(doc.features[i].name)", entities: [p.new], diff --git a/Sources/ForgeCommands/Commands/FileCommands.swift b/Sources/ForgeCommands/Commands/FileCommands.swift index a35e950..1bd18c4 100644 --- a/Sources/ForgeCommands/Commands/FileCommands.swift +++ b/Sources/ForgeCommands/Commands/FileCommands.swift @@ -33,7 +33,8 @@ enum DocumentFiles { nextFeature: doc.nextFeatureNumber, featureCounters: doc.featureNameCounters, baseBodies: doc.baseBodies.map(\.id), bodyNames: doc.bodyNames, refPlanes: doc.refPlaneOrder.isEmpty ? nil : try doc.orderedRefPlanes.map { try JSONCoding.toJSON($0) }, - nextPlane: doc.nextPlaneNumber == 1 ? nil : doc.nextPlaneNumber, baseSources: sources.isEmpty ? nil : sources) + nextPlane: doc.nextPlaneNumber == 1 ? nil : doc.nextPlaneNumber, baseSources: sources.isEmpty ? nil : sources, + hiddenBodies: doc.hiddenBodyIDs.isEmpty ? nil : doc.hiddenBodyIDs.sorted()) return DocumentPackage( manifest: DocumentPackage.Manifest(app: appVersion, kernel: Kernel.version), model: model, breps: breps, thumbnailPNG: try thumbnail(doc), baseBreps: baseBreps) @@ -42,6 +43,8 @@ enum DocumentFiles { /// 256 px isometric thumbnail for Finder / Quick Look (deterministic). static func thumbnail(_ doc: Document) throws -> Data? { guard !doc.bodyOrder.isEmpty || !doc.sketchOrder.isEmpty else { return nil } + var doc = doc + doc.isolatedBodyIDs = nil let ds = try DocumentScene(document: doc) guard let bounds = ds.scene.bounds else { return nil } var cam = Camera() @@ -92,6 +95,11 @@ enum DocumentFiles { } } doc.bodyNames = m.bodyNames + // Keep visibility for suppressed/rolled-back outputs, but never let an unknown + // package ID silently hide a body created later in this session. + let knownBodyIDs = Set(m.bodies.map(\.id) + (m.baseSources ?? []).map(\.id) + + m.features.flatMap(\.createdBodies).filter { $0.hasPrefix("body-") }) + doc.hiddenBodyIDs = Set(m.hiddenBodies ?? []).intersection(knownBodyIDs) for r in try (m.refPlanes ?? []).map({ try JSONCoding.fromJSON(RefPlane.self, $0) }) { doc.refPlanes[r.id] = r doc.refPlaneOrder.append(r.id) diff --git a/Sources/ForgeCommands/Commands/HoleWizard.swift b/Sources/ForgeCommands/Commands/HoleWizard.swift index 8c17883..13c4c62 100644 --- a/Sources/ForgeCommands/Commands/HoleWizard.swift +++ b/Sources/ForgeCommands/Commands/HoleWizard.swift @@ -136,7 +136,7 @@ public enum BodyHole: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() - let sk = try doc.sketch(p.sketch) + let sk = try doc.modelingSketch(p.sketch) let centres = sk.orderedEntities.filter { $0.kind == .point && !$0.construction && $0.owner == nil && $0.id != Sketch.originID } guard !centres.isEmpty else { throw ForgeError( diff --git a/Sources/ForgeCommands/Commands/ProfileCommands.swift b/Sources/ForgeCommands/Commands/ProfileCommands.swift index f096ec4..d81b23c 100644 --- a/Sources/ForgeCommands/Commands/ProfileCommands.swift +++ b/Sources/ForgeCommands/Commands/ProfileCommands.swift @@ -346,7 +346,7 @@ public enum BodyExtrude: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() - let sk = try doc.sketch(p.sketch) + let sk = try doc.modelingSketch(p.sketch) let (loops, regions, segmentIDs) = try sk.profileLoopsWithIDs() let feature = doc.currentFeature var face = try Kernel.faces(loops: loops, regions: regions) @@ -457,7 +457,7 @@ public enum BodyRevolve: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() - let sk = try doc.sketch(p.sketch) + let sk = try doc.modelingSketch(p.sketch) let axisID = try localID(p.axis, in: sk) let axisEntity = try sk.entity(axisID) guard axisEntity.kind == .line else { throw ForgeError(.invalidParams, "the revolve axis must be a line", entities: ["\(sk.id)/\(axisID)"]) } diff --git a/Sources/ForgeCommands/Commands/QueryCommands.swift b/Sources/ForgeCommands/Commands/QueryCommands.swift index 7b7757e..8326ccb 100644 --- a/Sources/ForgeCommands/Commands/QueryCommands.swift +++ b/Sources/ForgeCommands/Commands/QueryCommands.swift @@ -200,37 +200,94 @@ public enum QueryMassProperties: Command { public enum QueryMeasure: Command { public struct Params: Codable, Sendable, SchemaDocumented { public var from: String - public var to: String - public static let fieldDocs: [String: FieldDoc] = ["from": "First body", "to": "Second body"] + public var to: String? + public static let fieldDocs: [String: FieldDoc] = [ + "from": "Body, face, edge or vertex reference (including persistent face/edge names)", + "to": "Optional second reference; return minimum distance and closest points when supplied", + ] + } + public struct EntityMeasurement: Codable, Sendable { + public var reference: String + public var kind: String + public var lengthMM: Double? + public var areaMM2: Double? + public var volumeMM3: Double? + public var radiusMM: Double? + public var center: [Double]? + public var normal: [Double]? + public var position: [Double]? + enum CodingKeys: String, CodingKey { + case reference, kind, center, normal, position + case lengthMM = "length_mm", areaMM2 = "area_mm2", volumeMM3 = "volume_mm3", radiusMM = "radius_mm" + } } public struct Output: Codable, Sendable { - public var distanceMM: Double - public var pointFrom: [Double] - public var pointTo: [Double] - + public var distanceMM: Double? + public var pointFrom: [Double]? + public var pointTo: [Double]? + public var deltaMM: [Double]? + public var fromEntity: EntityMeasurement + public var toEntity: EntityMeasurement? enum CodingKeys: String, CodingKey { - case distanceMM = "distance_mm" - case pointFrom = "point_from" - case pointTo = "point_to" + case distanceMM = "distance_mm", pointFrom = "point_from", pointTo = "point_to", deltaMM = "delta_mm" + case fromEntity = "from_entity", toEntity = "to_entity" } } public static let name = "query.measure" - public static let summary = "Minimum distance between two bodies, with the closest points" - public static let discussion = "M0 measures body to body. Face/edge/vertex measurement and angles are not implemented yet." + public static let summary = "Measure bodies, faces, edges or vertices, with minimum distance between two selections" + public static let discussion = "One selection returns its length, area, volume, circular radius or vertex position as applicable. Two selections also return exact B-rep minimum distance, closest points and their signed XYZ displacement, all in millimeters. Named references must identify a single face or edge. Angles, maximum distances and normal-distance modes are not implemented." public static let category = CommandCategory.query public static let undo = UndoBehavior.none - public static let errors: [ErrorCode] = [.unknownEntity, .notImplemented] - public static let examples: [JSONValue] = [["from": "body-1", "to": "body-2"]] + public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams, .referenceLost, .kernelFailure] + public static let examples: [JSONValue] = [ + ["from": "body-1", "to": "body-2"], ["from": "body-1/edge-0"], + ["from": "body-1/face-0", "to": "body-1/vertex-2"], + ] + + static func resolve(_ reference: String, in doc: Document) throws -> (Shape, EntityMeasurement) { + let ref = try EntityRef.parse(reference) + let body = try doc.body(ref.body) + var summary = EntityMeasurement(reference: reference, kind: ref.kind.rawValue) + switch ref.kind { + case .body: + let properties = try body.shape.massProperties() + summary.areaMM2 = properties.surfaceArea + summary.volumeMM3 = properties.volume + summary.center = properties.centroid.array + return (body.shape, summary) + case .face: + let index = try doc.faceIndices([reference], of: body, sets: false)[0] + let face = try body.shape.face(index) + summary.areaMM2 = face.area + summary.center = face.centroid.array + if face.surfaceType == .plane { summary.normal = face.normal.array } + return (try body.shape.subshape(.face, index: index), summary) + case .edge: + let indices = try doc.edgeIndices([reference], of: body) + guard indices.count == 1 else { throw ForgeError(.invalidParams, "measurement requires one edge; reference identifies \(indices.count)", entities: [reference]) } + let edge = try body.shape.edge(indices[0]) + summary.lengthMM = edge.length + summary.radiusMM = edge.circleRadius + summary.center = edge.circleCenter?.array + return (try body.shape.subshape(.edge, index: indices[0]), summary) + case .vertex: + guard let index = ref.index, index < (try body.shape.topology().vertices) else { + throw ForgeError(.unknownEntity, "no vertex '\(reference)'", entities: [reference]) + } + summary.position = try body.shape.vertex(index).array + return (try body.shape.subshape(.vertex, index: index), summary) + } + } public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { let doc = try ctx.requireDocument() - let a = try EntityRef.parse(p.from), b = try EntityRef.parse(p.to) - guard a.kind == .body, b.kind == .body else { - throw ForgeError(.notImplemented, "M0 measures between bodies only", entities: [p.from, p.to]) - } - let d = try Kernel.distance(try doc.body(a.body).shape, try doc.body(b.body).shape) - return Output(distanceMM: d.distance, pointFrom: d.pointA.array, pointTo: d.pointB.array) + let (a, first) = try resolve(p.from, in: doc) + guard let to = p.to else { return Output(fromEntity: first) } + let (b, second) = try resolve(to, in: doc) + let distance = try Kernel.distance(a, b) + return Output(distanceMM: distance.distance, pointFrom: distance.pointA.array, pointTo: distance.pointB.array, + deltaMM: (distance.pointB - distance.pointA).array, fromEntity: first, toEntity: second) } } @@ -305,6 +362,14 @@ public enum SelectionSet: Command { var doc = try ctx.requireDocument() var refs: [String] = [] for s in p.entities { + if s.hasPrefix("plane-"), StandardPlane(rawValue: String(s.dropFirst(6))) != nil { + refs.append(s) + continue + } + if let plane = doc.refPlanes[s] ?? doc.orderedRefPlanes.first(where: { $0.name == s }) { + refs.append(plane.id) + continue + } if s.hasPrefix("sketch-") || doc.sketches[String(s.split(separator: "/").first ?? "")] != nil { guard doc.referenceExists(s) else { throw ForgeError(.unknownEntity, "no sketch entity '\(s)'", entities: [s], diff --git a/Sources/ForgeCommands/Commands/SessionCommands.swift b/Sources/ForgeCommands/Commands/SessionCommands.swift index 2b221ab..714190b 100644 --- a/Sources/ForgeCommands/Commands/SessionCommands.swift +++ b/Sources/ForgeCommands/Commands/SessionCommands.swift @@ -115,12 +115,13 @@ public enum DocumentState: Command { public var sketches: [SketchSummary] public var activeSketch: String? public var selection: [String] + public var visibility: BodyVisibilityState public var undo: [String] public var redo: [String] public var transaction: String? enum CodingKeys: String, CodingKey { - case document, bodies, sketches, selection, undo, redo, transaction + case document, bodies, sketches, selection, visibility, undo, redo, transaction case activeSketch = "active_sketch" } } @@ -140,6 +141,7 @@ public enum DocumentState: Command { bodies: try doc.orderedBodies.map(BodySummary.init), sketches: doc.orderedSketches.map { SketchSummary($0, active: $0.id == doc.activeSketch) }, activeSketch: doc.activeSketch, selection: doc.selection, + visibility: BodyVisibilityState(doc), undo: s.undoLabels, redo: s.redoLabels, transaction: s.transactionLabel) } } diff --git a/Sources/ForgeCommands/Commands/SketchCommands.swift b/Sources/ForgeCommands/Commands/SketchCommands.swift index 6de0a4d..69dcaec 100644 --- a/Sources/ForgeCommands/Commands/SketchCommands.swift +++ b/Sources/ForgeCommands/Commands/SketchCommands.swift @@ -723,8 +723,10 @@ public enum SketchAddSlot: Command { public var start: Point2 public var end: Point2 public var width: Length + public var construction: Bool? public static let fieldDocs: [String: FieldDoc] = [ "sketch": sketchParamDoc, + "construction": constructionDoc, "mode": FieldDoc("straight: start/end are the arc centres; center: start is the slot centre, end an arc centre", default: "straight"), "start": "First point", "end": "Second point", "width": "Slot width (arc diameter)", ] @@ -742,6 +744,7 @@ public enum SketchAddSlot: Command { var (doc, s) = try ctx.sketchForEdit(p.sketch) let before = Set(s.constraints.map(\.id)) let created = try s.addSlot(p.mode ?? .straight, p.start.tuple, p.end.tuple, width: p.width.millimeters) + if p.construction == true { for id in created.prefix(4) { try s.setConstruction(id, true) } } let added = s.constraints.map(\.id).filter { !before.contains($0) && !$0.contains("#") } return finish(&ctx, doc, &s, created: created, constraints: added, infer: false) } diff --git a/Sources/ForgeCommands/Commands/SketchConvertCommands.swift b/Sources/ForgeCommands/Commands/SketchConvertCommands.swift new file mode 100644 index 0000000..34d9450 --- /dev/null +++ b/Sources/ForgeCommands/Commands/SketchConvertCommands.swift @@ -0,0 +1,84 @@ +import ForgeCore +import ForgeKernel +import ForgeSketch +import Foundation + +public enum SketchConvertEntities: Command { + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var sketch: String? + public var entities: [String] + public var construction: Bool? + public var fixed: Bool? + public static let fieldDocs: [String: FieldDoc] = [ + "sketch": sketchParamDoc, + "entities": "Model edge or face references; faces convert all boundary edges, duplicate edges are included once", + "construction": constructionDoc, + "fixed": FieldDoc("Fix converted curves at their projected positions", default: true), + ] + public func validate() throws { + guard !entities.isEmpty else { throw ForgeError(.invalidParams, "select at least one model edge or face") } + } + } + public typealias Output = SketchEditResult + public static let name = "sketch.convert_entities" + public static let summary = "Project model edges or face boundaries into a sketch as independent curves" + public static let discussion = "Creates exact orthogonal projections of straight edges and circles/arcs parallel to the sketch plane. Curves are detached snapshots: later source edits do not resize them. Curved edges oblique to the plane, ellipses, splines and degenerate projections are rejected atomically. Fixed by default; set fixed: false for editable geometry." + public static let category = CommandCategory.sketch + public static let undo = UndoBehavior.undoable + public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams, .unsupported, .referenceLost] + public static let examples: [JSONValue] = [["entities": ["body-1/face-5"]], ["entities": ["body-1/edge-0"], "construction": true, "fixed": false]] + + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { + var (doc, sketch) = try ctx.sketchForEdit(p.sketch) + var seen = Set() + var edges: [Shape.EdgeInfo] = [] + for reference in p.entities { + let ref = try EntityRef.parse(reference) + guard ref.kind == .edge || ref.kind == .face else { + throw ForgeError(.invalidParams, "select model edges or faces", entities: [reference]) + } + let body = try doc.body(ref.body) + for index in try doc.edgeIndices([reference], of: body) { + if seen.insert("\(body.id)/edge-\(index)").inserted { edges.append(try body.shape.edge(index)) } + } + } + func project(_ point: Vec3) -> (Double, Double) { + let relative = point - sketch.plane.origin + return (relative.dot(sketch.plane.xAxis), relative.dot(sketch.plane.yAxis)) + } + var created: [String] = [] + var constraints: [String] = [] + for edge in edges { + guard !edge.isDegenerate else { throw ForgeError(.unsupported, "a degenerate edge cannot be converted") } + let start = project(edge.start), end = project(edge.end) + let id: String + switch edge.curveType { + case .line: + guard hypot(end.0 - start.0, end.1 - start.1) > 1e-7 else { + throw ForgeError(.unsupported, "an edge projects to a point on this sketch plane") + } + id = sketch.addLine(from: start, to: end, construction: p.construction ?? false) + case .circle: + guard let center3 = edge.circleCenter, let axis = edge.circleAxis, let radius = edge.circleRadius, + axis.cross(sketch.plane.normal).length < 1e-8 else { + throw ForgeError(.unsupported, "circular edges must be parallel to the sketch plane; oblique circle projection is not implemented") + } + let center = project(center3) + if abs(edge.length - 2 * .pi * radius) <= max(1e-7, radius * 1e-8) { + id = sketch.addCircle(center: center, radius: radius, construction: p.construction ?? false) + } else { + let mid = project(edge.midpoint) + func angle(_ point: (Double, Double)) -> Double { atan2(point.1 - center.1, point.0 - center.0) } + func positive(_ angle: Double) -> Double { let a = angle.truncatingRemainder(dividingBy: 2 * .pi); return a < 0 ? a + 2 * .pi : a } + let ccw = positive(angle(mid) - angle(start)) < positive(angle(end) - angle(start)) + id = sketch.addArc(center: center, start: ccw ? start : end, end: ccw ? end : start, construction: p.construction ?? false) + } + default: + throw ForgeError(.unsupported, "conversion supports straight edges and circular edges parallel to the sketch plane") + } + created.append(id) + if p.fixed ?? true { constraints.append(try sketch.addConstraint(.fix, [id])) } + } + return finish(&ctx, doc, &sketch, created: created, constraints: constraints, infer: false) + } +} diff --git a/Sources/ForgeCommands/Commands/SketchTransformCommands.swift b/Sources/ForgeCommands/Commands/SketchTransformCommands.swift index de70557..f939840 100644 --- a/Sources/ForgeCommands/Commands/SketchTransformCommands.swift +++ b/Sources/ForgeCommands/Commands/SketchTransformCommands.swift @@ -465,18 +465,18 @@ public enum SketchSplit: Command { public var at: [Point2] public static let fieldDocs: [String: FieldDoc] = [ "sketch": sketchParamDoc, - "entity": "The line, arc or circle to split", - "at": "Split points (projected onto the curve): one for a line or arc, two for a circle", + "entity": "The line, circular arc, partial ellipse, circle or ellipse to split", + "at": "Split points (projected onto the curve): one for an open curve, two for a circle or ellipse", ] public func validate() throws { - guard at.count == 1 || at.count == 2 else { throw ForgeError(.invalidParams, "give one split point (line/arc) or two (circle)") } + guard at.count == 1 || at.count == 2 else { throw ForgeError(.invalidParams, "give one split point (line/arc/partial ellipse) or two (circle/ellipse)") } } } public typealias Output = SketchTrimOutput public static let name = "sketch.split" - public static let summary = "Split a line or arc at a point, or a circle at two points, into pieces joined by coincident relations" - public static let discussion = "Line pieces stay on one line, arc/circle pieces stay concentric; the far end's relations move to the new piece; length-type relations of the original are removed and listed. Ellipses: not implemented." + public static let summary = "Split an open sketch curve at one point or a circle/ellipse at two points, with coincident joins" + public static let discussion = "Line pieces stay on one line, arc/circle pieces stay concentric; the far end's relations move to the new piece; length-type relations of the original are removed and listed. Ellipse pieces share their axes and rotation. Spline splitting is not implemented." public static let category = CommandCategory.sketch public static let undo = UndoBehavior.undoable public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams, .notImplemented, .solverFailed] diff --git a/Sources/ForgeCommands/Commands/SweepLoftRib.swift b/Sources/ForgeCommands/Commands/SweepLoftRib.swift index d90e3db..7290998 100644 --- a/Sources/ForgeCommands/Commands/SweepLoftRib.swift +++ b/Sources/ForgeCommands/Commands/SweepLoftRib.swift @@ -140,7 +140,7 @@ public enum BodySweep: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() - let pathSketch = try doc.sketch(p.path) + let pathSketch = try doc.modelingSketch(p.path) let (segments, pathIDs) = try pathSketch.pathChain(p.pathEntities) let path = try Kernel.wire(segments) let feature = doc.currentFeature @@ -153,7 +153,7 @@ public enum BodySweep: Command { face = try Kernel.faces(loops: [[.circle(center: start.point, normal: start.tangent, radius: d.millimeters / 2)]], regions: [0]) edgeNames = ["circle"] } else { - let sk = try doc.sketch(p.profile) + let sk = try doc.modelingSketch(p.profile) let (loops, regions, ids) = try sk.profileLoopsWithIDs() face = try Kernel.faces(loops: loops, regions: regions) edgeNames = try Naming.profileEdges(face, segmentIDs: ids) @@ -213,7 +213,7 @@ public enum BodyLoft: Command { var doc = try ctx.requireDocument() var sections: [NamedShape] = [] for ref in p.profiles { - let sk = try doc.sketch(ref) + let sk = try doc.modelingSketch(ref) let (loops, regions, ids) = try sk.profileLoopsWithIDs() guard Set(regions).count == 1 else { throw ForgeError(.invalidParams, "\(sk.name) has \(Set(regions).count) separate profiles; a loft profile is one closed loop", entities: [sk.id]) @@ -290,7 +290,7 @@ public enum BodyRib: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() - let sk = try doc.sketch(p.sketch) + let sk = try doc.modelingSketch(p.sketch) let (segments, ids) = try sk.pathChain() var points: [Vec3] = [] for s in segments { diff --git a/Sources/ForgeCommands/Commands/ViewCommands.swift b/Sources/ForgeCommands/Commands/ViewCommands.swift index 5e7b0fd..ce5e3b3 100644 --- a/Sources/ForgeCommands/Commands/ViewCommands.swift +++ b/Sources/ForgeCommands/Commands/ViewCommands.swift @@ -43,7 +43,7 @@ public struct DocumentScene: Sendable { public init(document: Document, bodies filter: [String]? = nil, highlight: [String] = [], showSketches: Bool = true) throws { let selected = try filter.map { try $0.map { try document.body($0).id } } - let list = document.orderedBodies.filter { selected?.contains($0.id) ?? true } + let list = document.orderedBodies.filter { (selected?.contains($0.id) ?? true) && document.isBodyVisible($0.id) } let bodyRefs = highlight.filter { !document.sketches.keys.contains(String($0.split(separator: "/").first ?? "")) } let refs = bodyRefs.compactMap(EntityRef.init(parsing:)) var items: [RenderItem] = [] diff --git a/Sources/ForgeCommands/Commands/VisibilityCommands.swift b/Sources/ForgeCommands/Commands/VisibilityCommands.swift new file mode 100644 index 0000000..53ff87a --- /dev/null +++ b/Sources/ForgeCommands/Commands/VisibilityCommands.swift @@ -0,0 +1,94 @@ +import ForgeCore + +public struct BodyVisibilityState: Codable, Sendable { + public var hiddenBodies: [String] + public var visibleBodies: [String] + public var isolatedBodies: [String]? + enum CodingKeys: String, CodingKey { + case hiddenBodies = "hidden_bodies", visibleBodies = "visible_bodies", isolatedBodies = "isolated_bodies" + } + public init(_ doc: Document) { + hiddenBodies = doc.bodyOrder.filter { doc.hiddenBodyIDs.contains($0) } + visibleBodies = doc.bodyOrder.filter { doc.isBodyVisible($0) } + isolatedBodies = doc.isolatedBodyIDs.map { ids in doc.bodyOrder.filter { ids.contains($0) } } + } +} + +public enum ViewSetVisibility: Command { + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var bodies: [String] + public var visible: Bool + public static let fieldDocs: [String: FieldDoc] = ["bodies": "Body IDs or names to show or hide", "visible": "True shows bodies; false hides them"] + public func validate() throws { + guard !bodies.isEmpty else { throw ForgeError(.invalidParams, "choose at least one body") } + } + } + public static let name = "view.set_visibility" + public static let summary = "Show or hide bodies without changing their geometry" + public static let discussion = "Ordinary visibility is saved with the document. During isolation, changes affect only the temporary isolation whitelist. Hidden bodies cannot be picked in rendered views; geometry queries and file exports still include them." + public static let category = CommandCategory.view + public static let undo = UndoBehavior.undoable + public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams] + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> BodyVisibilityState { + var doc = try ctx.requireDocument() + let ids = Set(try p.bodies.map { try doc.body($0).id }) + if var isolation = doc.isolatedBodyIDs { + if p.visible { isolation.formUnion(ids) } else { isolation.subtract(ids) } + doc.isolatedBodyIDs = isolation + } else if p.visible { doc.hiddenBodyIDs.subtract(ids) } + else { doc.hiddenBodyIDs.formUnion(ids) } + ctx.document = doc + return BodyVisibilityState(doc) + } +} + +public enum ViewIsolate: Command { + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var bodies: [String] + public static let fieldDocs: [String: FieldDoc] = ["bodies": "Bodies to show exclusively until Exit Isolation; may include hidden bodies"] + public func validate() throws { + guard !bodies.isEmpty else { throw ForgeError(.invalidParams, "choose at least one body to isolate") } + } + } + public static let name = "view.isolate" + public static let summary = "Temporarily show only the specified bodies" + public static let discussion = "Exit Isolation restores saved visibility. Isolation is not saved in document packages; new bodies remain outside the isolation whitelist." + public static let category = CommandCategory.view + public static let undo = UndoBehavior.undoable + public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams] + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> BodyVisibilityState { + var doc = try ctx.requireDocument() + doc.isolatedBodyIDs = Set(try p.bodies.map { try doc.body($0).id }) + ctx.document = doc + return BodyVisibilityState(doc) + } +} + +public enum ViewExitIsolation: Command { + public typealias Params = NoParams + public static let name = "view.exit_isolation" + public static let summary = "Exit isolation and restore ordinary body visibility" + public static let category = CommandCategory.view + public static let undo = UndoBehavior.undoable + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> BodyVisibilityState { + var doc = try ctx.requireDocument() + doc.isolatedBodyIDs = nil + ctx.document = doc + return BodyVisibilityState(doc) + } +} + +public enum ViewShowAll: Command { + public typealias Params = NoParams + public static let name = "view.show_all" + public static let summary = "Show all bodies and exit isolation" + public static let category = CommandCategory.view + public static let undo = UndoBehavior.undoable + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> BodyVisibilityState { + var doc = try ctx.requireDocument() + doc.hiddenBodyIDs = [] + doc.isolatedBodyIDs = nil + ctx.document = doc + return BodyVisibilityState(doc) + } +} diff --git a/Sources/ForgeCommands/Document.swift b/Sources/ForgeCommands/Document.swift index 835049f..2aa3c39 100644 --- a/Sources/ForgeCommands/Document.swift +++ b/Sources/ForgeCommands/Document.swift @@ -36,6 +36,14 @@ public struct Document: Sendable { public internal(set) var bodies: [String: Body] = [:] /// Explicit, queryable selection (SPEC §5.4: no hidden state). Entity reference strings. public var selection: [String] = [] + /// Persistent display visibility; geometry and exports still include hidden bodies. + public var hiddenBodyIDs: Set = [] + /// Temporary isolation whitelist. Nil restores ordinary saved visibility. + public var isolatedBodyIDs: Set? + + public func isBodyVisible(_ id: String) -> Bool { + isolatedBodyIDs.map { $0.contains(id) } ?? !hiddenBodyIDs.contains(id) + } var nextBodyNumber = 1 /// Sketches in creation order. @@ -192,6 +200,16 @@ public struct Document: Sendable { suggestions: [SuggestedFix(description: "List document state", command: "document.state")]) } + /// Profiles with unavailable attachments must never generate solids from stale geometry. + func modelingSketch(_ reference: String?) throws -> Sketch { + let s = try sketch(reference) + if let source = features.first(where: { $0.sketchID == s.id }), + source.status.state == .error || source.status.state == .suppressed || source.status.state == .rolledBack { + throw ForgeError(.referenceLost, "sketch \(s.name) is unavailable; repair or restore its feature before modeling", entities: [s.id, source.id]) + } + return s + } + public mutating func updateSketch(_ s: Sketch) { precondition(sketches[s.id] != nil) sketches[s.id] = s @@ -217,6 +235,8 @@ public struct Document: Sendable { /// Whether a reference string names something that currently exists: "body-1", /// "body-1/face-3", "sketch-2", "sketch-2/line-5". public func referenceExists(_ ref: String) -> Bool { + if ref.hasPrefix("plane-"), StandardPlane(rawValue: String(ref.dropFirst(6))) != nil { return true } + if refPlanes[ref] != nil { return true } let parts = ref.split(separator: "/", maxSplits: 1).map(String.init) guard let head = parts.first else { return false } if let sk = sketches[head] { diff --git a/Sources/ForgeCommands/Engine.swift b/Sources/ForgeCommands/Engine.swift index 5479927..cede35c 100644 --- a/Sources/ForgeCommands/Engine.swift +++ b/Sources/ForgeCommands/Engine.swift @@ -57,6 +57,7 @@ public struct ChangeSet: Codable, Sendable, Hashable { // Reordering and rollback can change the history without changing any shape. if let before, let after, before.name != after.name || before.units != after.units || before.rollback != after.rollback + || before.hiddenBodyIDs != after.hiddenBodyIDs || before.isolatedBodyIDs != after.isolatedBodyIDs || (Set(bf.map(\.id)) == Set(af.map(\.id)) && bf.map(\.id) != af.map(\.id)) { c.modified.append(after.id) } diff --git a/Sources/ForgeCommands/Features.swift b/Sources/ForgeCommands/Features.swift index 0367b30..fed295c 100644 --- a/Sources/ForgeCommands/Features.swift +++ b/Sources/ForgeCommands/Features.swift @@ -255,6 +255,14 @@ extension Document { (try? bodies[id]?.shape.topology()).map { (id, usesFaces ? $0.faces : $0.edges) } }) do { + // A lost or suppressed sketch attachment must not leave a usable stale profile. + for ref in f.usedSketches { + let sid = try sketch(ref).id + if let source = features[.. Shape { + guard let i = Int32(exactly: index), i >= 0 else { throw ForgeError(.invalidParams, "invalid subshape index") } + var err = FKError() + guard let h = fk_subshape(handle, kind.rawValue, i, &err) else { throw Kernel.error(err) } + return Shape(owning: h) + } + + public func vertex(_ index: Int) throws -> Vec3 { + guard let i = Int32(exactly: index), i >= 0 else { throw ForgeError(.invalidParams, "invalid vertex index") } + var point = [Double](repeating: 0, count: 3) + var err = FKError() + if fk_vertex_position(handle, i, &point, &err) != 0 { throw Kernel.error(err) } + return Vec3(point[0], point[1], point[2]) + } + public struct Topology: Codable, Sendable, Hashable { public var solids, shells, faces, wires, edges, vertices: Int } @@ -136,6 +154,9 @@ public final class Shape: @unchecked Sendable { public var midpoint: Vec3 public var isDegenerate: Bool public var faces: [Int] + public var circleCenter: Vec3? + public var circleAxis: Vec3? + public var circleRadius: Double? } public func edge(_ index: Int) throws -> EdgeInfo { @@ -150,7 +171,10 @@ public final class Shape: @unchecked Sendable { index: index, curveType: types[min(Int(e.curveType), types.count - 1)], length: e.length, start: Vec3(e.start.0, e.start.1, e.start.2), end: Vec3(e.end.0, e.end.1, e.end.2), midpoint: Vec3(e.midpoint.0, e.midpoint.1, e.midpoint.2), isDegenerate: e.isDegenerate != 0, - faces: faces.prefix(Int(min(n, 8))).map { Int($0) }) + faces: faces.prefix(Int(min(n, 8))).map { Int($0) }, + circleCenter: e.circleRadius > 0 ? Vec3(e.circleCenter.0, e.circleCenter.1, e.circleCenter.2) : nil, + circleAxis: e.circleRadius > 0 ? Vec3(e.circleAxis.0, e.circleAxis.1, e.circleAxis.2) : nil, + circleRadius: e.circleRadius > 0 ? e.circleRadius : nil) } /// Tessellate for display/picking. `linearDeflection` ≤ 0 picks an automatic value. diff --git a/Sources/ForgeMCP/Tools.swift b/Sources/ForgeMCP/Tools.swift index c0b600b..8981d72 100644 --- a/Sources/ForgeMCP/Tools.swift +++ b/Sources/ForgeMCP/Tools.swift @@ -99,6 +99,7 @@ public enum ToolCatalog { // ---- sketch alias("create_sketch", "Create sketch", "sketch.create"), alias("get_sketch", "Get sketch", "sketch.get"), + alias("convert_entities", "Project model edges into detached sketch curves", "sketch.convert_entities"), alias("edit_dimension", "Edit dimension", "sketch.set_dimension"), alias("check_sketch", "Check sketch", "sketch.check"), // ---- parametric history: the same commands used by the desktop feature tree diff --git a/Sources/ForgeSketch/Sketch.swift b/Sources/ForgeSketch/Sketch.swift index 2b20b61..afe1fcc 100644 --- a/Sources/ForgeSketch/Sketch.swift +++ b/Sources/ForgeSketch/Sketch.swift @@ -255,14 +255,17 @@ public struct Sketch: Codable, Sendable, Hashable { /// Arc from start to end, counter-clockwise around the centre. @discardableResult - public mutating func addArc(center: (Double, Double), start: (Double, Double), end: (Double, Double), construction: Bool = false) -> String { + public mutating func addArc(center: (Double, Double), start: (Double, Double), end: (Double, Double), construction: Bool = false, radiusYieldsToRelations: Bool = false) -> String { let id = newID(.arc) let c = addPoint(center.0, center.1, construction: true, owner: id) let s = addPoint(start.0, start.1, construction: construction, owner: id) let e = addPoint(end.0, end.1, construction: construction, owner: id) insert(SketchEntity(id: id, kind: .arc, construction: construction, owner: nil, points: [c, s, e], params: [])) - constraints.append( - SketchConstraint(id: "\(id)#radius", kind: .arcRadius, entities: [id], value: nil, driven: false, side: 1, isInternal: true)) + var radiusConstraint = SketchConstraint(id: "\(id)#radius", kind: .arcRadius, entities: [id], value: nil, driven: false, side: 1, isInternal: true) + // Composite geometry may imply this invariant through its ordinary relations. + // Keep enforcing it, but diagnose it last so it does not make those relations redundant. + radiusConstraint.yields = radiusYieldsToRelations + constraints.append(radiusConstraint) return id } diff --git a/Sources/ForgeUI/AppModel.swift b/Sources/ForgeUI/AppModel.swift index 204fa44..9caf701 100644 --- a/Sources/ForgeUI/AppModel.swift +++ b/Sources/ForgeUI/AppModel.swift @@ -19,7 +19,7 @@ package enum RibbonTab: String, CaseIterable, Identifiable { package enum Operation: Hashable { case extrude, cutExtrude, revolve, cutRevolve, hole, fillet, chamfer, shell, draft, plane, linearPattern, circularPattern, mirror, combine case sweep, cutSweep, loft, cutLoft, rib - case massProperties, measure, check, interference + case massProperties, measure, check, interference, moveBody case primitive(Primitive) // Sketch operations on the selected sketch entities. case addRelation, displayRelations, sketchOffset, sketchMirror, sketchLinearPattern, sketchCircularPattern @@ -46,6 +46,7 @@ package enum Operation: Hashable { case .shell: "Shell" case .draft: "Draft" case .combine: "Combine" + case .moveBody: "Move/Copy Bodies" case .massProperties: "Mass Properties" case .measure: "Measure" case .check: "Check" @@ -82,6 +83,7 @@ package enum Operation: Hashable { case .shell: .shell case .draft: .draft case .combine: .combine + case .moveBody: .move case .massProperties: .massProps case .measure: .measure case .check: .check @@ -175,6 +177,7 @@ package struct FeatureRow: Identifiable, Equatable { case "body.shell": .shell case "body.draft": .draft case "body.boolean": .combine + case "body.transform": .moveBody case "body.create_box": .primitive(.box) case "body.create_cylinder": .primitive(.cylinder) case "body.create_sphere": .primitive(.sphere) @@ -238,6 +241,8 @@ package final class AppModel { /// Bumped whenever the scene must be re-uploaded to the GPU. package var sceneVersion = 0 package var scene = DocumentSceneBox() + package var hiddenBodyIDs: Set = [] + package var isIsolatingBodies = false /// The document's scene before reference geometry (planes, axes, the sketch grid). @ObservationIgnored private var baseScene: DocumentScene? @ObservationIgnored private var referenceInputs: ReferenceInputs? @@ -389,6 +394,8 @@ package final class AppModel { package func refresh() async { guard let doc = await engine.activeDocument else { return } documentName = doc.name + hiddenBodyIDs = Set(doc.bodyOrder.filter { !doc.isBodyVisible($0) }) + isIsolatingBodies = doc.isolatedBodyIDs != nil bodies = (try? doc.orderedBodies.map(BodySummary.init)) ?? [] sketches = doc.orderedSketches.map { SketchRow( @@ -505,8 +512,22 @@ package final class AppModel { return true } + package var canNormalTo: Bool { sketchState.plane != nil || selectedFace != nil || selection.contains { $0.hasPrefix("plane-") } } + package func normalToSketch() { - if let p = sketchState.plane { viewportCommands.send(.normalTo(p)) } + if let plane = sketchState.plane { viewportCommands.send(.normalTo(plane)) } + else { Task { await normalToSelection() } } + } + + package func normalToSelection() async { + if let plane = sketchState.plane { viewportCommands.send(.normalTo(plane)); return } + guard let ref = selectedFace ?? selection.last(where: { $0.hasPrefix("plane-") }) else { return } + do { + guard let doc = await engine.activeDocument else { return } + let placement = ref.hasPrefix("plane-") && StandardPlane(rawValue: String(ref.dropFirst(6))) != nil ? String(ref.dropFirst(6)) : ref + viewportCommands.send(.normalTo(try doc.resolvePlacement(placement))) + lastError = nil + } catch { lastError = ForgeError.wrap(error) } } /// Bodies in the selection (a face/edge selection counts for its body). diff --git a/Sources/ForgeUI/BodyVisibilityWorkflows.swift b/Sources/ForgeUI/BodyVisibilityWorkflows.swift new file mode 100644 index 0000000..5b08db8 --- /dev/null +++ b/Sources/ForgeUI/BodyVisibilityWorkflows.swift @@ -0,0 +1,16 @@ +import ForgeCore + +extension AppModel { + package func setBodiesVisible(_ ids: [String], _ visible: Bool) async { + guard !ids.isEmpty else { return } + await run("view.set_visibility", ["bodies": .array(ids.map(JSONValue.string)), "visible": .bool(visible)]) + } + + package func isolateBodies(_ ids: [String]) async { + guard !ids.isEmpty else { return } + await run("view.isolate", ["bodies": .array(ids.map(JSONValue.string))]) + } + + package func showAllBodies() async { await run("view.show_all") } + package func exitBodyIsolation() async { await run("view.exit_isolation") } +} diff --git a/Sources/ForgeUI/PanelSpec.swift b/Sources/ForgeUI/PanelSpec.swift index 4380b94..33ad0cf 100644 --- a/Sources/ForgeUI/PanelSpec.swift +++ b/Sources/ForgeUI/PanelSpec.swift @@ -162,7 +162,7 @@ extension AppModel { } private var endConditionOptions: [(tag: String, title: String)] { - EndConditionUI.allCases.filter { operation == .cutExtrude || !bodies.isEmpty || $0.needsDepth }.map { ($0.rawValue, $0.rawValue) } + EndConditionUI.allCases.filter { operation == .cutExtrude || !bodies.isEmpty || $0.needsDepth || $0 == .upToVertex }.map { ($0.rawValue, $0.rawValue) } } // MARK: operations @@ -192,14 +192,16 @@ extension AppModel { d1.append(check("draftOutward", "Draft outward", \.draftOutward)) } } + if f.endCondition == .upToVertex { d1 += [field("vertexX", "Vertex X", unit: "mm", \.vertexX), field("vertexY", "Vertex Y", unit: "mm", \.vertexY), field("vertexZ", "Vertex Z", unit: "mm", \.vertexZ)] } s.append(PanelSection("Direction 1", controls: d1)) if f.endCondition != .midPlane && f.endCondition != .throughAllBoth { var d2: [PanelControl] = [ PanelControl(id: "end2", kind: .choice( - label: "End condition", options: [EndConditionUI.blind, .throughAll].filter { $0 == .blind || !bodies.isEmpty }.map { ($0.rawValue, $0.rawValue) }, + label: "End condition", options: [EndConditionUI.blind, .throughAll, .upToVertex].filter { $0 != .throughAll || !bodies.isEmpty }.map { ($0.rawValue, $0.rawValue) }, get: { [unowned self] in form.endCondition2.rawValue }, set: { [unowned self] in if let v = EndConditionUI(rawValue: $0) { form.endCondition2 = v } })), ] if f.endCondition2 == .blind { d2.append(field("depth2", "Depth", unit: "mm", \.depth2)) } + if f.endCondition2 == .upToVertex { d2 += [field("vertex2X", "Vertex X", unit: "mm", \.vertex2X), field("vertex2Y", "Vertex Y", unit: "mm", \.vertex2Y), field("vertex2Z", "Vertex Z", unit: "mm", \.vertex2Z)] } s.append(PanelSection("Direction 2", toggle: (get: { [unowned self] in form.direction2 }, set: { [unowned self] in form.direction2 = $0 }), controls: d2)) } var thin = [choice("thinType", "Type", [("one_direction", "One-Direction"), ("mid_plane", "Mid-Plane"), ("two_direction", "Two-Direction")], \.thinType), @@ -309,6 +311,13 @@ extension AppModel { PanelControl(id: "faces", kind: .list( items: f.draftFaces.map(shortName), placeholder: "Faces", active: f.activeBox == "faces", activate: { [unowned self] in form.activeBox = "faces" })), ])) + case .moveBody: + s.append(PanelSection("Body", controls: [choice("body", "Body", bodies.map { ($0.id, $0.name) }, \.target), check("copyBody", "Create copy", \.bodyCopy)])) + s.append(PanelSection("Translation", controls: [field("bodyDX", "X", unit: "mm", \.bodyDX), field("bodyDY", "Y", unit: "mm", \.bodyDY), field("bodyDZ", "Z", unit: "mm", \.bodyDZ)])) + s.append(PanelSection("Rotation", toggle: (get: { [unowned self] in form.bodyRotation }, set: { [unowned self] in form.bodyRotation = $0 }), controls: [ + choice("bodyAxis", "Axis", [("x", "X"), ("y", "Y"), ("z", "Z")] + (f.bodyAxis == "custom" ? [("custom", "Stored custom axis")] : []), \.bodyAxis), field("bodyAngle", "Angle", unit: "°", \.bodyAngle), + field("bodyOriginX", "Origin X", unit: "mm", \.bodyOriginX), field("bodyOriginY", "Origin Y", unit: "mm", \.bodyOriginY), field("bodyOriginZ", "Origin Z", unit: "mm", \.bodyOriginZ), + ])) case .combine: let bodyOptions = bodies.map { (tag: $0.id, title: $0.name) } s.append(PanelSection("Operation Type", controls: [choice("combine", "Operation", [("fuse", "Add"), ("cut", "Subtract"), ("common", "Common")], \.combine)])) @@ -342,7 +351,7 @@ extension AppModel { case .massProperties, .measure, .check: let rows = form.result.map(Self.keyValues) ?? [] s.append(PanelSection(op == .measure ? "Measure" : "Results", controls: rows.isEmpty - ? [note("empty", op == .measure ? "Select two faces, edges, vertices or bodies." : "Select a body.")] + ? [note("empty", op == .measure ? "Select one entity for its size, or two for their minimum distance." : "Select a body.")] : rows.enumerated().map { i, kv in PanelControl(id: "r\(i)", kind: .value(label: kv.0, value: kv.1)) })) case .addRelation: s += [selectedEntitiesSection, relationsSection(all: false), relationButtonsSection].compactMap { $0 } @@ -411,7 +420,7 @@ extension AppModel { case .shell: "Select the faces to remove. With none, the body becomes a closed hollow shell." case .draft: form.activeBox == "neutral" ? "Select the neutral plane: a planar face." : "Select the faces to draft." case .combine: "Click the bodies to combine in the view: the main body first." - case .measure where selection.count != 2: "Select two entities to measure between." + case .measure where !(1...2).contains(selection.count): "Select one or two entities to measure." case .sketchMirror where form.mirrorAxis.isEmpty: "Select the entities to mirror and a line (ideally a centerline) to mirror about." case .sketchOffset, .sketchLinearPattern, .sketchCircularPattern, .sketchMove, .sketchRotate, .sketchScale: sketchSelection.isEmpty ? "Select the sketch entities in the view." : nil @@ -503,7 +512,11 @@ extension AppModel { case .rectangle: s = [PanelSection("Rectangle Type", controls: [toolChoice("type", "Type", \.rectangleType)]), construction] case .circle: s = [PanelSection("Circle Type", controls: [toolChoice("type", "Type", \.circleType)]), construction] case .arc: s = [PanelSection("Arc Type", controls: [toolChoice("type", "Type", \.arcType)]), construction] - case .slot: s = [PanelSection("Slot Types", controls: [toolChoice("type", "Type", \.slotType)])] + case .slot: + s = [PanelSection("Slot Types", controls: [PanelControl(id: "type", kind: .choice( + label: "Type", options: SlotType.allCases.map { (tag: $0.rawValue, title: $0.rawValue) }, + get: { [unowned self] in sketchState.slotType.rawValue }, + set: { [unowned self] in if let type = SlotType(rawValue: $0) { chooseSlotType(type) } }))]), construction] case .polygon: s = [PanelSection("Parameters", controls: [ PanelControl(id: "sides", kind: .field( @@ -531,7 +544,7 @@ extension AppModel { } s = [PanelSection("Chamfer Parameters", controls: c)] case .trim: s = [PanelSection("Options", controls: [toolChoice("mode", "Mode", \.trimMode)])] - case .point, .extend, .dimension: s = [] + case .point, .extend, .split, .dimension: s = [] } return PanelPage( icon: tool.icon, title: tool == .line ? "Insert \(st.lineKind.rawValue)" : tool.title, subtitle: "", message: toolMessage(tool), ok: nil, diff --git a/Sources/ForgeUI/Platform.swift b/Sources/ForgeUI/Platform.swift index 67b7b2e..1ba529d 100644 --- a/Sources/ForgeUI/Platform.swift +++ b/Sources/ForgeUI/Platform.swift @@ -8,6 +8,8 @@ package protocol PlatformServices: AnyObject { /// A document to open (nil: cancelled). func chooseOpenPath() -> String? func chooseImportSTEPPath() -> String? + /// A replacement name, or nil when the user cancels. Empty input is validated by the command. + func requestName(_ title: String, currentName: String) -> String? func showMessage(_ title: String, _ message: String) } @@ -22,6 +24,7 @@ package final class HeadlessPlatform: PlatformServices { // Existing headless/platform implementations can opt into these optional dialogs. extension PlatformServices { + package func requestName(_ title: String, currentName: String) -> String? { nil } package func chooseImportSTEPPath() -> String? { nil } package func showMessage(_ title: String, _ message: String) {} } diff --git a/Sources/ForgeUI/PropertyManager.swift b/Sources/ForgeUI/PropertyManager.swift index f44a8be..3b19043 100644 --- a/Sources/ForgeUI/PropertyManager.swift +++ b/Sources/ForgeUI/PropertyManager.swift @@ -11,7 +11,7 @@ import Observation /// SolidWorks' end conditions as shown in the Extrude page (the engine's body.extrude names). package enum EndConditionUI: String, CaseIterable { - case blind = "Blind", throughAll = "Through All", throughAllBoth = "Through All - Both", midPlane = "Mid Plane" + case blind = "Blind", throughAll = "Through All", throughAllBoth = "Through All - Both", midPlane = "Mid Plane", upToVertex = "Up To Vertex" package var param: String { switch self { @@ -19,6 +19,7 @@ package enum EndConditionUI: String, CaseIterable { case .throughAll: "through_all" case .throughAllBoth: "through_all_both" case .midPlane: "mid_plane" + case .upToVertex: "up_to_vertex" } } @@ -32,6 +33,12 @@ package enum EndConditionUI: String, CaseIterable { /// Values being edited in the PropertyManager. Lengths are text so units work ("0.5 in"). package struct OperationForm { + package var bodyDX = "0", bodyDY = "0", bodyDZ = "0", bodyCopy = false + package var bodyCustomAxis: [JSONValue] = [0, 0, 1] + package var bodyRotation = false, bodyAngle = "90", bodyAxis = "z" + package var bodyOriginX = "0", bodyOriginY = "0", bodyOriginZ = "0" + package var vertexX = "0", vertexY = "0", vertexZ = "10" + package var vertex2X = "0", vertex2Y = "0", vertex2Z = "-10" package var depth = "10" package var endCondition = EndConditionUI.blind package var reverse = false @@ -91,6 +98,8 @@ extension AppModel { package func begin(_ op: Operation) { form.result = nil switch op { + case .moveBody: + form.target = selectedBodies.first ?? bodies.first?.id ?? "" case .plane: form.planeReference = selectedFace ?? "top" case .linearPattern, .circularPattern, .mirror: @@ -220,11 +229,17 @@ extension AppModel { let ec = p["end_condition"]?.stringValue ?? (p["direction"]?.stringValue == "mid_plane" ? "mid_plane" : "blind") form.endCondition = EndConditionUI(param: ec) ?? .blind form.depth = t(p["depth"]) ?? form.depth + if let v = p["vertex"]?.arrayValue, v.count == 3 { + form.vertexX = t(v[0]) ?? "0"; form.vertexY = t(v[1]) ?? "0"; form.vertexZ = t(v[2]) ?? "0" + } form.reverse = p["reverse"]?.boolValue ?? (p["direction"]?.stringValue == "reverse") if let d2 = p["direction2"], !d2.isNull { form.direction2 = true form.endCondition2 = EndConditionUI(param: d2["end_condition"]?.stringValue ?? "blind") ?? .blind form.depth2 = t(d2["depth"]) ?? form.depth2 + if let v = d2["vertex"]?.arrayValue, v.count == 3 { + form.vertex2X = t(v[0]) ?? "0"; form.vertex2Y = t(v[1]) ?? "0"; form.vertex2Z = t(v[2]) ?? "0" + } } else { form.direction2 = false } @@ -298,6 +313,24 @@ extension AppModel { form.draftReverse = p["reverse"]?.boolValue ?? false case .sweep, .cutSweep, .loft, .cutLoft, .rib: fillSweepLoftRib(op, p) + case .moveBody: + form.target = p["body"]?.stringValue ?? "" + form.bodyCopy = p["copy"]?.boolValue ?? false + let translation = p["translate"]?.arrayValue ?? [0, 0, 0] + if translation.count == 3 { form.bodyDX = t(translation[0]) ?? "0"; form.bodyDY = t(translation[1]) ?? "0"; form.bodyDZ = t(translation[2]) ?? "0" } + form.bodyRotation = p["rotate"] != nil && p["rotate"]?.isNull != true + form.bodyAngle = "90" + form.bodyAxis = "z" + form.bodyCustomAxis = [0, 0, 1] + form.bodyOriginX = "0"; form.bodyOriginY = "0"; form.bodyOriginZ = "0" + if let rotation = p["rotate"], !rotation.isNull { + form.bodyAngle = t(rotation["angle"]) ?? "0" + let axis = rotation["axis"]?.arrayValue ?? [0, 0, 1] + form.bodyAxis = axis == [1, 0, 0] ? "x" : axis == [0, 1, 0] ? "y" : axis == [0, 0, 1] ? "z" : "custom" + form.bodyCustomAxis = axis + if let origin = rotation["origin"]?.arrayValue, origin.count == 3 { form.bodyOriginX = t(origin[0]) ?? "0"; form.bodyOriginY = t(origin[1]) ?? "0"; form.bodyOriginZ = t(origin[2]) ?? "0" } + else { form.bodyOriginX = "0"; form.bodyOriginY = "0"; form.bodyOriginZ = "0" } + } case .combine: form.combine = p["operation"]?.stringValue ?? "fuse" form.target = p["target"]?.stringValue ?? "" @@ -332,7 +365,7 @@ extension AppModel { var params: JSONValue? switch op { case .extrude, .cutExtrude, .revolve, .cutRevolve, .hole, .plane, .primitive, .fillet, .chamfer, .shell, .draft, .linearPattern, - .circularPattern, .mirror, .combine, .sweep, .cutSweep, .loft, .cutLoft, .rib: + .circularPattern, .mirror, .combine, .moveBody, .sweep, .cutSweep, .loft, .cutLoft, .rib: params = featureEditParams(id, op) default: params = nil @@ -401,6 +434,7 @@ extension AppModel { guard let sk = operationSketch else { return nil } var p: [String: JSONValue] = ["sketch": .string(sk), "end_condition": .string(form.endCondition.param)] if form.endCondition.needsDepth { p["depth"] = quantity(form.depth) } + if form.endCondition == .upToVertex { p["vertex"] = [quantity(form.vertexX), quantity(form.vertexY), quantity(form.vertexZ)] } if form.reverse && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { p["reverse"] = true } if form.draftOn && !form.direction2 && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { var d: [String: JSONValue] = ["angle": angleQuantity(form.draftAngle)] @@ -416,6 +450,7 @@ extension AppModel { if form.direction2 && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { var d2: [String: JSONValue] = ["end_condition": .string(form.endCondition2.param)] if form.endCondition2 == .blind { d2["depth"] = quantity(form.depth2) } + if form.endCondition2 == .upToVertex { d2["vertex"] = [quantity(form.vertex2X), quantity(form.vertex2Y), quantity(form.vertex2Z)] } p["direction2"] = .object(d2) } if op == .cutExtrude { @@ -496,6 +531,14 @@ extension AppModel { "body": .string(String(body)), "neutral_plane": .string(form.draftNeutral), "faces": .array(form.draftFaces.map { .string($0) }), "angle": angleQuantity(form.draftFeatureAngle), "reverse": .bool(form.draftReverse), ])] + case .moveBody: + guard !form.target.isEmpty else { return nil } + var params: [String: JSONValue] = ["body": .string(form.target), "translate": [quantity(form.bodyDX), quantity(form.bodyDY), quantity(form.bodyDZ)], "copy": .bool(form.bodyCopy)] + if form.bodyRotation { + let axis: [JSONValue] = form.bodyAxis == "x" ? [1, 0, 0] : form.bodyAxis == "y" ? [0, 1, 0] : form.bodyAxis == "custom" ? form.bodyCustomAxis : [0, 0, 1] + params["rotate"] = ["axis": .array(axis), "angle": angleQuantity(form.bodyAngle), "origin": [quantity(form.bodyOriginX), quantity(form.bodyOriginY), quantity(form.bodyOriginZ)]] + } + return [Invocation("body.transform", .object(params))] case .combine: guard !form.target.isEmpty, !form.tool.isEmpty, form.target != form.tool else { return nil } return [Invocation("body.boolean", ["operation": .string(form.combine), "target": .string(form.target), "tool": .string(form.tool)])] @@ -679,7 +722,10 @@ extension AppModel { package var previewKey: String { guard let op = operation else { return "" } let f = form - return [op.title, operationSketch ?? "", f.depth, f.endCondition.rawValue, String(f.reverse), String(f.direction2), f.endCondition2.rawValue, f.depth2, + let placement = [f.bodyDX, f.bodyDY, f.bodyDZ, String(f.bodyCopy), String(f.bodyRotation), f.bodyAngle, f.bodyAxis, + JSONCoding.string(.array(f.bodyCustomAxis)), f.bodyOriginX, f.bodyOriginY, f.bodyOriginZ, + f.vertexX, f.vertexY, f.vertexZ, f.vertex2X, f.vertex2Y, f.vertex2Z].joined(separator: "|") + return [op.title, placement, operationSketch ?? "", f.depth, f.endCondition.rawValue, String(f.reverse), String(f.direction2), f.endCondition2.rawValue, f.depth2, String(f.merge), f.scope.joined(separator: ","), f.seeds.joined(separator: ","), f.linDirection, f.linSpacing, f.linCount, String(f.linReverse), String(f.linDirection2On), f.linDirection2, f.linSpacing2, f.linCount2, f.cirAxis, f.cirAngle, f.cirCount, String(f.cirEqual), String(f.cirReverse), f.mirrorPlane, f.holeType, f.holeSize, f.holeFit, f.holeEnd, f.holeDepth, String(f.holeReverse), String(f.draftOn), f.draftAngle, String(f.draftOutward), String(f.thinOn), f.thinType, @@ -733,12 +779,28 @@ extension AppModel { } package func computeMeasure() async { - let refs = selection.filter { !$0.hasPrefix("sketch-") } - guard refs.count == 2 else { + let refs = selection + guard (1...2).contains(refs.count) else { form.result = nil return } - form.result = try? await engine.execute("query.measure", ["from": .string(refs[0]), "to": .string(refs[1])]).result + let requestedSelection = selection + var params: [String: JSONValue] = ["from": .string(refs[0])] + if refs.count == 2 { params["to"] = .string(refs[1]) } + do { + let result = try await engine.execute("query.measure", .object(params)).result + guard selection == requestedSelection, operation == .measure else { return } + form.result = result + lastError = nil + } catch let error as ForgeError { + guard selection == requestedSelection, operation == .measure else { return } + form.result = nil + lastError = error + } catch { + guard selection == requestedSelection, operation == .measure else { return } + form.result = nil + lastError = ForgeError(.internalError, error.localizedDescription) + } } package func computeCheck() async { diff --git a/Sources/ForgeUI/RenameWorkflows.swift b/Sources/ForgeUI/RenameWorkflows.swift new file mode 100644 index 0000000..eba4136 --- /dev/null +++ b/Sources/ForgeUI/RenameWorkflows.swift @@ -0,0 +1,19 @@ +import ForgeCore + +extension AppModel { + /// Rename by stable identity through the same undoable command used by MCP. + /// Cancelling the native prompt does not submit a command or create an undo entry. + package func renameBody(_ id: String) async { + guard let body = bodies.first(where: { $0.id == id }), + let name = platform.requestName("Rename Body", currentName: body.name) else { return } + guard name != body.name else { return } + await run("body.rename", ["body": .string(id), "name": .string(name)]) + } + + package func renameFeature(_ id: String) async { + guard let feature = features.first(where: { $0.id == id }), + let name = platform.requestName("Rename Feature", currentName: feature.name) else { return } + guard name != feature.name else { return } + await run("feature.rename", ["feature": .string(id), "name": .string(name)]) + } +} diff --git a/Sources/ForgeUI/RibbonSpec.swift b/Sources/ForgeUI/RibbonSpec.swift index aec674f..fb566ef 100644 --- a/Sources/ForgeUI/RibbonSpec.swift +++ b/Sources/ForgeUI/RibbonSpec.swift @@ -47,6 +47,11 @@ extension AppModel { let hasSketch = !sketches.isEmpty, hasBody = !bodies.isEmpty let o = operation return [ + RibbonGroupSpec(title: "Sketch", buttons: [ + button("startSketch", .sketch, sketchStartTitle, help: "Start a sketch on the selected planar face; use the Sketch tab to choose another plane", enabled: activeSketch == nil) { [unowned self] in + Task { await startSketchFromSelection() } + }, + ]), RibbonGroupSpec(title: "Boss / Base", buttons: [ button("extrude", .extrude, "Extruded Boss/Base", help: "Extrude a closed sketch profile into a new body", active: o == .extrude, enabled: hasSketch, op(.extrude)), button("revolve", .revolve, "Revolved Boss/Base", help: "Revolve a sketch profile about a sketch line", active: o == .revolve, enabled: hasSketch, op(.revolve)), @@ -67,6 +72,7 @@ extension AppModel { enabled: sketches.count >= 2 && hasBody, large: false, op(.cutLoft)), ]), RibbonGroupSpec(title: "Modify", buttons: [ + button("moveBody", .move, "Move/Copy Bodies", enabled: hasBody, large: false, op(.moveBody)), button("fillet", o == .chamfer ? .chamfer : .fillet, o == .chamfer ? "Chamfer" : "Fillet", active: o == .fillet || o == .chamfer, enabled: hasBody, variants: [("Fillet", op(.fillet)), ("Chamfer", op(.chamfer))], op(o == .chamfer ? .chamfer : .fillet)), button("rib", .rib, "Rib", help: "A wall from an open sketch profile, extended to meet the body", active: o == .rib, enabled: hasSketch && hasBody, @@ -88,6 +94,13 @@ extension AppModel { RibbonGroupSpec(title: "Reference", buttons: [ button("plane", .plane, "Reference Geometry", active: o == .plane, variants: [("Plane", op(.plane))], op(.plane)), ]), + RibbonGroupSpec(title: "Visibility", buttons: [ + button("hideBodies", .hideShow, "Hide Bodies", enabled: !selectedBodies.isEmpty, large: false) { [unowned self] in Task { await setBodiesVisible(selectedBodies, false) } }, + button("showBodies", .hideShow, "Show Bodies", enabled: !selectedBodies.isEmpty, large: false) { [unowned self] in Task { await setBodiesVisible(selectedBodies, true) } }, + button("isolateBodies", .part, "Isolate Bodies", active: isIsolatingBodies, enabled: !selectedBodies.isEmpty, large: false) { [unowned self] in Task { await isolateBodies(selectedBodies) } }, + button("exitIsolation", .part, "Exit Isolation", enabled: isIsolatingBodies, large: false) { [unowned self] in Task { await exitBodyIsolation() } }, + button("showAllBodies", .hideShow, "Show All Bodies", enabled: !hiddenBodyIDs.isEmpty || isIsolatingBodies, large: false) { [unowned self] in Task { await showAllBodies() } }, + ]), RibbonGroupSpec(title: "Primitives", buttons: Primitive.allCases.map { p in button("prim-" + p.rawValue, p.icon, p.title, active: o == .primitive(p), large: false, op(.primitive(p))) }), @@ -118,8 +131,8 @@ extension AppModel { if editing { sketchButton = button("exitSketch", .exitSketch, "Exit Sketch", help: "Finish editing the sketch") { [unowned self] in Task { await exitSketch() } } } else { - sketchButton = button("sketch", .sketch, "Sketch", help: "Start a sketch on a plane (or the selected face)", variants: planes) { [unowned self] in - Task { await newSketch(onPlaneOrFace: selectedFace ?? "front") } + sketchButton = button("sketch", .sketch, sketchStartTitle, help: "Start a sketch on a plane (or the selected face)", variants: planes) { [unowned self] in + Task { await startSketchFromSelection() } } } func kinds(_ key: WritableKeyPath, _ t: SketchTool) -> [(title: String, action: () -> Void)] @@ -150,6 +163,11 @@ extension AppModel { }, ]), RibbonGroupSpec(title: "Tools", buttons: [ + button("selectModelGeometry", .sketch, "Select Model Geometry", help: "Stop drawing to select body edges or faces for Convert Entities", enabled: editing, large: false) { [unowned self] in selectModelGeometry() }, + button("splitEntities", .trim, "Split Entities", help: "Split lines and arcs with one click; circles and ellipses with two", active: st.tool == .split, enabled: editing, large: false, tool(.split)), + button("convertEntities", .sketch, "Convert Entities", help: "Project selected edges or face boundaries into this sketch as fixed copies; copies do not follow later model edits", enabled: editing && !selectedModelGeometry.isEmpty, large: false) { [unowned self] in + Task { await convertSelectedModelGeometry() } + }, button("sketchFillet", st.tool == .chamfer ? .sketchChamfer : .sketchFillet, st.tool == .chamfer ? "Sketch Chamfer" : "Sketch Fillet", active: st.tool == .fillet || st.tool == .chamfer, enabled: editing, variants: [("Sketch Fillet", { [unowned self] in chooseTool(.fillet) }), ("Sketch Chamfer", { [unowned self] in chooseTool(.chamfer) })], diff --git a/Sources/ForgeUI/SketchMode.swift b/Sources/ForgeUI/SketchMode.swift index f3a9d22..3782284 100644 --- a/Sources/ForgeUI/SketchMode.swift +++ b/Sources/ForgeUI/SketchMode.swift @@ -13,7 +13,7 @@ import Foundation /// SketchUIState and show it in their PropertyManager page, as SolidWorks does. package enum SketchTool: String, CaseIterable, Identifiable { case line, rectangle, circle, arc, slot, polygon, spline, ellipse, point - case fillet, chamfer, trim, extend, dimension + case fillet, chamfer, trim, extend, split, dimension package var id: String { rawValue } package var title: String { @@ -31,6 +31,7 @@ package enum SketchTool: String, CaseIterable, Identifiable { case .chamfer: "Sketch Chamfer" case .trim: "Trim Entities" case .extend: "Extend Entities" + case .split: "Split Entities" case .dimension: "Smart Dimension" } } @@ -50,6 +51,7 @@ package enum SketchTool: String, CaseIterable, Identifiable { case .chamfer: .sketchChamfer case .trim: .trim case .extend: .extend + case .split: .trim case .dimension: .smartDimension } } @@ -62,7 +64,7 @@ package enum RectangleType: String, CaseIterable { } package enum CircleType: String, CaseIterable { case center = "Circle", perimeter = "Perimeter Circle" } package enum ArcType: String, CaseIterable { case center = "Centerpoint Arc", tangent = "Tangent Arc", threePoint = "3 Point Arc" } -package enum SlotType: String, CaseIterable { case straight = "Straight Slot", center = "Centerpoint Straight Slot" } +package enum SlotType: String, CaseIterable { case straight = "Straight Slot", center = "Centerpoint Straight Slot", arc = "Centerpoint Arc Slot", threePointArc = "3 Point Arc Slot" } package enum EllipseType: String, CaseIterable { case full = "Ellipse", partial = "Partial Ellipse" } package enum ChamferType: String, CaseIterable { case angleDistance = "Angle-distance", distanceDistance = "Distance-distance" } package enum TrimMode: String, CaseIterable { case power = "Power trim", closest = "Trim to closest" } @@ -99,6 +101,8 @@ package struct SketchUIState { package var pending: [Point2] = [] /// Ids of existing points the pending clicks landed on (for relations such as midpoint). package var pendingTargets: [String?] = [] + /// Closed curve awaiting the second split point; Escape cancels this pending split. + package var splitEntity: String? /// First point of the current line chain: clicking it again closes the chain. package var chainStart: Point2? package var preview: SketchPreview? @@ -232,6 +236,7 @@ extension AppModel { package func chooseTool(_ tool: SketchTool?) { sketchState.tool = tool + sketchState.splitEntity = nil sketchState.pending = [] sketchState.pendingTargets = [] sketchState.chainStart = nil @@ -242,6 +247,13 @@ extension AppModel { clearPreview() } + /// Changing slot construction changes the meaning and number of collected clicks. + package func chooseSlotType(_ type: SlotType) { + guard sketchState.slotType != type else { return } + resetPending() + sketchState.slotType = type + } + package func clearPreview() { sketchState.preview = nil hoverLines = [] @@ -361,7 +373,24 @@ extension AppModel { } } case .slot: - if pending.count == 1 { + if sketchState.slotType == .arc || sketchState.slotType == .threePointArc { + if pending.count < 3 { + if pending.count == 1 { pv.polylines = [[pending[0], p]] } + if pending.count == 2 { + if sketchState.slotType == .arc { + if let g = arcSlotGeometry(pending + [p]) { + pv.polylines = [Self.arcSlotOutline(g.center, g.radius, g.startAngle, g.sweep, 0)] + } + } else { pv.polylines = [Self.arcThrough(pending[0], p, pending[1])] } + } + } else if let g = arcSlotGeometry(pending) { + let halfWidth = abs(hypot(p.u - g.center.u, p.v - g.center.v) - g.radius) + if halfWidth < g.radius { + pv.polylines = [Self.arcSlotOutline(g.center, g.radius, g.startAngle, g.sweep, halfWidth)] + } + lines = ["W \(fmt(2 * halfWidth))"] + } + } else if pending.count == 1 { let a = sketchState.slotType == .center ? Point2(2 * pending[0].u - p.u, 2 * pending[0].v - p.v) : pending[0] pv.polylines = [[a, p]] lines = ["L \(fmt(hypot(p.u - a.u, p.v - a.v)))"] @@ -402,6 +431,11 @@ extension AppModel { pv.polylines = [Self.ellipsePolyline(c, a, b, rot)] lines = pending.count == 2 ? ["a \(fmt(a))", "b \(fmt(b))"] : ["Click the end of the arc"] } + case .split: + if let first = pending.first { + pv.marker = first + lines = ["Click a second point on the same closed curve"] + } case .point, .fillet, .chamfer, .trim, .extend, .dimension: break } @@ -504,6 +538,48 @@ extension AppModel { return out + [out[0]] } + /// Resolve the centerline before the width click. Center arcs project the end + /// click to the radius established by the start, matching the ordinary arc tool. + package func arcSlotGeometry(_ points: [Point2]) -> (center: Point2, radius: Double, start: Point2, end: Point2, startAngle: Double, sweep: Double)? { + guard points.count == 3 else { return nil } + let c: Point2, start: Point2, end: Point2, r: Double + if sketchState.slotType == .arc { + c = points[0]; start = points[1] + r = hypot(start.u - c.u, start.v - c.v) + let d = hypot(points[2].u - c.u, points[2].v - c.v) + guard r > 1e-9, d > 1e-9 else { return nil } + end = Point2(c.u + r * (points[2].u - c.u) / d, c.v + r * (points[2].v - c.v) / d) + } else { + guard let cc = try? Sketch.circumcircle(points[0].tuple, points[2].tuple, points[1].tuple) else { return nil } + c = Point2(cc.center.0, cc.center.1); r = cc.radius + start = points[0]; end = points[1] + } + let a0 = atan2(start.v - c.v, start.u - c.u) + func ccw(_ point: Point2) -> Double { + var angle = atan2(point.v - c.v, point.u - c.u) - a0 + while angle < 0 { angle += 2 * .pi } + return angle + } + var sweep = ccw(end) + if sketchState.slotType == .threePointArc, ccw(points[2]) > sweep { sweep -= 2 * .pi } + guard abs(sweep) > 1e-9 else { return nil } + return (c, r, start, end, a0, sweep) + } + + package static func arcSlotOutline(_ c: Point2, _ r: Double, _ a0: Double, _ sweep: Double, _ halfWidth: Double) -> [Point2] { + let sign = sweep > 0 ? 1.0 : -1.0 + func point(_ center: Point2, _ radius: Double, _ angle: Double) -> Point2 { + Point2(center.u + radius * cos(angle), center.v + radius * sin(angle)) + } + var out = (0...48).map { point(c, r + halfWidth, a0 + sweep * Double($0) / 48) } + let end = point(c, r, a0 + sweep) + out += (1...24).map { point(end, halfWidth, a0 + sweep + sign * .pi * Double($0) / 24) } + out += (1...48).map { point(c, r - halfWidth, a0 + sweep * (1 - Double($0) / 48)) } + let start = point(c, r, a0) + out += (1...24).map { point(start, halfWidth, a0 + sign * .pi + sign * .pi * Double($0) / 24) } + return out + } + /// Polyline of the arc from a to b passing through m (a straight segment if collinear). package static func arcThrough(_ a: Point2, _ m: Point2, _ b: Point2) -> [Point2] { guard let cc = try? Sketch.circumcircle(a.tuple, m.tuple, b.tuple) else { return [a, b] } @@ -743,7 +819,22 @@ extension AppModel { } case .slot: sketchState.pending.append(p) - if sketchState.pending.count == 3 { + if sketchState.slotType == .arc || sketchState.slotType == .threePointArc { + if sketchState.pending.count == 4 { + let points = sketchState.pending + resetPending() + guard let g = arcSlotGeometry(Array(points.prefix(3))) else { + lastError = ForgeError(.invalidParams, "The slot centerline needs a nonzero arc; three-point slots need noncollinear points.") + return + } + let w = 2 * abs(hypot(p.u - g.center.u, p.v - g.center.v) - g.radius) + var params: [String: JSONValue] = ["mode": .string(sketchState.slotType == .arc ? "center" : "three_point"), + "start": pt(g.start), "end": pt(g.end), "width": .number(w), "construction": construction] + if sketchState.slotType == .arc { params["center"] = pt(g.center) } + else { params["through"] = pt(points[2]) } + await run("sketch.add_arc_slot", .object(params)) + } + } else if sketchState.pending.count == 3 { let (p0, p1) = (sketchState.pending[0], sketchState.pending[1]) let (a, b) = slotCentres(p0, p1) resetPending() @@ -751,7 +842,7 @@ extension AppModel { if w > 0 { let mode = sketchState.slotType == .center ? "center" : "straight" let start = sketchState.slotType == .center ? p0 : a - await run("sketch.add_slot", ["mode": .string(mode), "start": pt(start), "end": pt(b), "width": .number(w)]) + await run("sketch.add_slot", ["mode": .string(mode), "start": pt(start), "end": pt(b), "width": .number(w), "construction": construction]) } } case .polygon: @@ -825,6 +916,27 @@ extension AppModel { } else { await run("sketch.extend", ["entity": .string(local), "near": pt(raw)]) } + case .split: + guard let local, let sketch = sketchState.sketch, let entity = sketch.entities[local], + curve?.contains("/") != true || curve?.hasPrefix(sketch.id + "/") == true else { + lastError = ForgeError(.invalidParams, "Click a curve in the active sketch to split it.") + return + } + if let pendingEntity = sketchState.splitEntity, pendingEntity != local { + lastError = ForgeError(.invalidParams, "Click the second point on the same closed curve, or press Esc to cancel.", entities: [pendingEntity]) + return + } + if entity.kind == .circle || entity.kind == .ellipse { + if let first = sketchState.pending.first { + if await run("sketch.split", ["entity": .string(local), "at": [pt(first), pt(raw)]]) != nil { resetPending() } + } else { + sketchState.splitEntity = local + sketchState.pending = [raw] + lastError = nil + } + } else { + await run("sketch.split", ["entity": .string(local), "at": [pt(raw)]]) + } case .dimension: await dimensionClick(snap.kind == .point ? snap.target : local, at: raw, viewPoint: viewPoint) return @@ -843,6 +955,7 @@ extension AppModel { } private func resetPending() { + sketchState.splitEntity = nil sketchState.pending = [] sketchState.pendingTargets = [] sketchState.chainStart = nil @@ -899,7 +1012,13 @@ extension AppModel { case .tangent: return "Click the end of a line or arc, then where the arc ends." case .threePoint: return "Click the start, the end, then a point the arc passes through." } - case .slot: return st.slotType == .straight ? "Click the two arc centres, then the width." : "Click the slot centre, an arc centre, then the width." + case .slot: + switch st.slotType { + case .straight: return "Click the two arc centres, then the width." + case .center: return "Click the slot centre, an arc centre, then the width." + case .arc: return "Click the centre, start, end (counter-clockwise), then the width." + case .threePointArc: return "Click the start, end, a point on the arc, then the width." + } case .polygon: return "Click the centre, then a vertex (inscribed) or the middle of a side (circumscribed)." case .spline: return "Click the points the spline passes through; double-click to finish." case .ellipse: @@ -911,6 +1030,10 @@ extension AppModel { case .chamfer: return "Click a corner where two lines meet." case .trim: return st.trimMode == .power ? "Drag across the pieces to remove, or click them." : "Click the piece of a curve to remove." case .extend: return "Click a curve near the end to extend it to the next curve." + case .split: + return st.splitEntity == nil + ? "Click inside a line or arc to split it. On a circle or ellipse, click two different points." + : "Click a second point on the same closed curve, or press Esc to cancel." case .dimension: if let e = dimensionEdit, !e.placed { return e.measurement == nil ? "Click a second entity to dimension to." : "Move the pointer to where the dimension goes and click to place it (or click a second entity)." diff --git a/Sources/ForgeUI/SketchPlacementWorkflows.swift b/Sources/ForgeUI/SketchPlacementWorkflows.swift new file mode 100644 index 0000000..a66ac27 --- /dev/null +++ b/Sources/ForgeUI/SketchPlacementWorkflows.swift @@ -0,0 +1,46 @@ +import ForgeCore +import ForgeCommands + +extension AppModel { + package var sketchStartTitle: String { + if selectedFace != nil { return "Sketch on Face" } + if selection.contains(where: { $0.hasPrefix("plane-") }) { return "Sketch on Plane" } + return "Sketch" + } + + /// A generic Sketch action respects the picked face. An unsuitable model selection must + /// never silently create a sketch on the origin's Front plane. + package func startSketchFromSelection() async { + guard activeSketch == nil else { return } + if let face = selectedFace { + await newSketch(onPlaneOrFace: face) + } else if let plane = selection.last(where: { $0.hasPrefix("plane-") }) { + if let standard = StandardPlane(rawValue: String(plane.dropFirst(6))) { + await newSketch(on: standard) + } else { + await newSketch(onPlaneOrFace: plane) + } + } else if !selection.isEmpty { + lastError = ForgeError(.invalidParams, "Select a planar face or reference plane to start a sketch, or choose a plane from the Sketch menu.", entities: selection) + } else { + await newSketch(on: .front) + } + } + + package var selectedModelGeometry: [String] { + selection.filter { entityKind($0) == .edge || entityKind($0) == .face } + } + + /// With no sketch drawing tool active, both native viewports pick model faces and edges. + package func selectModelGeometry() { + chooseTool(nil) + contextToolbarAt = nil + } + + package func convertSelectedModelGeometry() async { + guard activeSketch != nil, !selectedModelGeometry.isEmpty else { return } + let refs = selectedModelGeometry + chooseTool(nil) + await run("sketch.convert_entities", ["entities": .array(refs.map(JSONValue.string))]) + } +} diff --git a/Sources/ForgeUI/TreeSpec.swift b/Sources/ForgeUI/TreeSpec.swift index 1fca0d8..70b820a 100644 --- a/Sources/ForgeUI/TreeSpec.swift +++ b/Sources/ForgeUI/TreeSpec.swift @@ -55,20 +55,27 @@ extension AppModel { if !bodies.isEmpty { let kids = bodies.filter { matches($0.name) }.map { b in TreeNode( - id: b.id, icon: .part, title: b.name, tooltip: "\(b.name): \(b.topology.faces) faces, \(String(format: "%.1f", b.volumeMM3)) mm³", + id: b.id, icon: hiddenBodyIDs.contains(b.id) ? .hideShow : .part, title: b.name + (hiddenBodyIDs.contains(b.id) ? " (Hidden)" : ""), tooltip: "\(b.name): \(b.topology.faces) faces, \(String(format: "%.1f", b.volumeMM3)) mm³", selected: selection.contains(b.id), select: { [unowned self] extend in Task { await select(b.id, extend: extend) } }, menu: [ + (hiddenBodyIDs.contains(b.id) ? "Show Body" : "Hide Body", { [unowned self] in Task { await setBodiesVisible([b.id], hiddenBodyIDs.contains(b.id)) } }), + ("Isolate Body", { [unowned self] in Task { await isolateBodies([b.id]) } }), + ("Rename…", { [unowned self] in Task { await renameBody(b.id) } }), ("Mass Properties", { [unowned self] in Task { await select(b.id, extend: false); begin(.massProperties) } }), ("Export STEP…", { [unowned self] in Task { await select(b.id, extend: false); export("step") } }), ("Export STL…", { [unowned self] in Task { await select(b.id, extend: false); export("stl") } }), ]) } - out.append(TreeNode(id: "bodies", icon: .folder, title: "Solid Bodies (\(bodies.count))", children: kids)) + var menu: [(title: String, action: () -> Void)] = [("Show All Bodies", { [unowned self] in Task { await showAllBodies() } })] + if isIsolatingBodies { menu.append(("Exit Isolation", { [unowned self] in Task { await exitBodyIsolation() } })) } + out.append(TreeNode(id: "bodies", icon: .folder, title: "Solid Bodies (\(bodies.count))", children: kids, menu: menu)) } for p in StandardPlane.allCases where matches(p.rawValue + " plane") { let name = "\(p.rawValue.capitalized) Plane" out.append(TreeNode( id: "plane-" + p.rawValue, icon: .plane, title: name, tooltip: "Double-click to sketch on this plane", + selected: selection.contains("plane-" + p.rawValue), + select: { [unowned self] extend in Task { await select("plane-" + p.rawValue, extend: extend) } }, activate: { [unowned self] in Task { await newSketch(on: p) } }, menu: [("Sketch on \(name)", { [unowned self] in Task { await newSketch(on: p) } })])) } if matches("origin") { out.append(TreeNode(id: "origin", icon: .origin, title: "Origin")) } @@ -104,6 +111,7 @@ extension AppModel { private func sketchNode(_ s: SketchRow, feature: FeatureRow?) -> TreeNode { let prefix = s.status == .underDefined ? "(-) " : s.status == .redundant || s.status == .conflicting ? "(+) " : s.status == .failed ? "(?) " : "" var menu: [(title: String, action: () -> Void)] = [("Edit Sketch", { [unowned self] in Task { await editSketch(s.id) } })] + if let feature { menu.append(("Rename…", { [unowned self] in Task { await renameFeature(feature.id) } })) } if let feature { menu.append(("Delete", { [unowned self] in Task { await run("feature.delete", ["feature": .string(feature.id)]) } })) } return TreeNode( id: s.id, icon: .sketch, title: prefix + s.name, selected: selection.contains(s.id) || activeSketch == s.id, @@ -126,6 +134,7 @@ extension AppModel { menu.append((f.suppressed ? "Unsuppress" : "Suppress", { [unowned self] in Task { await run("feature.suppress", ["feature": .string(f.id), "suppressed": .bool(!f.suppressed)]) } })) + menu.append(("Rename…", { [unowned self] in Task { await renameFeature(f.id) } })) menu.append(("Parent/Child…", { [unowned self] in Task { await showFeatureDependencies(f.id) } })) if rollback == nil, let index = features.firstIndex(where: { $0.id == f.id }) { if index > 0 { menu.append(("Move Up", { [unowned self] in Task { await moveFeature(f.id, by: -1) } })) } @@ -148,17 +157,19 @@ extension AppModel { let bodySelected = f.createdBodies.contains { selection.contains($0) } return TreeNode( id: f.id, icon: f.icon, title: f.name, tooltip: f.error ?? "", selected: bodySelected, state: state, children: children, - select: { [unowned self] _ in treeSelect(f) }, activate: { [unowned self] in treeActivate(f) }, menu: menu) + select: { [unowned self] extend in treeSelect(f, extend: extend) }, activate: { [unowned self] in treeActivate(f) }, menu: menu) } /// Click on a feature: toggles it as a seed while a pattern or mirror is open, otherwise /// selects its bodies. - package func treeSelect(_ f: FeatureRow) { + package func treeSelect(_ f: FeatureRow, extend: Bool = false) { if let op = operation, [Operation.linearPattern, .circularPattern, .mirror].contains(op), !f.isSketch { if let i = form.seeds.firstIndex(of: f.id) { form.seeds.remove(at: i) } else { form.seeds.append(f.id) } return } - if !f.createdBodies.isEmpty && f.command != "plane.create" { + if f.command == "plane.create", let plane = f.createdBodies.first { + Task { await select(plane, extend: extend) } + } else if !f.createdBodies.isEmpty { Task { await select(f.createdBodies) } } } diff --git a/Sources/ForgeWin/WinShell.swift b/Sources/ForgeWin/WinShell.swift index e23a4c7..1b2175b 100644 --- a/Sources/ForgeWin/WinShell.swift +++ b/Sources/ForgeWin/WinShell.swift @@ -309,7 +309,7 @@ final class WinShell { private func pushMenus() { guard let app else { return } - let (display, style, canNormal) = observe({ (model.display, viewport?.style ?? .shadedWithEdges, model.activeSketch != nil) }) { $0.dirtyMenus = true } + let (display, style, canNormal) = observe({ (model.display, viewport?.style ?? .shadedWithEdges, model.canNormalTo) }) { $0.dirtyMenus = true } fw_set_menu_check(app, Int32(FW_MENU_PERSPECTIVE), display.perspective ? 1 : 0) fw_set_menu_check(app, Int32(FW_MENU_PLANES), display.planes ? 1 : 0) fw_set_menu_check(app, Int32(FW_MENU_RELATIONS), display.relations ? 1 : 0) @@ -452,6 +452,12 @@ final class WinPlatform: PlatformServices { fw_confirm(app, title, message, confirm, cancel) != 0 } + func requestName(_ title: String, currentName: String) -> String? { + guard let p = fw_name_dialog(app, title, currentName) else { return nil } + defer { fw_free(p) } + return String(cString: p) + } + func chooseSavePath(suggestedName name: String) -> String? { guard let p = fw_save_dialog(app, name) else { return nil } defer { fw_free(p) } diff --git a/Tests/ForgeCommandsTests/ArcSlotTests.swift b/Tests/ForgeCommandsTests/ArcSlotTests.swift new file mode 100644 index 0000000..af45351 --- /dev/null +++ b/Tests/ForgeCommandsTests/ArcSlotTests.swift @@ -0,0 +1,155 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeCommands + +@Suite("Arc slot commands") +struct ArcSlotTests { + private func engine() async throws -> Engine { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("sketch.create", ["plane": "front"]) + return engine + } + + private func area(_ engine: Engine) async throws -> Double { + let result = try await engine.execute("sketch.check").result + #expect(result["valid"] == true) + return try #require(result["region_area_mm2"]?.doubleValue) + } + + @Test func centerAndThreePointSlotsHaveAnalyticAreasAndSixDegreesOfFreedom() async throws { + let cases: [(JSONValue, Double)] = [ + (["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4], .pi / 2), + (["center": [0, 0], "start": [20, 0], "end": [0, -20], "width": 4, "clockwise": true], .pi / 2), + (["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4, "clockwise": true], 3 * .pi / 2), + (["mode": "three_point", "start": [20, 0], "end": [-20, 0], "through": [0, 20], "width": 4], .pi), + (["mode": "three_point", "start": [20, 0], "end": [0, 20], "through": [-20, 0], "width": 4], 3 * .pi / 2), + ] + for (params, sweep) in cases { + let e = try await engine() + let result = try await e.execute("sketch.add_arc_slot", params).result + #expect(result["created"]?.arrayValue?.count == 5) + #expect(result["sketch"]?["dof"] == 6) + #expect(result["sketch"]?["status"] == "under_defined") + // Annular strip: (Ro²-Ri²)*theta/2 = R*w*theta. Two semicaps add pi*(w/2)². + let expected = 20 * 4 * sweep + .pi * 4 + #expect(abs(try await area(e) - expected) < 1e-7) + try await e.execute("sketch.exit") + try await e.execute("body.extrude", ["sketch": "sketch-1", "depth": 3]) + let mass = try await e.execute("query.mass_properties", ["body": "body-1"]).result + #expect(abs(try #require(mass["volume_mm3"]?.doubleValue) - expected * 3) < 1e-6) + } + } + + @Test func widthDimensionPreservesConcentricSidesAndSemicircularCaps() async throws { + let e = try await engine() + let slot = try await e.execute("sketch.add_arc_slot", ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4]).result + let created = try #require(slot["created"]?.arrayValue) + // Fix the five centreline parameters, leaving exactly the slot width free. + let fixed = try await e.execute("sketch.add_relation", ["type": "fix", "entities": [created[4]]]).result + #expect(fixed["sketch"]?["dof"] == 1) + let width = try await e.execute("sketch.add_dimension", ["type": "diameter", "entities": [created[1]], "value": 4]).result + #expect(width["sketch"]?["dof"] == 0) + let dimension = try #require(width["constraints"]?.arrayValue?.first) + try await e.execute("sketch.set_dimension", ["constraint": dimension, "value": 8]) + #expect(abs(try await area(e) - 96 * .pi) < 1e-6) + try await e.execute("edit.undo") + #expect(abs(try await area(e) - 44 * .pi) < 1e-6) + try await e.execute("edit.redo") + #expect(abs(try await area(e) - 96 * .pi) < 1e-6) + } + + @Test func rotatedTranslatedSlotsKeepCapCentersOnCenterlineWhileWidthChanges() async throws { + for rotation in [0.37, 1.21, Double.pi / 4 - 0.9 - 1e-7, Double.pi / 4 - 0.9 + 1e-7, -0.9 + 1e-8, Double.pi / 2 - 0.9 - 1e-8] { + let e = try await engine() + func point(_ angle: Double) -> JSONValue { + .array([.number(43 + 20 * cos(angle)), .number(-17 + 20 * sin(angle))]) + } + let slot = try await e.execute("sketch.add_arc_slot", ["center": [43, -17], "start": point(rotation), "end": point(rotation + 0.9), "width": 4]).result + let ids = try #require(slot["created"]?.arrayValue) + #expect(slot["sketch"]?["dof"] == 6) + let rotated = try await e.execute("sketch.rotate", ["entities": .array(ids), "center": [43, -17], "angle": "90 deg", "keep_relations": true]).result + #expect(rotated["sketch"]?["dof"] == 6) + #expect(rotated["sketch"]?["status"] == "under_defined") + let fixed = try await e.execute("sketch.add_relation", ["type": "fix", "entities": [ids[4]]]).result + #expect(fixed["sketch"]?["dof"] == 1) + let dimension = try await e.execute("sketch.add_dimension", ["type": "diameter", "entities": [ids[1]], "value": 4]).result + #expect(dimension["sketch"]?["dof"] == 0) + let constraint = try #require(dimension["constraints"]?.arrayValue?.first) + try await e.execute("sketch.set_dimension", ["constraint": constraint, "value": 8]) + #expect(abs(try await area(e) - (20 * 8 * 0.9 + 16 * .pi)) < 1e-6) + let entities = try #require(try await e.execute("sketch.get").result["entities"]?.arrayValue) + let axis = try #require(entities.first { $0["id"] == ids[4] }) + for (index, endpoint) in [(1, "end"), (3, "start")] { + let cap = try #require(entities.first { $0["id"] == ids[index] }) + for coordinate in 0..<2 { + let actual = try #require(cap["center"]?[coordinate]?.doubleValue) + let expected = try #require(axis[endpoint]?[coordinate]?.doubleValue) + #expect(abs(actual - expected) < 1e-7) + } + } + } + } + + @Test func straightSlotsSupportConstructionInBothModes() async throws { + for mode in ["straight", "center"] { + let e = try await engine() + let result = try await e.execute("sketch.add_slot", ["mode": .string(mode), "start": [0, 0], "end": [20, 0], "width": 4, "construction": true]).result + let ids = try #require(result["created"]?.arrayValue) + let entities = try #require(try await e.execute("sketch.get").result["entities"]?.arrayValue) + #expect(entities.filter { ids.contains($0["id"] ?? .null) }.allSatisfy { $0["construction"] == true }) + } + } + + @Test func invalidSlotsAreRejectedWithoutMutatingTheSketch() async throws { + let e = try await engine() + let before = try await e.execute("sketch.get").result + let invalid: [JSONValue] = [ + ["start": [20, 0], "end": [0, 20], "width": 4], + ["center": [0, 0], "start": [20, 0], "end": [0, 21], "width": 4], + ["center": [0, 0], "start": [20, 0], "end": [20, 0], "width": 4], + ["center": [0, 0], "start": [0, 0], "end": [0, 0], "width": 4], + ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 40], + ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": -1], + ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4, "through": [10, 10]], + ["mode": "three_point", "start": [0, 0], "end": [20, 0], "through": [10, 0], "width": 4], + ["mode": "three_point", "start": [20, 0], "end": [0, 20], "through": [-20, 0], "width": 4, "clockwise": false], + // A 354-degree sweep leaves insufficient clearance for the 4 mm rounded ends. + ["center": [0, 0], "start": [20, 0], "end": [19.900083305560518, -1.996668332936563], "width": 4], + ] + for params in invalid { + do { + try await e.execute("sketch.add_arc_slot", params) + Issue.record("Invalid arc slot was accepted: \(params)") + } catch let error as ForgeError { #expect(error.code == .invalidParams) } + #expect(try await e.execute("sketch.get").result == before) + } + } + + @Test func unitAwareDryRunConstructionAndPersistence() async throws { + let e = try await engine() + let params: JSONValue = ["center": ["1 in", "1 in"], "start": ["2 in", "1 in"], "end": ["1 in", "2 in"], "width": "0.1 in"] + let before = try await e.execute("sketch.get").result + try await e.execute("sketch.add_arc_slot", params, dryRun: true) + #expect(try await e.execute("sketch.get").result == before) + try await e.execute("sketch.add_arc_slot", params) + let expected = 25.4 * 2.54 * .pi / 2 + .pi * pow(1.27, 2) + #expect(abs(try await area(e) - expected) < 1e-6) + let path = FileManager.default.temporaryDirectory.appendingPathComponent("forge-arc-slot-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: path) } + try await e.execute("sketch.exit") + try await e.execute("body.extrude", ["sketch": "sketch-1", "depth": 5]) + try await e.execute("document.save", ["path": .string(path.path)]) + try await e.execute("document.new") + try await e.execute("document.open", ["path": .string(path.path)]) + try await e.execute("document.regenerate") + let mass = try await e.execute("query.mass_properties", ["body": "body-1"]).result + #expect(abs(try #require(mass["volume_mm3"]?.doubleValue) - expected * 5) < 1e-5) + let construction = try await engine() + let result = try await construction.execute("sketch.add_arc_slot", ["center": [0, 0], "start": [20, 0], "end": [0, 20], "width": 4, "construction": true]).result + let ids = try #require(result["created"]?.arrayValue) + let entities = try #require(try await construction.execute("sketch.get").result["entities"]?.arrayValue) + #expect(entities.filter { ids.contains($0["id"] ?? .null) }.allSatisfy { $0["construction"] == true }) + } +} diff --git a/Tests/ForgeCommandsTests/FeatureTreeTests.swift b/Tests/ForgeCommandsTests/FeatureTreeTests.swift index 16eed0b..e89cbba 100644 --- a/Tests/ForgeCommandsTests/FeatureTreeTests.swift +++ b/Tests/ForgeCommandsTests/FeatureTreeTests.swift @@ -229,6 +229,22 @@ struct AppliedFeatureTests { @Suite("Reference planes and sketches on faces") struct ReferencePlaneTests { + @Test func planeSelectionSurvivesRebuildAndPrunesOnlyLostSupport() async throws { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("plane.create", ["reference": "top", "offset": 20]) + try await engine.execute("body.create_box", ["width": 10, "height": 20, "depth": 30]) + try await engine.execute("selection.set", ["entities": ["plane-front", "plane-1"]]) + try await engine.execute("document.regenerate") + #expect(await engine.activeDocument?.selection == ["plane-front", "plane-1"]) + try await engine.execute("feature.edit", ["feature": "feature-1", "params": ["offset": 40]]) + #expect(await engine.activeDocument?.selection == ["plane-front", "plane-1"]) + try await engine.execute("feature.suppress", ["feature": "feature-1", "suppressed": true]) + #expect(await engine.activeDocument?.selection == ["plane-front"]) + #expect(await engine.activeDocument?.referenceExists("plane-1") == false) + #expect(await engine.activeDocument?.referenceExists("plane-missing") == false) + } + func topFace(_ e: Engine, _ body: String = "body-1") async throws -> String { let faces = try await e.execute("query.faces", ["body": .string(body)]).result["faces"]!.arrayValue! return faces.first { $0["normal"]!.arrayValue!.map { $0.doubleValue! } == [0, 1, 0] }!["id"]!.stringValue! @@ -267,7 +283,8 @@ struct ReferencePlaneTests { #expect(names == ["Plane1", "Sketch1", "Boss-Extrude1"]) // Deleting the plane leaves the sketch with a lost reference. let states = try await e.execute("feature.delete", ["feature": "Plane1"]).result["features"]!.arrayValue!.map { $0["state"]!.stringValue! } - #expect(states == ["error", "ok"]) + #expect(states == ["error", "error"]) + #expect(await e.activeDocument!.bodies.isEmpty) } } diff --git a/Tests/ForgeCommandsTests/MeasurementTests.swift b/Tests/ForgeCommandsTests/MeasurementTests.swift new file mode 100644 index 0000000..209b6ab --- /dev/null +++ b/Tests/ForgeCommandsTests/MeasurementTests.swift @@ -0,0 +1,109 @@ +import ForgeCore +import ForgeKernel +import Foundation +import Testing + +@testable import ForgeCommands + +@Suite("Selected entity measurements") +struct MeasurementTests { + func engine() async throws -> Engine { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("body.create_box", ["width": 10, "height": 20, "depth": 30]) + return engine + } + + func face(_ engine: Engine, normal: Vec3) async throws -> String { + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + for i in 0..<(try body.shape.topology().faces) { + if (try body.shape.face(i).normal - normal).length < 1e-9 { return "body-1/face-\(i)" } + } + throw ForgeError(.internalError, "test face missing") + } + + func vertex(_ shape: Shape, at point: Vec3) throws -> Int { + for i in 0..<(try shape.topology().vertices) { + if (try shape.vertex(i) - point).length < 1e-9 { return i } + } + throw ForgeError(.internalError, "test vertex missing") + } + + @Test func bodyFaceAndEdgePropertiesUsePhysicalUnits() async throws { + let engine = try await engine() + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + let measurement = try await engine.execute("query.measure", ["from": "body-1"]).result + #expect(measurement["distance_mm"] == nil) + #expect(abs(measurement["from_entity"]!["volume_mm3"]!.doubleValue! - 6000) < 1e-8) + #expect(abs(measurement["from_entity"]!["area_mm2"]!.doubleValue! - 2200) < 1e-8) + let top = try await face(engine, normal: .unitZ) + let area = try await engine.execute("query.measure", ["from": .string(top)]).result + #expect(abs(area["from_entity"]!["area_mm2"]!.doubleValue! - 200) < 1e-8) + #expect(area["from_entity"]?["normal"] == [0, 0, 1]) + for i in 0..<(try body.shape.topology().edges) { + let edge = try body.shape.edge(i) + let result = try await engine.execute("query.measure", ["from": .string("body-1/edge-\(i)")]).result + let length = try #require(result["from_entity"]?["length_mm"]?.doubleValue) + #expect(abs(length - (edge.end - edge.start).length) < 1e-8) + } + } + + @Test func selectedFacesAndEdgesMeasureTheirOwnGeometry() async throws { + let engine = try await engine() + let bottom = try await face(engine, normal: -.unitZ) + let top = try await face(engine, normal: .unitZ) + let between = try await engine.execute("query.measure", ["from": .string(bottom), "to": .string(top)]).result + #expect(abs(between["distance_mm"]!.doubleValue! - 30) < 1e-8) + #expect(between["delta_mm"] == [0, 0, 30]) + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + let index = try #require((0..<(try body.shape.topology().edges)).first { + guard let edge = try? body.shape.edge($0) else { return false } + return abs(edge.start.z) < 1e-9 && abs(edge.end.z) < 1e-9 + }) + let edge = "body-1/edge-\(index)" + let separated = try await engine.execute("query.measure", ["from": .string(edge), "to": .string(top)]).result + #expect(abs(separated["distance_mm"]!.doubleValue! - 30) < 1e-8) + let touching = try await engine.execute("query.measure", ["from": .string(edge), "to": .string(bottom)]).result + #expect(abs(touching["distance_mm"]!.doubleValue!) < 1e-8) + let named = try #require(body.naming?.edges[index]) + let persistent = try await engine.execute("query.measure", ["from": .string("body-1/edge@\(named)"), "to": .string(top)]).result + #expect(persistent["distance_mm"] == separated["distance_mm"]) + } + + @Test func verticesMeasureExactCoordinatesAndCrossBodyDistances() async throws { + let engine = try await engine() + try await engine.execute("body.create_box", ["width": 2, "height": 3, "depth": 4, "origin": [20, 30, 40]]) + let doc = try #require(await engine.activeDocument) + let a = try vertex(doc.body("body-1").shape, at: .zero) + let b = try vertex(doc.body("body-2").shape, at: Vec3(20, 30, 40)) + let result = try await engine.execute("query.measure", ["from": .string("body-1/vertex-\(a)"), "to": .string("body-2/vertex-\(b)")]).result + #expect(abs(result["distance_mm"]!.doubleValue! - Double(2900).squareRoot()) < 1e-8) + #expect(result["point_from"] == [0, 0, 0]) + #expect(result["point_to"] == [20, 30, 40]) + #expect(result["from_entity"]?["position"] == [0, 0, 0]) + #expect(result["to_entity"]?["position"] == [20, 30, 40]) + #expect(result["delta_mm"] == [20, 30, 40]) + let vertexToBody = try await engine.execute("query.measure", ["from": .string("body-2/vertex-\(b)"), "to": "body-1"]).result + #expect(abs(vertexToBody["distance_mm"]!.doubleValue! - Double(300).squareRoot()) < 1e-8) + } + + @Test func circularEdgesReportRadiusAndCircumference() async throws { + let engine = Engine() + try await engine.execute("document.new", ["units": ["length": "in"]]) + try await engine.execute("body.create_cylinder", ["radius": "5 mm", "height": "10 mm"]) + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + let i = try #require((0..<(try body.shape.topology().edges)).first { (try? body.shape.edge($0).curveType) == .circle }) + let result = try await engine.execute("query.measure", ["from": .string("body-1/edge-\(i)")]).result + #expect(abs(result["from_entity"]!["radius_mm"]!.doubleValue! - 5) < 1e-9) + #expect(abs(result["from_entity"]!["length_mm"]!.doubleValue! - 10 * .pi) < 1e-8) + } + + @Test func rejectsMissingAndOutOfRangeSelectionsWithoutMutatingDocument() async throws { + let engine = try await engine() + let before = try await engine.execute("document.state").result + for ref in ["body-1/vertex-999", "body-1/face-999", "body-1/edge-999", "body-2", "body-1/face@missing", "body-1/vertex-9223372036854775807"] { + await #expect(throws: ForgeError.self) { try await engine.execute("query.measure", ["from": .string(ref)]) } + } + #expect(try await engine.execute("document.state").result == before) + } +} diff --git a/Tests/ForgeCommandsTests/SketchConvertTests.swift b/Tests/ForgeCommandsTests/SketchConvertTests.swift new file mode 100644 index 0000000..d0f9d10 --- /dev/null +++ b/Tests/ForgeCommandsTests/SketchConvertTests.swift @@ -0,0 +1,165 @@ +import ForgeCore +import ForgeKernel +import Foundation +import Testing + +@testable import ForgeCommands + +@Suite("Convert model entities") +struct SketchConvertTests { + func boxEngine() async throws -> Engine { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("body.create_box", ["width": 10, "height": 20, "depth": 30]) + return engine + } + + func planarFace(_ engine: Engine, normal: Vec3) async throws -> String { + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + for index in 0..<(try body.shape.topology().faces) { + if (try body.shape.face(index).normal - normal).length < 1e-6 { return "body-1/face-\(index)" } + } + throw ForgeError(.internalError, "test face not found") + } + + func circularEdge(_ engine: Engine) async throws -> String { + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + for index in 0..<(try body.shape.topology().edges) { + if try body.shape.edge(index).curveType == .circle { return "body-1/edge-\(index)" } + } + throw ForgeError(.internalError, "test edge not found") + } + + @Test func faceBoundaryMakesClosedProfileWithUndoDryRunAndRoundTrip() async throws { + let engine = try await boxEngine() + let face = try await planarFace(engine, normal: .unitZ) + try await engine.execute("sketch.create", ["face": .string(face)]) + let params: JSONValue = ["entities": [.string(face), .string(face)]] + let dry = try await engine.execute("sketch.convert_entities", params, dryRun: true) + #expect(dry.result["created"]?.arrayValue?.count == 4) + #expect(await engine.activeDocument?.orderedSketches[0].orderedEntities.count == 1) + let result = try await engine.execute("sketch.convert_entities", params) + #expect(result.result["created"]?.arrayValue?.count == 4) + let converted = try #require(await engine.activeDocument?.orderedSketches.first) + #expect(converted.report?.dof == 0) + try await engine.execute("edit.undo") + #expect(await engine.activeDocument?.orderedSketches[0].orderedEntities.count == 1) + try await engine.execute("edit.redo") + #expect(await engine.activeDocument?.orderedSketches[0] == converted) + let extrusion = try await engine.execute("body.extrude", ["depth": 2]) + #expect(abs((volume(extrusion) ?? 0) - 400) < 1e-6) + try await engine.execute("document.regenerate") + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("forge-convert-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let path = dir.appendingPathComponent("Part.forgepart").path + try await engine.execute("document.save", ["path": .string(path)]) + let reopened = Engine() + try await reopened.execute("document.open", ["path": .string(path)]) + try await reopened.execute("document.regenerate") + #expect(await reopened.activeDocument?.orderedSketches[0].orderedEntities.count == converted.orderedEntities.count) + let mass = try await reopened.execute("query.mass_properties", ["body": "body-2"]) + #expect(abs((mass.result["volume_mm3"]?.doubleValue ?? 0) - 400) < 1e-6) + } + + @Test func parallelCircleProjectsExactlyAndRemainsDetached() async throws { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("body.create_cylinder", ["radius": 4, "height": 12]) + let edge = try await circularEdge(engine) + try await engine.execute("sketch.create", ["plane": "front", "offset": 20]) + let result = try await engine.execute("sketch.convert_entities", ["entities": [.string(edge)], "fixed": false]) + let id = try #require(result.result["created"]?.arrayValue?.first?.stringValue) + var sketch = try #require(await engine.activeDocument?.orderedSketches.first) + #expect(try sketch.entity(id).kind == .circle) + #expect(sketch.report?.dof == 3) + let circle = try sketch.entity(id) + #expect(abs(sketch.params[circle.params[0]] - 4) < 1e-9) + try await engine.execute("feature.edit", ["feature": "feature-1", "params": ["radius": 6]]) + sketch = try #require(await engine.activeDocument?.orderedSketches.first) + #expect(abs(sketch.params[circle.params[0]] - 4) < 1e-9) + } + + @Test func convertsCircularArcsWithoutChangingTheirSweep() async throws { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("body.create_cylinder", ["radius": 4, "height": 12]) + try await engine.execute("body.create_box", ["width": 10, "height": 20, "depth": 14, "origin": [0, -10, -1]]) + try await engine.execute("body.boolean", ["operation": "cut", "target": "body-1", "tool": "body-2"]) + let edge = try await circularEdge(engine) + try await engine.execute("sketch.create", ["plane": "front"]) + let result = try await engine.execute("sketch.convert_entities", ["entities": [.string(edge)]]) + let id = try #require(result.result["created"]?.arrayValue?.first?.stringValue) + let sketch = try #require(await engine.activeDocument?.orderedSketches.first) + let arc = try sketch.entity(id) + #expect(arc.kind == .arc) + #expect(sketch.report?.dof == 0) + let points = try arc.points.map { try sketch.entity($0) }.map { Vec3(sketch.params[$0.params[0]], sketch.params[$0.params[1]], 0) } + #expect(abs((points[1] - points[0]).length - 4) < 1e-8) + #expect(abs((points[2] - points[1]).length - 8) < 1e-8) + // CCW from +Y to -Y sweeps the retained negative-X half, not the removed half. + #expect(abs(points[1].y - 4) < 1e-8) + #expect(abs(points[2].y + 4) < 1e-8) + } + + @Test func unsupportedProjectionRejectsWholeCommand() async throws { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("body.create_cylinder", ["radius": 4, "height": 12]) + let edge = try await circularEdge(engine) + try await engine.execute("sketch.create", ["plane": "right"]) + let before = await engine.activeDocument?.orderedSketches.first + await #expect(throws: ForgeError.self) { + try await engine.execute("sketch.convert_entities", ["entities": [.string(edge)]]) + } + #expect(await engine.activeDocument?.orderedSketches.first == before) + let body = try #require(await engine.activeDocument?.bodies["body-1"]) + let line = try #require((0..<(try body.shape.topology().edges)).first { (try? body.shape.edge($0).curveType) == .line }) + try await engine.execute("sketch.create", ["plane": "front"]) + await #expect(throws: ForgeError.self) { + try await engine.execute("sketch.convert_entities", ["entities": [.string(edge), .string("body-1/edge-\(line)")]]) + } + #expect(await engine.activeDocument?.orderedSketches[1].orderedEntities.count == 1) + } +} + +@Suite("Sketch attachment repair") +struct SketchAttachmentRepairTests { + @Test func lostPlaneBlocksDownstreamGeometryAndCanBeRepairedWithUndo() async throws { + let engine = Engine() + try await engine.execute("document.new") + try await engine.execute("plane.create", ["reference": "top", "offset": 30]) + try await engine.execute("sketch.create", ["plane": "Plane1"]) + try await engine.execute("sketch.add_rectangle", ["points": [[0, 0], [10, 10]]]) + try await engine.execute("body.extrude", ["depth": 2]) + try await engine.execute("feature.delete", ["feature": "Plane1"]) + #expect(await engine.activeDocument!.bodies.isEmpty) + #expect(await engine.activeDocument!.features.map(\.status.state) == [.error, .error]) + await #expect(throws: ForgeError.self) { try await engine.execute("body.extrude", ["depth": 4]) } + try await engine.execute("feature.repair_reference", ["feature": "Sketch1", "old": "plane-1", "new": "front"]) + #expect(await engine.activeDocument!.features.map(\.status.state) == [.ok, .ok]) + #expect(abs(try await engine.activeDocument!.body("body-1").shape.boundingBox().max.z - 2) < 1e-6) + try await engine.execute("edit.undo") + #expect(await engine.activeDocument!.bodies.isEmpty) + try await engine.execute("edit.redo") + #expect(await engine.activeDocument!.features.map(\.status.state) == [.ok, .ok]) + } + + @Test func faceAttachmentRepairChangesPersistedPlacement() async throws { + let helper = SketchConvertTests() + let engine = try await helper.boxEngine() + let front = try await helper.planarFace(engine, normal: .unitZ) + let side = try await helper.planarFace(engine, normal: .unitY) + try await engine.execute("sketch.create", ["face": .string(front)]) + try await engine.execute("sketch.add_circle", ["center": [5, 5], "radius": 2]) + try await engine.execute("body.extrude", ["depth": 3]) + let old = try #require(await engine.activeDocument!.orderedSketches[0].placement) + try await engine.execute("feature.repair_reference", ["feature": "Sketch1", "old": .string(old), "new": .string(side)]) + let sketch = try #require(await engine.activeDocument?.orderedSketches.first) + #expect((sketch.plane.normal - .unitY).length < 1e-8) + #expect(sketch.placement?.contains("face@") == true) + #expect(sketch.placement != old) + try await engine.execute("feature.edit", ["feature": "Box1", "params": ["height": 25]]) + #expect(abs(try await engine.activeDocument!.body("body-2").shape.boundingBox().min.y - 25) < 1e-6) + } +} diff --git a/Tests/ForgeCommandsTests/VisibilityTests.swift b/Tests/ForgeCommandsTests/VisibilityTests.swift new file mode 100644 index 0000000..3fdf4d7 --- /dev/null +++ b/Tests/ForgeCommandsTests/VisibilityTests.swift @@ -0,0 +1,114 @@ +import ForgeCore +import ForgeData +import ForgeRender +import Foundation +import Testing +@testable import ForgeCommands + +@Suite("Body visibility commands") +struct VisibilityTests { + private func engine() async throws -> Engine { + let e = Engine() + try await e.execute("document.new") + try await e.execute("body.create_box", ["width": 10, "height": 10, "depth": 10]) + try await e.execute("body.create_box", ["width": 10, "height": 10, "depth": 10, "origin": [30, 0, 0]]) + return e + } + + @Test func hiddenBodiesAreNotRenderedPickedOrFramedButRemainInModel() async throws { + let e = try await engine() + let result = try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + #expect(result.changes.modified == ["doc-1"]) + let doc = try #require(await e.activeDocument) + #expect(doc.bodies.count == 2 && doc.features.count == 2) + let scene = try DocumentScene(document: doc) + #expect(scene.bodies == ["body-2"]) + #expect(scene.scene.bounds?.min.x == 30) + #expect(RayPicker.pick(scene.scene, origin: Vec3(5, 5, 100), direction: Vec3(0, 0, -1)) == nil) + let hit = try #require(RayPicker.pick(scene.scene, origin: Vec3(35, 5, 100), direction: Vec3(0, 0, -1))) + #expect(scene.reference(for: hit)?.hasPrefix("body-2/face-") == true) + let state = try await e.execute("document.state").result + #expect(state["visibility"]?["hidden_bodies"] == ["body-1"]) + #expect(state["visibility"]?["visible_bodies"] == ["body-2"]) + let properties = try await e.execute("query.mass_properties", ["body": "body-1"]).result + #expect(abs((properties["volume_mm3"]?.doubleValue ?? 0) - 1000) < 1e-8) + } + + @Test func visibilityTransactionUndoDryRunAndInvalidInputsAreAtomic() async throws { + let e = try await engine() + let dry = try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false], dryRun: true) + #expect(dry.changes.modified == ["doc-1"]) + #expect(await e.activeDocument?.hiddenBodyIDs.isEmpty == true) + await #expect(throws: ForgeError.self) { + try await e.execute("view.set_visibility", ["bodies": ["body-1", "missing"], "visible": false]) + } + #expect(await e.activeDocument?.hiddenBodyIDs.isEmpty == true) + try await e.execute("transaction.begin", ["label": "Hide first body"]) + try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + try await e.execute("transaction.commit") + try await e.execute("edit.undo") + #expect(await e.activeDocument?.hiddenBodyIDs.isEmpty == true) + try await e.execute("edit.redo") + #expect(await e.activeDocument?.hiddenBodyIDs == ["body-1"]) + } + + @Test func isolationRestoresPriorVisibilityAndNewBodiesStayOutsideIt() async throws { + let e = try await engine() + try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + try await e.execute("view.isolate", ["bodies": ["body-1"]]) + #expect(try DocumentScene(document: #require(await e.activeDocument)).bodies == ["body-1"]) + try await e.execute("body.create_sphere", ["radius": 1]) + #expect(try DocumentScene(document: #require(await e.activeDocument)).bodies == ["body-1"]) + try await e.execute("view.set_visibility", ["bodies": ["body-2"], "visible": true]) + try await e.execute("view.exit_isolation") + #expect(try DocumentScene(document: #require(await e.activeDocument)).bodies == ["body-2", "body-3"]) + try await e.execute("edit.undo") + #expect(await e.activeDocument?.isolatedBodyIDs == ["body-1", "body-2"]) + try await e.execute("view.show_all") + #expect(try DocumentScene(document: #require(await e.activeDocument)).bodies.count == 3) + #expect(await e.activeDocument?.isolatedBodyIDs == nil) + } + + @Test func saveDuringIsolationPersistsOrdinaryVisibilityOnlyAndOldFilesDefaultVisible() async throws { + let e = try await engine() + try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + try await e.execute("view.isolate", ["bodies": ["body-1"]]) + let path = FileManager.default.temporaryDirectory.appendingPathComponent("forge-visibility-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: path) } + try await e.execute("document.save", ["path": .string(path.path)]) + let loaded = Engine() + try await loaded.execute("document.open", ["path": .string(path.path)]) + #expect(await loaded.activeDocument?.isolatedBodyIDs == nil) + #expect(try DocumentScene(document: #require(await loaded.activeDocument)).bodies == ["body-2"]) + try await loaded.execute("document.regenerate") + #expect(try DocumentScene(document: #require(await loaded.activeDocument)).bodies == ["body-2"]) + let modelPath = path.appendingPathComponent("model.json") + var json = try JSONCoding.parse(String(contentsOf: modelPath, encoding: .utf8)).objectValue! + json.removeValue(forKey: "hidden_bodies") + try JSONCoding.string(.object(json)).write(to: modelPath, atomically: true, encoding: .utf8) + let legacy = Engine() + try await legacy.execute("document.open", ["path": .string(path.path)]) + #expect(try DocumentScene(document: #require(await legacy.activeDocument)).bodies.count == 2) + } + + @Test func packageVisibilityRetainsSuppressedBodiesButIgnoresUnknownFutureIDs() async throws { + let e = try await engine() + try await e.execute("view.set_visibility", ["bodies": ["body-2"], "visible": false]) + try await e.execute("feature.suppress", ["feature": "feature-2"]) + let path = FileManager.default.temporaryDirectory.appendingPathComponent("forge-hidden-ids-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: path) } + try await e.execute("document.save", ["path": .string(path.path)]) + let modelPath = path.appendingPathComponent("model.json") + var json = try JSONCoding.parse(String(contentsOf: modelPath, encoding: .utf8)).objectValue! + json["hidden_bodies"] = ["body-2", "body-3", "missing"] + try JSONCoding.string(.object(json)).write(to: modelPath, atomically: true, encoding: .utf8) + let loaded = Engine() + try await loaded.execute("document.open", ["path": .string(path.path)]) + #expect(await loaded.activeDocument?.hiddenBodyIDs == ["body-2"]) + try await loaded.execute("feature.suppress", ["feature": "feature-2", "suppressed": false]) + #expect(await loaded.activeDocument?.isBodyVisible("body-2") == false) + try await loaded.execute("body.create_sphere", ["radius": 1]) + #expect(await loaded.activeDocument?.isBodyVisible("body-3") == true) + } + +} diff --git a/Tests/ForgeUITests/ArcSlotWorkflowTests.swift b/Tests/ForgeUITests/ArcSlotWorkflowTests.swift new file mode 100644 index 0000000..d664917 --- /dev/null +++ b/Tests/ForgeUITests/ArcSlotWorkflowTests.swift @@ -0,0 +1,101 @@ +import ForgeCore +import ForgeSketch +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop curved slots") +struct ArcSlotWorkflowTests { + @Test func centerArcSlotProjectsEndAndExtrudesAnalyticArea() async throws { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + let id = try #require(m.activeSketch) + m.sketchState.slotType = .arc + m.chooseTool(.slot) + for p in [Point2(0, 0), Point2(10, 0), Point2(0, 15)] { + await m.sketchClick(p, tolerance: 0.001, curve: nil) + } + #expect(m.sketchState.pending.count == 3) + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .arc }.isEmpty == true) + await m.sketchClick(Point2(0, 12), tolerance: 0.001, curve: nil) + #expect(m.lastError == nil) + #expect(m.sketchState.pending.isEmpty) + let sk = try #require(m.sketchState.sketch) + #expect(sk.orderedEntities.filter { $0.kind == .arc && !$0.construction }.count == 4) + await m.run("sketch.exit") + await m.run("body.extrude", ["sketch": .string(id), "depth": 3]) + #expect(m.lastError == nil) + let doc = try #require(await m.engine.activeDocument) + let body = try #require(doc.bodies.values.first) + // quarter-circle centerline length 5π, width 4, two semicircular caps R2. + #expect(abs(try body.shape.massProperties().volume - 72 * .pi) < 1e-6) + await m.run("edit.undo") + #expect(m.bodies.isEmpty) + await m.run("edit.redo") + #expect(m.bodies.count == 1) + } + + @Test func threePointSlotAndConstructionOptionUseFourClicks() async throws { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + m.sketchState.slotType = .threePointArc + m.sketchState.forConstruction = true + m.chooseTool(.slot) + for p in [Point2(10, 0), Point2(-10, 0), Point2(0, 10), Point2(0, 12)] { + await m.sketchClick(p, tolerance: 0.001, curve: nil) + } + #expect(m.lastError == nil) + let sk = try #require(m.sketchState.sketch) + #expect(sk.orderedEntities.filter { $0.kind == .arc }.count == 5) + #expect(sk.orderedEntities.filter { $0.kind == .arc }.allSatisfy { $0.construction }) + await m.run("edit.undo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .arc }.isEmpty == true) + await m.run("edit.redo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .arc }.count == 5) + } + + @Test func changingSlotTypeDiscardsIncompatibleClicksAndCanFinishNewSlot() async throws { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + m.chooseSlotType(.arc) + m.chooseTool(.slot) + for p in [Point2(0, 0), Point2(10, 0), Point2(0, 10)] { + await m.sketchClick(p, tolerance: 0.001, curve: nil) + } + #expect(m.sketchState.pending.count == 3) + // Invoke the actual shared desktop PropertyManager control. + let control = try #require(m.panelPage.sections.flatMap(\.controls).first { $0.id == "type" }) + guard case .choice(_, _, _, let select) = control.kind else { + Issue.record("Slot type must be a choice control") + return + } + select(SlotType.straight.rawValue) + #expect(m.sketchState.pending.isEmpty) + #expect(m.sketchState.preview == nil) + #expect(m.hoverLines.isEmpty) + for p in [Point2(0, 0), Point2(10, 0), Point2(10, 2)] { + await m.sketchClick(p, tolerance: 0.001, curve: nil) + } + #expect(m.lastError == nil) + #expect(m.sketchState.pending.isEmpty) + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .arc }.count == 2) + } + + @Test func collinearThreePointSlotRejectsWithoutGeometry() async throws { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + m.sketchState.slotType = .threePointArc + m.chooseTool(.slot) + for p in [Point2(0, 0), Point2(10, 0), Point2(5, 0), Point2(5, 2)] { + await m.sketchClick(p, tolerance: 0.001, curve: nil) + } + #expect(m.lastError?.code == .invalidParams) + #expect(m.sketchState.pending.isEmpty) + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .arc }.isEmpty == true) + } +} diff --git a/Tests/ForgeUITests/BodyPlacementWorkflowTests.swift b/Tests/ForgeUITests/BodyPlacementWorkflowTests.swift new file mode 100644 index 0000000..3c35b71 --- /dev/null +++ b/Tests/ForgeUITests/BodyPlacementWorkflowTests.swift @@ -0,0 +1,139 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Body placement workflows") +struct BodyPlacementWorkflowTests { + @Test func placementInputsInvalidatePreviewAndUnitsReachGeometry() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + model.begin(.moveBody) + let original = model.previewKey + model.form.bodyDX = "1 in" + #expect(model.previewKey != original) + await model.updatePreview() + let bounds = try #require(model.preview.items.first?.mesh.bounds) + #expect(abs(bounds.min.x - 25.4) < 1e-5) + #expect(abs(bounds.max.x - 35.4) < 1e-5) + // Every placement field is observed by the native and SwiftUI preview schedulers. + for key in [\OperationForm.bodyDY, \.bodyDZ, \.bodyAngle, \.bodyAxis, \.bodyOriginX, \.bodyOriginY, \.bodyOriginZ, + \.vertexX, \.vertexY, \.vertexZ, \.vertex2X, \.vertex2Y, \.vertex2Z] { + let before = model.previewKey + model.form[keyPath: key] += "1" + #expect(model.previewKey != before) + } + var before = model.previewKey + model.form.bodyCopy.toggle() + #expect(model.previewKey != before) + before = model.previewKey + model.form.bodyRotation.toggle() + #expect(model.previewKey != before) + before = model.previewKey + model.form.bodyCustomAxis = [1, 1, 0] + #expect(model.previewKey != before) + } + + @Test func editingTranslationResetsUnstoredRotationDefaults() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await model.run("body.transform", ["body": "body-1", "translate": [10, 0, 0]]) + model.form.bodyAxis = "custom" + model.form.bodyCustomAxis = [1, 1, 0] + model.form.bodyOriginX = "100" + model.form.bodyAngle = "123" + model.editFeature(try #require(model.features.last)) + await model.editTask?.value + #expect(!model.form.bodyRotation) + #expect(model.form.bodyAxis == "z" && model.form.bodyAngle == "90") + #expect(model.form.bodyOriginX == "0" && model.form.bodyCustomAxis == [0, 0, 1]) + model.cancelOperation() + } + + @Test func copyRotateMoveThenEditAndUndo() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await model.select(["body-1"]) + model.begin(.moveBody) + #expect(model.panelPage.title == "Move/Copy Bodies") + model.form.bodyCopy = true + model.form.bodyDX = "100" + model.form.bodyRotation = true + model.form.bodyAngle = "90" + model.form.bodyAxis = "z" + await model.commitOperation() + #expect(model.bodies.count == 2) + let moved = try #require(await model.engine.activeDocument?.body("body-2")) + #expect((try moved.shape.massProperties().centroid - Vec3(90, 5, 15)).length < 1e-6) + let feature = try #require(model.features.last) + #expect(feature.operation == .moveBody) + model.editFeature(feature) + await model.editTask?.value + #expect(model.form.bodyCopy) + #expect(model.form.bodyRotation) + model.form.bodyDX = "120" + await model.commitOperation() + let edited = try #require(await model.engine.activeDocument?.body("body-2")) + #expect(abs(try edited.shape.massProperties().centroid.x - 110) < 1e-6) + await model.run("edit.undo") + let restored = try #require(await model.engine.activeDocument?.body("body-2")) + #expect(abs(try restored.shape.massProperties().centroid.x - 90) < 1e-6) + } + + @Test func customRotationAxisSurvivesInspectorRoundtrip() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await model.run("body.transform", ["body": "body-1", "rotate": ["axis": [1, 1, 0], "angle": "30 deg", "origin": [2, 3, 4]]]) + let before = try #require(await model.engine.activeDocument?.body("body-1")).shape + let mass = try before.massProperties() + let feature = try #require(model.features.last) + model.editFeature(feature) + await model.editTask?.value + #expect(model.form.bodyAxis == "custom") + await model.commitOperation() + let after = try #require(await model.engine.activeDocument?.body("body-1")).shape + #expect((try after.massProperties().centroid - mass.centroid).length < 1e-6) + } + + @Test func upToVertexBothDirectionsSurvivesFeatureEditor() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("sketch.create", ["plane": "front"]) + await model.run("sketch.add_rectangle", ["points": [[0, 0], [10, 10]]]) + await model.run("sketch.exit") + await model.run("body.extrude", ["sketch": "sketch-1", "end_condition": "up_to_vertex", "vertex": [0, 0, 15], "direction2": ["end_condition": "up_to_vertex", "vertex": [0, 0, -5]]]) + let feature = try #require(model.features.last) + model.editFeature(feature) + await model.editTask?.value + #expect(model.form.endCondition == .upToVertex) + #expect(model.form.endCondition2 == .upToVertex) + await model.commitOperation() + let body = try #require(await model.engine.activeDocument?.body("body-1")) + #expect(abs(try body.shape.massProperties().volume - 2000) < 1e-6) + #expect(model.features.last?.params["end_condition"] == "up_to_vertex") + #expect(model.features.last?.params["direction2"]?["end_condition"] == "up_to_vertex") + } + + @Test func normalToSelectedFaceAndPlaneWithoutOpeningSketch() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + await model.select(["body-1/face-0"]) + #expect(model.canNormalTo) + await model.normalToSelection() + #expect(model.activeSketch == nil) + #expect(model.lastError == nil) + guard case .normalTo(let facePlane)? = model.viewportCommands.log.last else { Issue.record("No face camera command"); return } + #expect(abs(facePlane.normal.x) > 0.99) + await model.select(["plane-top"]) + await model.normalToSelection() + #expect(model.lastError == nil) + guard case .normalTo(let plane)? = model.viewportCommands.log.last else { Issue.record("No plane camera command"); return } + #expect(abs(plane.normal.y) > 0.99) + } +} diff --git a/Tests/ForgeUITests/BodyVisibilityWorkflowTests.swift b/Tests/ForgeUITests/BodyVisibilityWorkflowTests.swift new file mode 100644 index 0000000..dc0f544 --- /dev/null +++ b/Tests/ForgeUITests/BodyVisibilityWorkflowTests.swift @@ -0,0 +1,72 @@ +import ForgeCore +import ForgeRender +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop body visibility") +struct BodyVisibilityWorkflowTests { + private func model() async -> AppModel { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 10, "depth": 10]) + await m.run("body.create_box", ["width": 10, "height": 10, "depth": 10, "origin": [30, 0, 0]]) + return m + } + + private func wait(_ predicate: () -> Bool) async throws { + for _ in 0..<100 where !predicate() { try await Task.sleep(for: .milliseconds(10)) } + #expect(predicate()) + } + + @Test func bodyTreeHideAndShowActionsUpdateSceneAndRemainAccessible() async throws { + let m = await model() + let body = try #require(m.treeNodes.first { $0.id == "bodies" }?.children.first { $0.id == "body-1" }) + let hide = try #require(body.menu.first { $0.title == "Hide Body" }) + hide.action() + try await wait { m.scene.value?.bodies == ["body-2"] } + #expect(m.bodies.count == 2 && m.hiddenBodyIDs == ["body-1"]) + let hidden = try #require(m.treeNodes.first { $0.id == "bodies" }?.children.first { $0.id == "body-1" }) + #expect(hidden.title.contains("Hidden")) + let show = try #require(hidden.menu.first { $0.title == "Show Body" }) + show.action() + try await wait { m.scene.value?.bodies == ["body-1", "body-2"] } + #expect(m.lastError == nil) + } + + @Test func faceSelectionRibbonIsolationRestoresOriginalVisibility() async throws { + let m = await model() + await m.setBodiesVisible(["body-2"], false) + await m.select("body-1/face-0", extend: false) + m.ribbonTab = .features + let isolate = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "isolateBodies" }) + #expect(isolate.enabled) + isolate.action() + try await wait { m.isIsolatingBodies } + await m.setBodiesVisible(["body-2"], true) + #expect(m.scene.value?.bodies == ["body-1", "body-2"]) + let exit = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "exitIsolation" }) + #expect(exit.enabled) + exit.action() + try await wait { !m.isIsolatingBodies && m.scene.value?.bodies == ["body-1"] } + let showAll = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "showAllBodies" }) + showAll.action() + try await wait { m.hiddenBodyIDs.isEmpty && m.scene.value?.bodies.count == 2 } + #expect(m.lastError == nil) + } + + @Test func hidingEveryBodyProducesUnpickableEmptyModelSceneAndUndoRestoresIt() async throws { + let m = await model() + await m.setBodiesVisible(["body-1", "body-2"], false) + let ds = try #require(m.scene.value) + #expect(ds.bodies.isEmpty) + let modelItems = ds.scene.items.filter { $0.objectID < 1_000_000 } + #expect(modelItems.isEmpty) + #expect(RayPicker.pick(RenderScene(items: modelItems), origin: Vec3(5, 5, 100), direction: Vec3(0, 0, -1)) == nil) + await m.run("edit.undo") + #expect(m.scene.value?.bodies == ["body-1", "body-2"]) + await m.run("document.new") + #expect(m.hiddenBodyIDs.isEmpty && !m.isIsolatingBodies) + } +} diff --git a/Tests/ForgeUITests/MeasureWorkflowTests.swift b/Tests/ForgeUITests/MeasureWorkflowTests.swift new file mode 100644 index 0000000..0e52f6f --- /dev/null +++ b/Tests/ForgeUITests/MeasureWorkflowTests.swift @@ -0,0 +1,53 @@ +import ForgeCore +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop subentity measurement") +struct MeasureWorkflowTests { + @Test func singleBodyReportsSizeAndPairReportsMinimumDistance() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + let first = try #require(m.bodies.first?.id) + m.selection = [first] + m.begin(.measure) + await m.computeMeasure() + let result = try #require(m.form.result) + #expect(result["from_entity"]?["volume_mm3"]?.doubleValue == 6000) + #expect(m.lastError == nil) + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30, "origin": [40, 0, 0]]) + let second = try #require(m.bodies.first { $0.id != first }?.id) + m.selection = [first, second] + await m.computeMeasure() + #expect(abs((m.form.result?["distance_mm"]?.doubleValue ?? -1) - 30) < 1e-6) + m.selection = [first, second, "missing"] + await m.computeMeasure() + #expect(m.form.result == nil) + } + + @Test func unsupportedSelectionDoesNotSilentlyBecomeSingleBodyMeasurement() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 20, "depth": 30]) + let body = try #require(m.bodies.first?.id) + await m.newSketch(on: .front) + let sketch = try #require(m.activeSketch) + await m.run("sketch.exit") + m.selection = [body, sketch] + m.begin(.measure) + await m.computeMeasure() + #expect(m.form.result == nil) + #expect(m.lastError != nil) + } + + @Test func invalidReferenceReportsErrorInsteadOfBlankResults() async throws { + let m = AppModel() + await m.bootstrap() + m.begin(.measure) + m.selection = ["body-999/edge-1"] + await m.computeMeasure() + #expect(m.form.result == nil) + #expect(m.lastError != nil) + } +} diff --git a/Tests/ForgeUITests/PlaneTreeSelectionTests.swift b/Tests/ForgeUITests/PlaneTreeSelectionTests.swift new file mode 100644 index 0000000..9f211b8 --- /dev/null +++ b/Tests/ForgeUITests/PlaneTreeSelectionTests.swift @@ -0,0 +1,82 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Plane selection from desktop trees") +struct PlaneTreeSelectionTests { + @Test(arguments: [false, true]) + func primarySketchActionUsesClickedPlane(referencePlane: Bool) async throws { + let model = AppModel() + await model.bootstrap() + var nodeID = "plane-top", planeID = "plane-top" + if referencePlane { + await model.run("plane.create", ["reference": "top", "offset": 30]) + let feature = try #require(model.features.last) + nodeID = feature.id + planeID = try #require(feature.createdBodies.first) + } + let node = try #require(model.treeNodes.first { $0.id == nodeID }) + try await click(node, model: model, expected: [planeID]) + model.ribbonTab = .features + let button = try #require(model.ribbonGroups.flatMap(\.buttons).first { $0.id == "startSketch" }) + #expect(button.title == "Sketch on Plane") + button.action() + for _ in 0..<100 where model.sketchState.tool != .line && model.lastError == nil { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(model.lastError == nil && model.activeSketch != nil) + let plane = try #require(model.sketchState.plane) + #expect(abs(plane.normal.y) > 0.99) + #expect(abs(plane.origin.y - (referencePlane ? 30 : 0)) < 1e-7) + if referencePlane { + #expect(model.sketchState.sketch?.placement == planeID) + } + } + + private func click(_ node: TreeNode, model: AppModel, expected: [String], extend: Bool = false) async throws { + let select = try #require(node.select) + select(extend) + for _ in 0..<100 where model.selection != expected && model.lastError == nil { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(model.lastError == nil) + #expect(model.selection == expected) + } + + @Test func standardPlaneClickHighlightsAndOrientsWithoutStartingSketch() async throws { + let model = AppModel() + await model.bootstrap() + let top = try #require(model.treeNodes.first { $0.id == "plane-top" }) + try await click(top, model: model, expected: ["plane-top"]) + #expect(model.treeNodes.first { $0.id == top.id }?.selected == true) + #expect(model.canNormalTo && model.activeSketch == nil) + await model.normalToSelection() + guard case .normalTo(let plane)? = model.viewportCommands.log.last else { Issue.record("No Normal To command after plane click"); return } + #expect(abs(plane.normal.y) > 0.99) + let front = try #require(model.treeNodes.first { $0.id == "plane-front" }) + try await click(front, model: model, expected: ["plane-top", "plane-front"], extend: true) + #expect(model.treeNodes.first { $0.id == front.id }?.selected == true) + try await click(front, model: model, expected: ["plane-top"], extend: true) + #expect(model.treeNodes.first { $0.id == front.id }?.selected == false) + } + + @Test func referencePlaneFeatureClickHighlightsAndOrientsWithoutStartingSketch() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("plane.create", ["reference": "top", "offset": 30]) + let feature = try #require(model.features.last) + let planeID = try #require(feature.createdBodies.first) + let node = try #require(model.treeNodes.first { $0.id == feature.id }) + try await click(node, model: model, expected: [planeID]) + #expect(model.treeNodes.first { $0.id == feature.id }?.selected == true) + #expect(model.canNormalTo && model.activeSketch == nil) + await model.normalToSelection() + guard case .normalTo(let plane)? = model.viewportCommands.log.last else { Issue.record("No Normal To command after reference plane click"); return } + #expect(abs(plane.normal.y) > 0.99) + #expect(abs(plane.origin.y - 30) < 1e-7) + try await click(node, model: model, expected: [], extend: true) + #expect(model.treeNodes.first { $0.id == feature.id }?.selected == false) + } +} diff --git a/Tests/ForgeUITests/RenameWorkflowTests.swift b/Tests/ForgeUITests/RenameWorkflowTests.swift new file mode 100644 index 0000000..98b142e --- /dev/null +++ b/Tests/ForgeUITests/RenameWorkflowTests.swift @@ -0,0 +1,107 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +private final class NamePromptPlatform: PlatformServices { + var answer: String? + var prompts: [(String, String)] = [] + func requestName(_ title: String, currentName: String) -> String? { + prompts.append((title, currentName)) + return answer + } + func confirm(_ title: String, _ message: String, confirm: String, cancel: String) -> Bool { true } + func chooseSavePath(suggestedName name: String) -> String? { nil } + func chooseOpenPath() -> String? { nil } +} + +@MainActor +@Suite("Tree rename workflows") +struct RenameWorkflowTests { + @Test func unicodeNamesPreserveIdentityAndUndoRedo() async throws { + let model = AppModel(), prompt = NamePromptPlatform() + model.platform = prompt + await model.bootstrap() + await model.run("body.create_box", ["width": 2, "height": 3, "depth": 4]) + let oldBody = try #require(model.bodies.first).name + let oldFeature = try #require(model.features.first).name + prompt.answer = "机架 — café" + await model.renameBody("body-1") + #expect(model.bodies.first?.name == prompt.answer) + #expect(model.bodies.first?.id == "body-1") + #expect(prompt.prompts.last?.1 == oldBody) + await model.run("edit.undo") + #expect(model.bodies.first?.name == oldBody) + await model.run("edit.redo") + #expect(model.bodies.first?.name == "机架 — café") + prompt.answer = "底座 — Base" + await model.renameFeature("feature-1") + #expect(model.features.first?.name == prompt.answer) + #expect(model.features.first?.id == "feature-1") + #expect(prompt.prompts.last?.1 == oldFeature) + await model.run("edit.undo") + #expect(model.features.first?.name == oldFeature) + await model.run("edit.redo") + #expect(model.features.first?.name == "底座 — Base") + let volume = try #require(model.bodies.first?.volumeMM3) + #expect(abs(volume - 24) < 1e-12) + + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("forge-rename-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: folder) } + try #require(await model.run("document.save", ["path": .string(folder.path)]) != nil) + await model.run("document.new") + try #require(await model.run("document.open", ["path": .string(folder.path)]) != nil) + #expect(model.features.first?.name == "底座 — Base") + #expect(model.bodies.first?.name == "机架 — café") + } + + @Test func cancelAndUnchangedNamesDoNotAddUndoSteps() async throws { + let model = AppModel(), prompt = NamePromptPlatform() + model.platform = prompt + await model.bootstrap() + await model.run("body.create_box", ["width": 2, "height": 3, "depth": 4]) + prompt.answer = nil + await model.renameBody("body-1") + await model.renameFeature("feature-1") + prompt.answer = try #require(model.bodies.first).name + await model.renameBody("body-1") + prompt.answer = try #require(model.features.first).name + await model.renameFeature("feature-1") + await model.run("edit.undo") + #expect(model.bodies.isEmpty) + #expect(model.features.isEmpty) + } + + @Test func emptyNamesShowCommandErrorAndPreserveNames() async throws { + let model = AppModel(), prompt = NamePromptPlatform() + model.platform = prompt + await model.bootstrap() + await model.run("body.create_box", ["width": 2, "height": 3, "depth": 4]) + let oldBody = try #require(model.bodies.first).name + let oldFeature = try #require(model.features.first).name + prompt.answer = " " + await model.renameBody("body-1") + #expect(model.lastError?.code == .invalidParams) + #expect(model.bodies.first?.name == oldBody) + await model.renameFeature("feature-1") + #expect(model.lastError?.code == .invalidParams) + #expect(model.features.first?.name == oldFeature) + await model.run("edit.undo") + #expect(model.bodies.isEmpty) + } + + @Test func sharedTreeExposesRenameForBodiesFeaturesAndAbsorbedSketches() async throws { + let model = AppModel() + await model.bootstrap() + await model.run("sketch.create", ["plane": "front"]) + await model.run("sketch.add_circle", ["center": [0, 0], "radius": 2]) + await model.run("sketch.exit") + await model.run("body.extrude", ["sketch": "sketch-1", "depth": 3]) + let bodyFolder = try #require(model.treeNodes.first { $0.id == "bodies" }) + #expect(bodyFolder.children.first?.menu.contains { $0.title == "Rename…" } == true) + let extrude = try #require(model.treeNodes.first { $0.id == "feature-2" }) + #expect(extrude.menu.contains { $0.title == "Rename…" }) + #expect(extrude.children.first?.menu.contains { $0.title == "Rename…" } == true) + } +} diff --git a/Tests/ForgeUITests/SketchPlacementWorkflowTests.swift b/Tests/ForgeUITests/SketchPlacementWorkflowTests.swift new file mode 100644 index 0000000..9d6425f --- /dev/null +++ b/Tests/ForgeUITests/SketchPlacementWorkflowTests.swift @@ -0,0 +1,110 @@ +import ForgeCore +import ForgeRender +import ForgeSketch +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop face sketch workflows") +struct SketchPlacementWorkflowTests { + private func box() async -> AppModel { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 20, "height": 20, "depth": 20]) + return m + } + + private func pickTopFace(_ m: AppModel) throws -> String { + let scene = try #require(m.scene.value) + let bodies = RenderScene(items: scene.scene.items.filter { $0.objectID < 1_000_000 }) + let hit = try #require(RayPicker.pick(bodies, origin: Vec3(10, 10, 100), direction: Vec3(0, 0, -1))) + #expect(hit.element == .face) + return try #require(scene.reference(for: hit)) + } + + @Test func featureRibbonStartsPickedFaceSketchAndCutsThePart() async throws { + let m = await box() + let face = try pickTopFace(m) + await m.select(face, extend: false) + m.ribbonTab = .features + let button = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "startSketch" }) + #expect(button.enabled && button.title == "Sketch on Face") + button.action() + for _ in 0..<100 where m.sketchState.tool != .line && m.lastError == nil { try await Task.sleep(for: .milliseconds(10)) } + let id = try #require(m.activeSketch) + let plane = try #require(m.sketchState.plane) + #expect(abs(plane.origin.z - 20) < 1e-7) + #expect(plane.normal.z > 0.99) + for _ in 0..<100 { + if case .normalTo? = m.viewportCommands.log.last { break } + try await Task.sleep(for: .milliseconds(10)) + } + guard case .normalTo(let cameraPlane)? = m.viewportCommands.log.last else { Issue.record("face sketch did not orient its camera"); return } + #expect(cameraPlane == plane) + // Translate known world-space corners into the face's local coordinates, then use + // the same two-click rectangle workflow as the desktop viewport. + func local(_ p: Vec3) -> Point2 { + let d = p - plane.origin + return Point2(d.dot(plane.xAxis), d.dot(plane.yAxis)) + } + m.chooseTool(.rectangle) + await m.sketchClick(local(Vec3(5, 5, 20)), tolerance: 0.001, curve: nil) + await m.sketchClick(local(Vec3(10, 10, 20)), tolerance: 0.001, curve: nil) + #expect(m.lastError == nil) + let document = try #require(await m.engine.activeDocument) + #expect(document.sketches[id]?.placement?.contains("/face@") == true) + await m.exitSketch() + m.begin(.cutExtrude) + m.form.depth = "5" + await m.commitOperation() + #expect(m.lastError == nil) + let result = try await m.engine.execute("query.mass_properties", ["body": "body-1"]) + let volume = try #require(result.result["volume_mm3"]?.doubleValue) + #expect(abs(volume - (8000 - 5 * 5 * 5)) < 1e-6) + } + + @Test func invalidBodySelectionDoesNotFallBackToFrontPlane() async { + let m = await box() + for ref in ["body-1", "body-1/edge-0"] { + await m.select(ref, extend: false) + await m.startSketchFromSelection() + #expect(m.activeSketch == nil && m.sketches.isEmpty) + #expect(m.lastError?.code == .invalidParams) + } + } + + @Test func curvedFaceIsRejectedWithoutCreatingAFrontSketch() async throws { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_sphere", ["radius": 10]) + await m.select("body-1/face-0", extend: false) + await m.startSketchFromSelection() + #expect(m.activeSketch == nil && m.sketches.isEmpty) + #expect(m.lastError != nil) + } + + @Test func modelSelectionModeConvertsFaceBoundaryThroughCommandBus() async throws { + let m = await box() + let face = try pickTopFace(m) + await m.select(face, extend: false) + await m.startSketchFromSelection() + let id = try #require(m.activeSketch) + #expect(m.sketchState.tool == .line) + m.selectModelGeometry() + #expect(m.sketchState.tool == nil && m.activeSketch == id) + await m.select(face, extend: false) + m.ribbonTab = .sketch + let convert = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "convertEntities" }) + #expect(convert.enabled) + await m.convertSelectedModelGeometry() + #expect(m.lastError == nil) + let doc = try #require(await m.engine.activeDocument) + let sketch = try #require(doc.sketches[id]) + #expect(sketch.orderedEntities.filter { $0.kind == .line }.count == 4) + await m.run("edit.undo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .line }.isEmpty == true) + await m.run("edit.redo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .line }.count == 4) + } +} diff --git a/Tests/ForgeUITests/SketchSplitWorkflowTests.swift b/Tests/ForgeUITests/SketchSplitWorkflowTests.swift new file mode 100644 index 0000000..11814ad --- /dev/null +++ b/Tests/ForgeUITests/SketchSplitWorkflowTests.swift @@ -0,0 +1,80 @@ +import ForgeCore +import ForgeSketch +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop Split Entities") +struct SketchSplitWorkflowTests { + private func sketchModel() async -> AppModel { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + return m + } + + @Test func ribbonSplitCreatesJoinedLinePiecesAndUndoRestoresOriginal() async throws { + let m = await sketchModel() + await m.run("sketch.add_line", ["start": [0, 0], "end": [20, 0]]) + let sk = try #require(m.sketchState.sketch) + let line = try #require(sk.orderedEntities.first { $0.kind == .line }) + m.ribbonTab = .sketch + let button = try #require(m.ribbonGroups.flatMap(\.buttons).first { $0.id == "splitEntities" }) + #expect(button.enabled) + button.action() + #expect(m.sketchState.tool == .split && m.panelPage.title == "Split Entities") + await m.sketchClick(Point2(7, 0), tolerance: 0.01, curve: "\(sk.id)/\(line.id)") + #expect(m.lastError == nil) + let split = try #require(m.sketchState.sketch) + let pieces = split.orderedEntities.filter { $0.kind == .line } + #expect(pieces.count == 2) + let lengths = pieces.map { e in + let a = split.point(e.points[0]), b = split.point(e.points[1]) + return hypot(b.0 - a.0, b.1 - a.1) + }.sorted() + #expect(abs(lengths[0] - 7) < 1e-7 && abs(lengths[1] - 13) < 1e-7) + #expect(split.userConstraints.contains { $0.kind == .coincident }) + await m.run("edit.undo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .line }.count == 1) + await m.run("edit.redo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .line }.count == 2) + } + + @Test func circleWaitsForTwoClicksOnSameCurveAndEscapeCancelsPendingSplit() async throws { + let m = await sketchModel() + await m.run("sketch.add_circle", ["center": [0, 0], "radius": 5]) + await m.run("sketch.add_line", ["start": [10, 0], "end": [20, 0]]) + let sk = try #require(m.sketchState.sketch) + let circle = try #require(sk.orderedEntities.first { $0.kind == .circle }) + let line = try #require(sk.orderedEntities.first { $0.kind == .line }) + let ref = "\(sk.id)/\(circle.id)" + m.chooseTool(.split) + await m.sketchClick(Point2(5, 0), tolerance: 0.01, curve: ref) + #expect(m.sketchState.splitEntity == circle.id && m.sketchState.pending.count == 1) + #expect(m.sketchState.sketch?.entities[circle.id]?.kind == .circle) + await m.sketchClick(Point2(15, 0), tolerance: 0.01, curve: "\(sk.id)/\(line.id)") + #expect(m.lastError?.code == .invalidParams) + #expect(m.sketchState.splitEntity == circle.id) + m.cancelSketchOperation() + #expect(m.sketchState.tool == .split && m.sketchState.pending.isEmpty && m.sketchState.splitEntity == nil) + await m.sketchClick(Point2(5, 0), tolerance: 0.01, curve: ref) + await m.sketchClick(Point2(-5, 0), tolerance: 0.01, curve: ref) + #expect(m.lastError == nil && m.sketchState.pending.isEmpty) + let result = try #require(m.sketchState.sketch) + #expect(result.orderedEntities.filter { $0.kind == .arc }.count == 2) + #expect(result.orderedEntities.filter { $0.kind == .circle }.isEmpty) + await m.run("edit.undo") + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .circle }.count == 1) + } + + @Test func splitRejectsEntitiesFromAnotherSketch() async throws { + let m = await sketchModel() + await m.run("sketch.add_line", ["start": [0, 0], "end": [20, 0]]) + let line = try #require(m.sketchState.sketch?.orderedEntities.first { $0.kind == .line }) + m.chooseTool(.split) + await m.sketchClick(Point2(7, 0), tolerance: 0.01, curve: "sketch-999/\(line.id)") + #expect(m.lastError?.code == .invalidParams) + #expect(m.sketchState.sketch?.orderedEntities.filter { $0.kind == .line }.count == 1) + } +} diff --git a/Tests/GoldenModelTests/Models/026_curved_slot.json b/Tests/GoldenModelTests/Models/026_curved_slot.json new file mode 100644 index 0000000..9c57419 --- /dev/null +++ b/Tests/GoldenModelTests/Models/026_curved_slot.json @@ -0,0 +1,73 @@ +{ + "forge_script": 1, + "name": "026_curved_slot", + "description": "Quarter-circle slot R10 width4 extruded3: area=width*arcLength+pi*(width/2)^2=24pi; volume=72pi.", + "commands": [ + { + "command": "document.new", + "params": {} + }, + { + "command": "sketch.create", + "params": { + "plane": "front" + } + }, + { + "command": "sketch.add_arc_slot", + "params": { + "center": [ + 0, + 0 + ], + "start": [ + 10, + 0 + ], + "end": [ + 0, + 10 + ], + "width": 4 + } + }, + { + "command": "body.extrude", + "params": { + "sketch": "sketch-1", + "depth": 3 + } + } + ], + "expect": { + "body_count": 1, + "bodies": [ + { + "body": "body-1", + "volume_mm3": { + "value": 226.1946710584651, + "tol": 1e-06 + }, + "bbox_min": { + "value": [ + -2, + -2, + 0 + ], + "tol": 1e-06 + }, + "bbox_max": { + "value": [ + 12, + 12, + 3 + ], + "tol": 1e-06 + }, + "faces": 6, + "valid": true, + "closed": true + } + ] + } +} diff --git a/Tests/IntegrationTests/test_mcp_stdio.py b/Tests/IntegrationTests/test_mcp_stdio.py index 365c6cd..5ab6f0a 100644 --- a/Tests/IntegrationTests/test_mcp_stdio.py +++ b/Tests/IntegrationTests/test_mcp_stdio.py @@ -58,6 +58,62 @@ def test_invalid_step_keeps_stdout_valid_json(self): self.assertFalse(responses[2]["result"]["isError"]) self.assertEqual(responses[2]["result"]["structuredContent"]["bodies"], []) + def test_face_sketch_conversion_builds_an_analytic_boss(self): + executable = os.environ.get("FORGE_CLI", ".build/debug/forge-cli") + responses = self.run_calls(executable, [ + ("new_document", {}), + ("execute", {"command": "body.create_box", "params": {"width": 10, "height": 20, "depth": 30}}), + ("execute", {"command": "sketch.create", "params": {"face": "body-1/face-5"}}), + ("convert_entities", {"entities": ["body-1/face-5"]}), + ("execute", {"command": "sketch.exit", "params": {}}), + ("execute", {"command": "body.extrude", "params": {"sketch": "sketch-1", "depth": 2}}), + ("compare_to_spec", {"spec": {"body_count": 2, "bodies": [ + {"body": "body-1", "volume_mm3": {"value": 6000, "tol": 1e-6}}, + {"body": "body-2", "volume_mm3": {"value": 400, "tol": 1e-6}}, + ]}}), + ]) + for response in responses: + self.assertFalse(response["result"]["isError"], response) + self.assertTrue(responses[-1]["result"]["structuredContent"]["passed"]) + + def test_curved_slot_measurement_and_body_visibility(self): + import math + executable = os.environ.get("FORGE_CLI", ".build/debug/forge-cli") + with tempfile.TemporaryDirectory() as temporary: + saved = str(Path(temporary) / "curved-slot.forgepart") + responses = self.run_calls(executable, [ + ("new_document", {}), + ("execute", {"command": "sketch.create", "params": {"plane": "front"}}), + ("execute", {"command": "sketch.add_arc_slot", "params": { + "center": [0, 0], "start": [10, 0], "end": [0, 10], "width": 4}}), + ("execute", {"command": "sketch.exit", "params": {}}), + ("execute", {"command": "body.extrude", "params": {"sketch": "sketch-1", "depth": 3}}), + ("measure", {"from": "body-1"}), + ("execute", {"command": "view.set_visibility", "params": {"bodies": ["body-1"], "visible": False}}), + ("execute", {"command": "view.isolate", "params": {"bodies": ["body-1"]}}), + ("save", {"path": saved}), + ]) + for response in responses: + self.assertFalse(response["result"]["isError"], response) + measured = responses[5]["result"]["structuredContent"]["from_entity"] + self.assertAlmostEqual(measured["volume_mm3"], 72 * math.pi, places=6) + self.assertEqual(responses[6]["result"]["structuredContent"]["result"]["visible_bodies"], []) + self.assertEqual(responses[7]["result"]["structuredContent"]["result"]["visible_bodies"], ["body-1"]) + reopened = self.run_calls(executable, [ + ("open", {"path": saved}), ("rebuild", {}), + ("execute", {"command": "document.state", "params": {}}), + ("execute", {"command": "view.show_all", "params": {}}), + ("measure", {"from": "body-1"}), + ]) + for response in reopened: + self.assertFalse(response["result"]["isError"], response) + visibility = reopened[2]["result"]["structuredContent"]["result"]["visibility"] + self.assertEqual(visibility["hidden_bodies"], ["body-1"]) + self.assertEqual(visibility["visible_bodies"], []) + self.assertIsNone(visibility.get("isolated_bodies")) + self.assertEqual(reopened[3]["result"]["structuredContent"]["result"]["visible_bodies"], ["body-1"]) + self.assertAlmostEqual(reopened[4]["result"]["structuredContent"]["from_entity"]["volume_mm3"], 72 * math.pi, places=6) + def run_calls(self, executable, calls): messages = [{"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-11-25"}}] messages.extend({"jsonrpc": "2.0", "id": index + 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}} diff --git a/Tests/NativeGTKTests/MenuActionTests.c b/Tests/NativeGTKTests/MenuActionTests.c index 488d974..30afb3a 100644 --- a/Tests/NativeGTKTests/MenuActionTests.c +++ b/Tests/NativeGTKTests/MenuActionTests.c @@ -1,6 +1,7 @@ -// Exercise the real native menu model and action group, without opening file dialogs. +// Exercise the real native menu/action group and name-entry dialog without Swift. #include "gtk_internal.h" #include +#include #include typedef struct { @@ -57,6 +58,81 @@ static void checkWidgets(fw_app *app, GtkWidget *widget, TestState *state) { } } +typedef struct { + TestState *state; + const char *title; + const char *initial; + const char *replacement; + int response; + int responded; + gint64 deadline; +} NameResponse; + +static GtkWidget *findEntry(GtkWidget *widget) { + if (GTK_IS_ENTRY(widget)) return widget; + for (GtkWidget *child = gtk_widget_get_first_child(widget); child; child = gtk_widget_get_next_sibling(child)) { + GtkWidget *entry = findEntry(child); + if (entry) return entry; + } + return NULL; +} + +// fw_name_dialog runs GTK's nested main loop. Drive its actual widgets from that loop, +// rather than replacing the dialog function with a mock. Both this deadline and the +// shell timeout prevent a broken response connection from hanging CI indefinitely. +static gboolean respondToName(gpointer data) { + NameResponse *response = data; + if (g_get_monotonic_time() >= response->deadline) { + fprintf(stderr, "Timed out waiting for name dialog: %s\n", response->title); + exit(1); + } + GListModel *windows = gtk_window_get_toplevels(); + for (guint i = 0; i < g_list_model_get_n_items(windows); ++i) { + GtkWindow *window = g_list_model_get_item(windows, i); + if (GTK_IS_DIALOG(window) && g_strcmp0(gtk_window_get_title(window), response->title) == 0) { + GtkWidget *entry = findEntry(GTK_WIDGET(window)); + if (!entry) { + fprintf(stderr, "Name dialog has no editable entry\n"); + ++response->state->failures; + } else { + if (strcmp(gtk_editable_get_text(GTK_EDITABLE(entry)), response->initial) != 0) { + fprintf(stderr, "Name dialog did not preserve initial UTF-8 text\n"); + ++response->state->failures; + } + gtk_editable_set_text(GTK_EDITABLE(entry), response->replacement); + } + response->responded = 1; + gtk_dialog_response(GTK_DIALOG(window), response->response); + g_object_unref(window); + return G_SOURCE_REMOVE; + } + g_object_unref(window); + } + return G_SOURCE_CONTINUE; +} + +static void checkNameDialog(fw_app *app, TestState *state, int action, const char *text) { + NameResponse response = {state, "Rename regression", "Original — 部品", text, action, 0, + g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND}; + guint source = g_timeout_add(10, respondToName, &response); + char *name = fw_name_dialog(app, response.title, response.initial); + if (!response.responded) { + g_source_remove(source); + fprintf(stderr, "Name dialog returned before a response\n"); + ++state->failures; + } + if (action == GTK_RESPONSE_ACCEPT) { + if (!name || strcmp(name, text) != 0) { + fprintf(stderr, "Name dialog did not return exact accepted UTF-8 text\n"); + ++state->failures; + } + } else if (name != NULL) { + fprintf(stderr, "Cancelled name dialog returned a value\n"); + ++state->failures; + } + fw_free(name); // Includes the cancellation path: freeing NULL must be harmless. +} + int main(void) { TestState state = {0}; fw_app *app = fw_app_create("Menu action regression", receive, &state); @@ -70,8 +146,12 @@ int main(void) { state.actions, state.importItems, state.importEvents); ++state.failures; } + checkNameDialog(app, &state, GTK_RESPONSE_ACCEPT, "机架 — café 🚀"); + checkNameDialog(app, &state, GTK_RESPONSE_CANCEL, "discarded replacement"); + checkNameDialog(app, &state, GTK_RESPONSE_ACCEPT, ""); fw_app_destroy(app); if (state.failures) return 1; printf("GTK menu actions: %d registered entries; Import STEP dispatch passed\n", state.actions); + printf("GTK name dialog: UTF-8 accept, cancellation and empty input passed\n"); return 0; } diff --git a/docs/research/modeling-workflow-gaps.md b/docs/research/modeling-workflow-gaps.md new file mode 100644 index 0000000..162df92 --- /dev/null +++ b/docs/research/modeling-workflow-gaps.md @@ -0,0 +1,1355 @@ +# Modeling workflow gaps and complete matrix inventory + +Audit date: 2026-09-30. Source baseline: `2ab8a66`, before the follow-up workflow fixes. +This document compares the repository's declared scope with actual command registrations, +shared UI models, native shell bindings, and public SOLIDWORKS documentation. It is a +source audit, not a completed interactive test on all three operating systems. Findings +remain baseline findings if the implementation changes after this audit. + +The scope in [SPEC](../../SPEC.md) is explicitly a multi-year product. The appendix +accounts for **every one of the 1,000 FEATURES rows**, grouped by its original section. +It does not claim to enumerate every behavior of every SOLIDWORKS release/add-in, nor +that reading a row independently verifies its implementation. Rows overlap and vary +in size; status counts are not a percentage of product functionality. + +## Follow-up delivery: eight everyday workflows + +The follow-up changes address the following eight workflows. This section describes +implemented source paths and their regression coverage; the baseline findings and +1,000-row appendix below are intentionally preserved as the pre-change snapshot. +Native macOS/Windows interactive behavior still requires validation on those systems. + +| Workflow delivered | Actual scope and evidence | Remaining boundary | +|---|---|---| +| 1. Start a sketch on the selected face | `SketchPlacementWorkflows.swift` and both ribbons expose Sketch on Face from the Features tab as well as the Sketch tab. The shared action respects the selected face; body/edge selections no longer silently choose Front. `SketchPlacementWorkflowTests` covers viewport face picking, placement/camera, drawing a profile and cutting, and invalid/curved selections. | Builds on existing planar-face engine support; arbitrary curved-surface sketching and automatic face-selected Cut → sketch → resume are still absent. | +| 2. Convert selected model edges/face boundaries | New registered `sketch.convert_entities` plus Select Model Geometry and Convert Entities UI actions. Exact projections support lines and circular edges parallel to the sketch plane, deduplicate shared boundaries, optionally mark construction geometry, and fix curves by default. `SketchConvertTests` and `SketchPlacementWorkflowTests` cover engine/UI paths. | These are detached snapshots, not associative On Edge references. Source edits do not resize converted curves. Oblique circular, ellipse, spline and degenerate projections are rejected atomically. | +| 3. Split sketch entities interactively | Shared `SketchTool.split`, both ribbons, on-curve clicks, pending-point state for closed curves and cancellation call the existing `sketch.split` command. `SketchSplitWorkflowTests` covers supported interactions. | Unsupported splines remain unsupported; this does not implement the entire sketch repair or combine-split-entities workflow. | +| 4. Move/Copy Bodies from the inspector | New Move/Copy Bodies operation, shared/mac property pages and ribbon action expose translation, rotation and copy. Existing transform features can be reopened; arbitrary stored rotation axes are retained. `BodyPlacementWorkflowTests` covers copy/rotate/translate, edit/undo and custom-axis round-trip. | No direct-manipulation triad, mate-based placement or assembly components are implied. | +| 5. Edit Up To Vertex extrusions faithfully | Both inspector paths now represent Up To Vertex and its coordinate values, including direction 2, rather than defaulting a stored end condition to Blind. Feature editing retains this supported mode. | A coordinate termination is not a persistent topological vertex reference. Up-to-surface/next/body and selected-contour support remain separate gaps. | +| 6. Normal To selected geometry | Shared `normalToSelection()` resolves a picked planar face or plane, and Normal To availability includes suitable selection without an active sketch. Existing active-sketch alignment remains. `BodyPlacementWorkflowTests` covers face alignment. | Cylindrical/conical alignment, two-face orientation, reverse-normal toggling, named views and complete plane-selection affordances are not claimed. | +| 7. Rename bodies from the tree | Shared `RenameWorkflows.swift`, body-tree Rename actions and native name dialogs call `body.rename` by stable identity. `RenameWorkflowTests` covers Unicode, cancellation/no-op, invalid names, undo/redo and package reopen. | This edits the body's display name; it does not rename external files or implement reference-preserving Pack and Go. | +| 8. Rename features and absorbed sketches on each desktop | Shared/mac tree Rename actions call `feature.rename`; absorbed sketch rows use their owning sketch feature. macOS, GTK and Win32 provide native text entry; headless services cancel by default. The same rename regression suite checks action availability and persistence. | This supplies consistent naming access; folders, feature freeze, configuration-specific naming and native-platform accessibility certification remain outside this change. | + +The follow-up also fixes supporting feature-edit and persistent-reference issues found +while exercising these paths. It does **not** complete the remaining families below: +selection filters/Select Other, hide/show/isolate, face/edge measurement, region picking, +assemblies, drawings, simulation, manufacturing and the remaining matrix backlog. +Full test/build outcomes belong in the PR and PROGRESS record; this document makes no +independent all-tests-passed claim. + +## Further delivery: measurement, body visibility and curved slots + +The next implementation adds `query.measure` for bodies and individual faces, edges +and vertices, including persistent face/edge names. One selection reports its physical +size or coordinates; two report B-rep minimum distance, closest points and XYZ deltas. +The desktop accepts either selection count and displays command errors. Angles, +maximum/normal distances and sketch-entity measurement remain pending. + +Body visibility now has registered show/hide/isolate/exit/show-all commands. Hidden +bodies remain in modeling and export, but are excluded from rendering, picking and +framing. Ordinary hidden state persists, including suppressed feature output intent; +isolation is temporary and exits to the prior state. Tree, ribbon and macOS View/context +actions expose the commands. Components, individual sketch and plane visibility still +need their own display-pane workflows. + +Centerpoint and three-point arc slots create editable concentric sides and tangent +semicircular caps, with a construction centerline. All four slot variants are available +in desktop tool choices; curved slots use four clicks with a live boundary preview. +Command and desktop regressions cover analytic extrusion volume, solver degrees of +freedom, width editing, construction, atomic validation, undo and persistence. Grouped +Fix Slot/Equal Slots relations remain pending. + + +## How to interpret the evidence + +- **Engine available, guided UI missing** means there is a registered command but no + corresponding ordinary tool/property page found. The macOS JSON command palette, + CLI, or MCP may still reach it. Windows/Linux do not have equivalent command palettes. +- **Partial** means an actual implementation exists but its supported options or + platform path are narrower than the workflow. A toolbar label does not establish parity. +- **Absent** means the relevant model/command/UI was not found, corroborated by the + matrix. A kernel operation or rendered picture is not a finished product workflow. +- **Present, verify interaction** means source contains a viable path. It must not be + described as absent solely because FEATURES or an older research note is stale. + +Every delivered model operation still needs SPEC §0 proof: deterministic rebuild, +persistence, undo/redo, command/MCP exposure, and regression coverage. UI features +add selection, preview/cancel, edit-existing, keyboard, and per-platform interaction tests. + +## Highest-value everyday gaps + +| Priority / workflow | Baseline classification and evidence | Concrete implementation and acceptance criterion | +|---|---|---| +| P0: edit an extrusion without changing its meaning | Partial, with a data-integrity hazard. `Commands/ProfileCommands.swift` supports `up_to_vertex`; `ForgeUI/PropertyManager.swift` has only four `EndConditionUI` cases and maps unknown stored values to `.blind` in `editFeature`. | Preserve or explicitly reject unsupported edit options; preferably expose Up To Vertex for both directions. An MCP-created up-to-vertex feature opened and committed unchanged must retain its termination reference/value and geometry. Changing only its name or unrelated option must not turn it into Blind. | +| P1: Normal To a selected face/plane | Engine camera primitive available, guided selection workflow missing. `AppModel.normalToSketch()` only reads `sketchState.plane`; the macOS command is disabled without an active sketch. WinShell uses the same method. | Resolve a selected planar face/reference plane without creating a sketch; support explicit failure for unsuitable geometry. Align, retain target/zoom sensibly, and return using Previous View. Test on an offset and tilted planar face. [Official Normal To behavior](https://help.solidworks.com/2014/English/solidworks/sldworks/t_viewing_models_normal_to.htm). | +| P1: Split Entities with the mouse | Engine available, guided UI missing. `SketchSplit` is registered and implemented; `SketchTool`, shared ribbon and macOS ribbon expose Trim/Extend but not Split. | Add a split tool: one on-curve point for open entities, two for closed entities; preview pending points, cancel safely, preserve constraints or explain removals. Undo restores the original curve. Spline support remains a separate kernel/solver gap. [Official Split Entities](https://help.solidworks.com/2026/english/SolidWorks/sldworks/c_split_entities.htm). | +| P1: Move/Copy Body | Engine available, guided UI missing. `BodyTransform` is registered, but `Operation` and `FeatureRow.operation` have no body-transform property page. A move icon alone does not allow editing. | Provide body selection, translation/rotation, copy choice, numeric units and preview. Reopen/edit the resulting feature without losing its transform. Test rotate then translate and copy versus move independently. [Official features toolbar](https://help.solidworks.com/2026/english/SolidWorks/sldworks/r_Features_Toolbar.htm). | +| P1: Rename features and bodies on every desktop | Engine available, platform UI gap. `FeatureRename`/`BodyRename` registered. macOS `FeatureTree.swift` has feature rename; shared `TreeSpec` menus do not. Body menus only measure/export. | Add shared rename affordances with current value, cancellation and invalid-input errors. Verify tree refresh, document reopen and undo; identity-based references must survive renames. | +| P1: Measure two selected faces/edges | Partial, misleading UI/error handling. `QueryMeasure.run` rejects non-body references. UI `computeMeasure()` passes selected refs and uses `try?`; the mac context Measure button accepts any two selections. | Either restrict and explain supported body-only scope or implement topology-level distance/angle measurement. Picking two faces must produce a value with units or a visible supported-scope error, never a silently blank result. | +| P1: Convert Entities | Absent. FEATURES `7.1/tools/convert-entities`; no conversion command in registry. | Project selected model edges/loops into the active sketch and retain external references through rebuild. A face sketch should copy an existing hole boundary without redrawing it. Start with planar lines/circles; explicitly reject unsupported curves. [Official Convert Entities](https://help.solidworks.com/2026/english/SolidWorks/Sldworks/c_Convert_Entities.htm). | +| P1: Hide/show/isolate solids and sketches | Absent as a persisted per-entity workflow. `DisplayOptions` controls global overlays; no hide/show body command in the registry or body tree menus. Preview hiding is temporary rendering machinery. | Hide an obstructing body without suppressing its features; restore it from the tree; isolate then restore prior states; reflect state through MCP and save/open. [Official Hide and Show Bodies](https://help.solidworks.com/2026/english/SolidWorks/sldworks/HIDD_HIDE_SHOW.htm). | +| P1: Selection filters / Select Other | Absent. `P/smart-selection` is not started; native pick calls return a single hit and no filter/candidate-cycle UI was found. | Choose faces/edges/sketch entities explicitly; list candidates behind the pointer with hover highlight. Hidden selections must not require rotating the whole model. [Filters](https://help.solidworks.com/2026/english/SolidWorks/sldworks/r_selection_filter.htm), [Select Other](https://help.solidworks.com/2024/English/solidworks/sldworks/HIDD_SelectOther_dlg.htm). | +| P1: Extrude only one region | Partial geometry detection, absent region-selection workflow. `PanelSpec` explicitly says all closed regions are used; `7.2/.../contour-selection` not started. | Pick a region in a multi-loop sketch, preview exactly that region, store stable contour intent, and retain it after an unrelated sketch edit. Closed nested holes must remain distinct from independently selectable regions. | + +## Face-based sketching: implemented path and remaining pitfalls + +`SketchMode.newSketch(onPlaneOrFace:)` already passes a face reference to `sketch.create`, +aligns to the resulting sketch, and enters the line tool. `RibbonSpec.sketchGroups` +selects the chosen face for its primary action and adds an On Selected Face flyout. +`ForgeApp/Ribbon.swift` also offers On Selected Face; `ViewportOverlays` offers a +context Sketch action on macOS. Standard and reference planes have tree actions. +This is **present, verify interaction**, not absent. + +The important gaps are discoverability and consistency. `selectedFace` checks only +entity kind, despite its comment saying planar; it can offer sketch-on-face for a +curved surface and defer rejection to the command. There is no guided plane-selection +step after pressing Sketch with no suitable selection; the shared primary action +silently uses Front. Native Win/Linux lack the mac context bar. Clicking Extruded Cut +with a face selected does not start a face sketch and resume the pending feature: +feature buttons are gated by existing sketches. That SOLIDWORKS workflow is documented +in [the lip tutorial](https://help.solidworks.com/2026/english/swtutorialonline/t_tut_lesson2_creatinglip.htm). + +Acceptance: create a box, select each of its six planar faces in turn, create a sketch, +place a dimensioned circle, cut through the body, change the parent box thickness, +and save/reopen. Confirm face normal, origin, sketch coordinates, downstream reference +identity and camera orientation. Repeat on a transformed body and an imported solid. +A cylindrical side face should receive an actionable explanation, with no empty sketch +left behind. Full sketch-on-arbitrary-surface and 3D sketching remain separate missing work. + +## Sketching: remaining work beyond exposing existing commands + +- Geometry: arc slots, parabola/conic, sketch text/fonts, style/fit/equation-driven + splines, sketch pictures/calibration/autotrace, blocks, derived sketches and full + 3D sketching remain matrix gaps. Existing point/control-point splines are not a + full surface-design toolset. +- Tools: convert/intersection/silhouette entities, dynamic mirror, stretch, jog, + repair/fully-define sketch, and spline curvature controls remain absent. Existing + offset handles line/arc chains and circles, not exact ellipse/spline offsets; + cap ends are straight. Trim/split lack splines. Sketch patterns place instances + but their spacing/angle is not an editable driving pattern dimension. +- Constraints: existing 2D solver handles substantial ordinary relations, but + equal curvature, curve-length equality, 3D axis/plane/surface relations, pierce, + and external on-edge references need separate work. Spline tangency away from + endpoints is explicitly not implemented in `Constraints.swift`. +- Dimensions: ordinary linear/radial/diameter/angular and driven values exist; + ordinate/baseline/chain, arc/path length, min/max arc conditions, unit-aware + expressions/global variables and auto fully-definition are not completed. +- Repair UX: errors and executable suggestions exist, but a complete conflict + exploration/repair panel is not equivalent to a transient error banner. Test + delete/make-driven suggestions and cancellation without creating solver drift. + +[Official sketch relations](https://help.solidworks.com/2026/english/solidworks/sldworks/c_Description_of_Sketch_Relations.htm) +define entity-specific semantics; acceptance must measure residuals and degrees of +freedom after drag/edit, not count relation icons. + +## Features, editing and navigation + +The registry and property pages already expose extrude/revolve, sweep/loft/rib, +fillet/chamfer/shell/draft, holes, patterns/mirror, booleans and reference planes. +History supports suppression, rollback, edit, rename, reorder, parent/child lookup, +and reference repair. These are real starting points, not complete family parity. + +Remaining feature variants include up-to-next/surface/body/offset extrusion, +open-profile thin features, revolve direction 2/up-to modes, sweep twist/guide curves/ +solid tool, loft guide curves/centerline/tangency/point profiles, curved ribs, +variable/full-round/setback fillets, expanded chamfers/draft/shell variants, full hole +standards/types, surface creation/editing, direct face editing, recognition and +mesh-to-BREP tools. `PatternCommands` restricts feature seeds to extrusions, +revolutions and Hole Wizard holes; exposing Pattern for every body is not evidence +that every feature can be patterned. See the row inventory for all named variants. +[Official extrusion conditions](https://help.solidworks.com/2023/english/solidworks/sldworks/c_end_condition_extrude.htm) +and [features toolbar](https://help.solidworks.com/2026/english/SolidWorks/sldworks/r_Features_Toolbar.htm) +provide behavioral/reference scope. + +Editing additionally needs global variables, equations, linked dimensions, +configurations/design tables, folders/freeze, robust vertex naming, full preview +cancellation and topology repair UI, and feature parameter coverage on every shell. +The whole edit pipeline should preserve unknown/unexposed stored parameters or +explicitly refuse editing; reconstructing only visible controls is a corruption risk. + +Navigation has fit, previous view, standard orientations, styles, projection, +orbit/pan/zoom, sketch normal and a mac orientation palette. Remaining workflows: +zoom-to-selection/area, custom named views, selected-face normal including reverse, +section clipping/caps, per-entity transparency/display states, selection sets, +3Dconnexion and configurable shortcuts. Reference planes are rendered under a shared +non-document object ID and picks ignore them; use tree selection until meaningful +viewport plane selection is implemented. Keyboard-only/accessibility and large-model +performance require measured tests, not only API hooks. + +## Broader product scope: do not conflate neighboring capabilities + +| Group | Current audit conclusion | First coherent delivery slice | +|---|---|---| +| Surfacing, sheet metal, weldments, mold/tooling | Families overwhelmingly/not started; solid loft/sweep do not provide surface editing or manufacturable flat patterns. | Valid surface body model; separate bend/flat-pattern and weldment profile/cut-list milestones. | +| Assemblies / motion | No ForgeAssembly target or component/mate command family. Multibody transforms and `query.interference` are not components, mates or motion studies. | Saved instances with stable document references, ground/float, plane/concentric mates, DOF/conflict diagnostics; then subassemblies/interference/motion. [Mate compatibility](https://help.solidworks.com/2022/English/SolidWorks/sldworks/r_Standard_Mates_by_Entity.htm). | +| Drawings / BOM / MBD / tolerance | No ForgeDrawing or associative drawing command family. Raster multiview rendering is not drafting or semantic PMI. | Sheet/scale/model views, projected/section/detail views and associative dimensions; then BOM/balloons, GD&T and export. [Drawing views](https://help.solidworks.com/2026/english/SolidWorks/Sldworks/c_derived_drawing_views.htm), [BOM updates](https://help.solidworks.com/2020/english/SolidWorks/sldworks/c_bill_of_materials_-_overview2.htm). | +| Analysis / FEA / CFD / plastics | Geometry validity, distance, volume/area/centroid and solid interference are implemented subsets. No study/mesh/load/solve/result pipeline or simulation target. | Materials plus calibrated mass/inertia; independent linear-static benchmark with convergence, then additional physics as separate verified studies. | +| Routing / electrical / CAM | No corresponding package target/command pipelines. All enumerated specialized workflows remain future work. | Typed route/component/netlist and manufacturing stock/tool/operation models before user-facing authoring or generated manufacturing output. | +| Rendering | Working viewport/headless rendering is a subset; photoreal, PBR/material authoring, advanced lighting/environment, animations and publishing remain gaps. | Persist appearances and display states, then physically based lighting and independent image-quality/performance fixtures. | +| Data management | Local package persistence/history exists; not vault/check-in/out/revision workflows, permissions or server collaboration. | Explicit file references, recovery/backup and reference-preserving pack-and-go before managed vault workflows. | +| Exchange | STEP solid import plus STEP/STL export and native packages exist. Mixed surface/wire STEP is explicitly rejected; no assembly-instance import model, PMI, native SOLIDWORKS translator or general mesh import. | Round-trip fixtures for supported solid units/topology; separate assembly, surface and PMI support. [Official file support](https://help.solidworks.com/2026/english/SolidWorks/sldworks/c_import_export_file_information.htm). | +| Automation / ease of use | Shared command/MCP/CLI foundation exists; plugins, macro recording, typed inline palette inputs, customization and all-platform discoverability are incomplete. | Shared UI actions over commands, queryable active state, realistic tutorials and end-to-end MCP/UI equivalence fixtures. | + +## Inventory discrepancies to reconcile + +The matrix should remain conservative, but some notes are stale. Sketch-on-face is +marked not started despite actual planar support. Many sketch rows still say no +feature-tree item although sketches are features. Power trim says no drag-across UI +although `SketchMode` contains trimmed-in-drag handling. Some command descriptions +claim ellipse split/trim and point-on-spline are absent while implementations/matrix +show later work. Counts of golden models and older engine/import capability notes +also predate later changes. Reconcile each with its actual tests; do not bulk-upgrade +statuses from names alone. The appendix deliberately preserves the matrix's reported +status instead of converting these discrepancies into unsupported completion claims. + +## Complete matrix coverage at baseline + +The following inventory includes every matrix row ID exactly once. Group-level +acceptance is specified above and in [the earlier parity audit](solidworks-parity-audit.md). +For individual ownership, named tests, MCP tool and existing limitations, follow the +same ID in [FEATURES.md](../../FEATURES.md). `not started` means a backlog entry, +`in progress` means partial, `done` is the repository's declared completion status, +and `verified` requires the additional SPEC review criteria. None is a new result +of running tests during this read-only audit. + +| Matrix group | Rows | Not started | In progress | Done | Verified | +|---|---:|---:|---:|---:|---:| +| Platform (SPEC §2–§6, §8–§9) | 61 | 13 | 22 | 26 | 0 | +| 7.1 Sketching (2D and 3D) | 120 | 54 | 66 | 0 | 0 | +| 7.2 Part features | 156 | 119 | 36 | 1 | 0 | +| 7.3 Surfacing | 28 | 28 | 0 | 0 | 0 | +| 7.4 Sheet metal | 36 | 36 | 0 | 0 | 0 | +| 7.5 Weldments | 13 | 13 | 0 | 0 | 0 | +| 7.6 Mold / tooling | 11 | 11 | 0 | 0 | 0 | +| 7.7 Assemblies | 102 | 102 | 0 | 0 | 0 | +| 7.8 Motion | 21 | 21 | 0 | 0 | 0 | +| 7.9 Drawings | 96 | 96 | 0 | 0 | 0 | +| 7.10 Model-Based Definition (MBD) | 7 | 7 | 0 | 0 | 0 | +| 7.11 Tolerance & quality | 11 | 11 | 0 | 0 | 0 | +| 7.12 Analysis tools (in-part) | 33 | 29 | 3 | 1 | 0 | +| 7.13 Simulation (FEA) | 86 | 86 | 0 | 0 | 0 | +| 7.14 Flow Simulation (CFD) | 34 | 34 | 0 | 0 | 0 | +| 7.15 Plastics | 12 | 12 | 0 | 0 | 0 | +| 7.16 Routing & electrical | 36 | 36 | 0 | 0 | 0 | +| 7.17 Rendering & visualization | 28 | 28 | 0 | 0 | 0 | +| 7.18 CAM | 26 | 26 | 0 | 0 | 0 | +| 7.19 Data management | 26 | 26 | 0 | 0 | 0 | +| 7.20 Import / export | 36 | 34 | 2 | 0 | 0 | +| 7.21 Customization & automation | 13 | 11 | 2 | 0 | 0 | +| Discovered (SolidWorks capabilities not listed in SPEC §7) | 8 | 8 | 0 | 0 | 0 | +| **Total** | **1000** | **841** | **131** | **28** | **0** | + +### Platform (SPEC §2–§6, §8–§9) + +| Matrix ID | Recorded status | +|---|---| +| `P/kernel-bridge` | done | +| `P/kernel-primitives` | done | +| `P/kernel-booleans` | done | +| `P/kernel-queries` | done | +| `P/kernel-tessellation` | done | +| `P/kernel-brep-io` | done | +| `P/command-bus` | done | +| `P/command-schema` | done | +| `P/units` | done | +| `P/structured-errors` | done | +| `P/undo-redo` | done | +| `P/transactions` | done | +| `P/dry-run` | done | +| `P/batch` | done | +| `P/explicit-state` | in progress | +| `P/journal` | in progress | +| `P/forge-cli` | done | +| `P/golden-models` | in progress | +| `P/determinism` | in progress | +| `P/mcp-stdio` | done | +| `P/mcp-socket` | done | +| `P/mcp-discovery` | done | +| `P/mcp-document` | done | +| `P/mcp-open-save` | in progress | +| `P/mcp-export` | done | +| `P/mcp-mutate` | done | +| `P/mcp-feature-tools` | in progress | +| `P/mcp-query-geometry` | not started | +| `P/mcp-vision` | in progress | +| `P/mcp-verification` | in progress | +| `P/mcp-interference` | done | +| `P/mcp-resources` | in progress | +| `P/mcp-prompts` | in progress | +| `P/plugins-swift` | not started | +| `P/scripting-js` | not started | +| `P/scripting-python` | not started | +| `P/macro-recorder` | not started | +| `P/feature-tree` | in progress | +| `P/persistent-naming` | in progress | +| `P/semantic-refs` | not started | +| `P/parameters` | not started | +| `P/file-format` | in progress | +| `P/background-regen` | in progress | +| `P/metal-viewport` | in progress | +| `P/headless-render` | done | +| `P/app-shell` | in progress | +| `P/app-model-shared` | done | +| `P/windows-app` | in progress | +| `P/windows-engine` | done | +| `P/linux-app` | in progress | +| `P/linux-install` | done | +| `P/command-palette` | in progress | +| `P/inspector` | in progress | +| `P/handles` | not started | +| `P/explainable-failures` | not started | +| `P/smart-selection` | not started | +| `P/input-devices` | in progress | +| `P/accessibility` | not started | +| `P/performance` | not started | +| `P/ci` | in progress | +| `P/fuzzing` | not started | + +### 7.1 Sketching (2D and 3D) + +| Matrix ID | Recorded status | +|---|---| +| `7.1/entities/line` | in progress | +| `7.1/entities/centerline` | in progress | +| `7.1/entities/midpoint-line` | in progress | +| `7.1/entities/rectangle` | in progress | +| `7.1/entities/rectangle/corner` | in progress | +| `7.1/entities/rectangle/center` | in progress | +| `7.1/entities/rectangle/3-point` | in progress | +| `7.1/entities/rectangle/parallelogram` | in progress | +| `7.1/entities/slot` | in progress | +| `7.1/entities/slot/straight` | in progress | +| `7.1/entities/slot/center` | in progress | +| `7.1/entities/slot/arc` | not started | +| `7.1/entities/slot/3-point-arc` | not started | +| `7.1/entities/circle` | in progress | +| `7.1/entities/circle/center` | in progress | +| `7.1/entities/circle/perimeter` | in progress | +| `7.1/entities/arc` | in progress | +| `7.1/entities/arc/center` | in progress | +| `7.1/entities/arc/tangent` | in progress | +| `7.1/entities/arc/3-point` | in progress | +| `7.1/entities/polygon` | in progress | +| `7.1/entities/ellipse` | in progress | +| `7.1/entities/partial-ellipse` | in progress | +| `7.1/entities/parabola` | not started | +| `7.1/entities/conic` | not started | +| `7.1/entities/spline` | in progress | +| `7.1/entities/spline/point-control-vertex` | in progress | +| `7.1/entities/spline/style-spline` | not started | +| `7.1/entities/spline/equation-driven-curve` | not started | +| `7.1/entities/spline/fit-spline` | not started | +| `7.1/entities/point` | in progress | +| `7.1/entities/text` | not started | +| `7.1/entities/text/with-fonts` | not started | +| `7.1/entities/construction-geometry` | in progress | +| `7.1/entities/fillet-chamfer` | in progress | +| `7.1/entities/fillet-chamfer/sketch` | in progress | +| `7.1/tools/trim` | in progress | +| `7.1/tools/trim/power` | in progress | +| `7.1/tools/trim/corner` | not started | +| `7.1/tools/trim/inside-outside` | not started | +| `7.1/tools/extend` | in progress | +| `7.1/tools/offset` | in progress | +| `7.1/tools/offset/bi-directional` | in progress | +| `7.1/tools/offset/cap-ends` | in progress | +| `7.1/tools/offset/construction` | in progress | +| `7.1/tools/convert-entities` | not started | +| `7.1/tools/intersection-curve` | not started | +| `7.1/tools/silhouette-entities` | not started | +| `7.1/tools/mirror` | in progress | +| `7.1/tools/mirror/static-dynamic` | in progress | +| `7.1/tools/linear-circular-sketch-patterns` | in progress | +| `7.1/tools/move-copy-rotate-scale-stretch` | in progress | +| `7.1/tools/split-entities` | in progress | +| `7.1/tools/jog-line` | not started | +| `7.1/tools/sketch-picture` | not started | +| `7.1/tools/sketch-picture/with-scale-calibration` | not started | +| `7.1/tools/autotrace` | not started | +| `7.1/tools/sketch-blocks` | not started | +| `7.1/tools/sketch-blocks/create` | not started | +| `7.1/tools/sketch-blocks/insert` | not started | +| `7.1/tools/sketch-blocks/edit` | not started | +| `7.1/tools/sketch-blocks/explode` | not started | +| `7.1/tools/sketch-blocks/belts-chains` | not started | +| `7.1/tools/derived-sketch` | not started | +| `7.1/tools/shared-sketches` | not started | +| `7.1/tools/3d-sketch` | not started | +| `7.1/tools/3d-sketch/with-plane-switching` | not started | +| `7.1/tools/3d-sketch/3d-sketch-on-plane` | not started | +| `7.1/tools/sketch-on-face-surface` | not started | +| `7.1/tools/spline-tools` | not started | +| `7.1/tools/spline-tools/tangency-curvature-handles` | not started | +| `7.1/tools/spline-tools/simplify` | not started | +| `7.1/tools/spline-tools/fit` | not started | +| `7.1/tools/spline-tools/add-tangency-control` | not started | +| `7.1/tools/spline-tools/curvature-combs` | not started | +| `7.1/tools/instant2d` | not started | +| `7.1/tools/sketchxpert` | in progress | +| `7.1/tools/sketchxpert/conflict-repair` | in progress | +| `7.1/tools/check-sketch-for-feature` | in progress | +| `7.1/tools/repair-sketch` | not started | +| `7.1/tools/sketch-contours-regions-selection` | in progress | +| `7.1/tools/sketch-ink-equivalent` | not started | +| `7.1/tools/sketch-ink-equivalent/pencil` | not started | +| `7.1/relations/coincident` | in progress | +| `7.1/relations/collinear` | in progress | +| `7.1/relations/coradial` | in progress | +| `7.1/relations/concentric` | in progress | +| `7.1/relations/horizontal` | in progress | +| `7.1/relations/vertical` | in progress | +| `7.1/relations/parallel` | in progress | +| `7.1/relations/perpendicular` | in progress | +| `7.1/relations/tangent` | in progress | +| `7.1/relations/equal` | in progress | +| `7.1/relations/symmetric` | in progress | +| `7.1/relations/midpoint` | in progress | +| `7.1/relations/fix` | in progress | +| `7.1/relations/merge` | in progress | +| `7.1/relations/pierce` | not started | +| `7.1/relations/intersection` | not started | +| `7.1/relations/along-x-y-z` | not started | +| `7.1/relations/along-x-y-z/3d` | not started | +| `7.1/relations/equal-curvature` | not started | +| `7.1/relations/on-edge` | in progress | +| `7.1/relations/curve-length-equal` | not started | +| `7.1/relations/automatic-relations-with-inference` | in progress | +| `7.1/relations/display-delete-relations` | in progress | +| `7.1/dimensions/smart-dimension` | in progress | +| `7.1/dimensions/smart-dimension/linear` | in progress | +| `7.1/dimensions/smart-dimension/angular` | in progress | +| `7.1/dimensions/smart-dimension/radial` | in progress | +| `7.1/dimensions/smart-dimension/diameter` | in progress | +| `7.1/dimensions/smart-dimension/arc-length` | not started | +| `7.1/dimensions/smart-dimension/path-length` | not started | +| `7.1/dimensions/driven-reference` | in progress | +| `7.1/dimensions/ordinate` | not started | +| `7.1/dimensions/chain` | not started | +| `7.1/dimensions/baseline` | not started | +| `7.1/dimensions/fully-define-sketch` | not started | +| `7.1/dimensions/dimension-to-min-max-arc-condition` | not started | +| `7.1/dimensions/equations-in-dimension-fields` | not started | + +### 7.2 Part features + +| Matrix ID | Recorded status | +|---|---| +| `7.2/reference-geometry/planes` | in progress | +| `7.2/reference-geometry/planes/all-definitions` | not started | +| `7.2/reference-geometry/axes` | not started | +| `7.2/reference-geometry/coordinate-systems` | not started | +| `7.2/reference-geometry/points` | not started | +| `7.2/reference-geometry/center-of-mass` | not started | +| `7.2/reference-geometry/mate-references` | not started | +| `7.2/reference-geometry/bounding-box` | not started | +| `7.2/reference-geometry/reference-curves` | not started | +| `7.2/reference-geometry/reference-curves/projected` | not started | +| `7.2/reference-geometry/reference-curves/helix-spiral` | not started | +| `7.2/reference-geometry/reference-curves/composite` | not started | +| `7.2/reference-geometry/reference-curves/split-line` | not started | +| `7.2/reference-geometry/reference-curves/curve-through-xyz-points` | not started | +| `7.2/reference-geometry/reference-curves/curve-through-reference-points` | not started | +| `7.2/boss-base-and-cut/extrude` | in progress | +| `7.2/boss-base-and-cut/extrude/blind` | in progress | +| `7.2/boss-base-and-cut/extrude/through-all` | in progress | +| `7.2/boss-base-and-cut/extrude/up-to-next-vertex-surface-offset` | in progress | +| `7.2/boss-base-and-cut/extrude/mid-plane` | in progress | +| `7.2/boss-base-and-cut/extrude/thin-feature` | in progress | +| `7.2/boss-base-and-cut/extrude/draft` | in progress | +| `7.2/boss-base-and-cut/extrude/direction-2` | in progress | +| `7.2/boss-base-and-cut/extrude/contour-selection` | not started | +| `7.2/boss-base-and-cut/revolve` | in progress | +| `7.2/boss-base-and-cut/sweep` | in progress | +| `7.2/boss-base-and-cut/sweep/profile` | done | +| `7.2/boss-base-and-cut/sweep/solid-body-tool-sweep` | not started | +| `7.2/boss-base-and-cut/sweep/twist` | not started | +| `7.2/boss-base-and-cut/sweep/guide-curves` | not started | +| `7.2/boss-base-and-cut/sweep/path-alignment` | in progress | +| `7.2/boss-base-and-cut/loft` | in progress | +| `7.2/boss-base-and-cut/loft/guide-curves` | not started | +| `7.2/boss-base-and-cut/loft/centerline` | not started | +| `7.2/boss-base-and-cut/loft/start-end-constraints` | not started | +| `7.2/boss-base-and-cut/loft/tangency` | not started | +| `7.2/boss-base-and-cut/boundary-boss-cut` | not started | +| `7.2/boss-base-and-cut/thicken-thicken-cut` | not started | +| `7.2/boss-base-and-cut/cut-with-surface` | not started | +| `7.2/applied/fillet` | in progress | +| `7.2/applied/fillet/constant` | in progress | +| `7.2/applied/fillet/variable` | not started | +| `7.2/applied/fillet/face` | not started | +| `7.2/applied/fillet/full-round` | not started | +| `7.2/applied/fillet/setback` | not started | +| `7.2/applied/fillet/filletxpert` | not started | +| `7.2/applied/fillet/conic-curvature-continuous-profiles` | not started | +| `7.2/applied/chamfer` | in progress | +| `7.2/applied/chamfer/angle-distance` | in progress | +| `7.2/applied/chamfer/distance-distance` | in progress | +| `7.2/applied/chamfer/vertex` | not started | +| `7.2/applied/chamfer/offset-face` | not started | +| `7.2/applied/chamfer/face-face` | not started | +| `7.2/applied/draft` | in progress | +| `7.2/applied/draft/neutral-plane` | in progress | +| `7.2/applied/draft/parting-line` | not started | +| `7.2/applied/draft/step` | not started | +| `7.2/applied/draft/draftxpert` | not started | +| `7.2/applied/shell` | in progress | +| `7.2/applied/shell/multi-thickness` | not started | +| `7.2/applied/rib` | in progress | +| `7.2/applied/hole-wizard` | in progress | +| `7.2/applied/hole-wizard/counterbore` | in progress | +| `7.2/applied/hole-wizard/countersink` | in progress | +| `7.2/applied/hole-wizard/straight` | in progress | +| `7.2/applied/hole-wizard/tapped` | in progress | +| `7.2/applied/hole-wizard/pipe-tap` | not started | +| `7.2/applied/hole-wizard/legacy` | not started | +| `7.2/applied/hole-wizard/slot` | not started | +| `7.2/applied/hole-wizard/counterbore-countersink-slot` | not started | +| `7.2/applied/hole-wizard/ansi` | not started | +| `7.2/applied/hole-wizard/iso` | in progress | +| `7.2/applied/hole-wizard/din` | not started | +| `7.2/applied/hole-wizard/jis` | not started | +| `7.2/applied/hole-wizard/gb` | not started | +| `7.2/applied/hole-wizard/bsi` | not started | +| `7.2/applied/hole-wizard/ks` | not started | +| `7.2/applied/hole-wizard/as` | not started | +| `7.2/applied/hole-wizard/is` | not started | +| `7.2/applied/hole-wizard/pem-etc` | not started | +| `7.2/applied/advanced-hole` | not started | +| `7.2/applied/cosmetic-thread` | not started | +| `7.2/applied/thread-feature` | not started | +| `7.2/applied/stud-wizard` | not started | +| `7.2/applied/dome` | not started | +| `7.2/applied/wrap` | not started | +| `7.2/applied/wrap/emboss` | not started | +| `7.2/applied/wrap/deboss` | not started | +| `7.2/applied/wrap/scribe` | not started | +| `7.2/applied/indent` | not started | +| `7.2/applied/flex` | not started | +| `7.2/applied/flex/bend` | not started | +| `7.2/applied/flex/twist` | not started | +| `7.2/applied/flex/taper` | not started | +| `7.2/applied/flex/stretch` | not started | +| `7.2/applied/deform` | not started | +| `7.2/applied/intersect` | not started | +| `7.2/applied/freeform` | not started | +| `7.2/applied/lip-groove` | not started | +| `7.2/applied/mounting-boss` | not started | +| `7.2/applied/snap-hook-groove` | not started | +| `7.2/applied/vent` | not started | +| `7.2/applied/fastening-features` | not started | +| `7.2/patterns-and-mirror/linear` | in progress | +| `7.2/patterns-and-mirror/circular` | in progress | +| `7.2/patterns-and-mirror/curve-driven` | not started | +| `7.2/patterns-and-mirror/sketch-driven` | not started | +| `7.2/patterns-and-mirror/table-driven` | not started | +| `7.2/patterns-and-mirror/fill-pattern` | not started | +| `7.2/patterns-and-mirror/variable-pattern` | not started | +| `7.2/patterns-and-mirror/chain-pattern` | not started | +| `7.2/patterns-and-mirror/mirror` | in progress | +| `7.2/patterns-and-mirror/mirror/features` | in progress | +| `7.2/patterns-and-mirror/mirror/faces` | not started | +| `7.2/patterns-and-mirror/mirror/bodies` | not started | +| `7.2/patterns-and-mirror/geometry-pattern` | not started | +| `7.2/patterns-and-mirror/instance-skipping-varying` | not started | +| `7.2/multibody/combine` | in progress | +| `7.2/multibody/combine/add-subtract-common` | in progress | +| `7.2/multibody/split` | not started | +| `7.2/multibody/move-copy-body` | in progress | +| `7.2/multibody/delete-keep-body` | in progress | +| `7.2/multibody/insert-part` | not started | +| `7.2/multibody/insert-into-new-part` | not started | +| `7.2/multibody/save-bodies` | not started | +| `7.2/multibody/body-folders` | not started | +| `7.2/multibody/cut-list` | not started | +| `7.2/direct-editing/move-rotate-offset-replace-delete-face` | not started | +| `7.2/direct-editing/delete-hole` | not started | +| `7.2/direct-editing/simplify-defeature` | not started | +| `7.2/direct-editing/instant3d` | not started | +| `7.2/direct-editing/import-diagnostics-and-healing` | not started | +| `7.2/direct-editing/featureworks` | not started | +| `7.2/direct-editing/featureworks/feature-recognition-on-imported-bodies` | not started | +| `7.2/scale` | not started | +| `7.2/fillet-aware-undo` | not started | +| `7.2/library-features` | not started | +| `7.2/design-library` | not started | +| `7.2/smart-features` | not started | +| `7.2/forming-tools` | not started | +| `7.2/cosmetic-patterns` | not started | +| `7.2/decals` | not started | +| `7.2/appearances` | not started | +| `7.2/materials-database` | not started | +| `7.2/materials-database/with-custom-materials` | not started | +| `7.2/sensors` | not started | +| `7.2/feature-freeze` | not started | +| `7.2/feature-statistics` | not started | +| `7.2/performance-evaluation` | not started | +| `7.2/mesh-brep/import-mesh` | not started | +| `7.2/mesh-brep/import-mesh/stl-obj-3mf` | not started | +| `7.2/mesh-brep/mesh-bodies` | not started | +| `7.2/mesh-brep/convert-mesh-to-body` | not started | +| `7.2/mesh-brep/graphics-bodies` | not started | +| `7.2/mesh-brep/segment-mesh` | not started | +| `7.2/mesh-brep/3d-texture` | not started | + +### 7.3 Surfacing + +| Matrix ID | Recorded status | +|---|---| +| `7.3/extruded` | not started | +| `7.3/revolved` | not started | +| `7.3/swept` | not started | +| `7.3/lofted` | not started | +| `7.3/boundary` | not started | +| `7.3/planar` | not started | +| `7.3/fill` | not started | +| `7.3/fill/with-constraints-curvature` | not started | +| `7.3/freeform` | not started | +| `7.3/offset` | not started | +| `7.3/ruled` | not started | +| `7.3/radiated` | not started | +| `7.3/knit` | not started | +| `7.3/knit/with-gap-control` | not started | +| `7.3/untrim` | not started | +| `7.3/extend` | not started | +| `7.3/trim` | not started | +| `7.3/trim/standard-mutual` | not started | +| `7.3/delete-face-hole` | not started | +| `7.3/replace-face` | not started | +| `7.3/thicken` | not started | +| `7.3/surface-flatten` | not started | +| `7.3/mid-surface` | not started | +| `7.3/face-curves` | not started | +| `7.3/parting-surface` | not started | +| `7.3/shut-off-surface` | not started | +| `7.3/sew-heal` | not started | +| `7.3/curvature-continuity-checks` | not started | + +### 7.4 Sheet metal + +| Matrix ID | Recorded status | +|---|---| +| `7.4/base-flange-tab` | not started | +| `7.4/edge-flange` | not started | +| `7.4/edge-flange/all-positions` | not started | +| `7.4/edge-flange/custom-profile` | not started | +| `7.4/miter-flange` | not started | +| `7.4/hem` | not started | +| `7.4/hem/all-types` | not started | +| `7.4/jog` | not started | +| `7.4/sketched-bend` | not started | +| `7.4/cross-break` | not started | +| `7.4/closed-corner` | not started | +| `7.4/welded-corner` | not started | +| `7.4/break-relief-corner` | not started | +| `7.4/break-relief-corner/all-relief-types` | not started | +| `7.4/corner-trim` | not started | +| `7.4/forming-tools` | not started | +| `7.4/forming-tools/and-custom-forming-tools` | not started | +| `7.4/vent` | not started | +| `7.4/lofted-bend` | not started | +| `7.4/lofted-bend/formed-and-bent` | not started | +| `7.4/swept-flange` | not started | +| `7.4/convert-to-sheet-metal` | not started | +| `7.4/insert-bends-rip` | not started | +| `7.4/flatten-unfold-fold` | not started | +| `7.4/flat-pattern` | not started | +| `7.4/flat-pattern/with-bend-lines` | not started | +| `7.4/flat-pattern/bend-notes` | not started | +| `7.4/flat-pattern/grain-direction` | not started | +| `7.4/flat-pattern/flat-pattern-export-to-dxf-dwg` | not started | +| `7.4/gauge-tables` | not started | +| `7.4/bend-tables` | not started | +| `7.4/k-factor-bend-allowance-bend-deduction` | not started | +| `7.4/tab-and-slot` | not started | +| `7.4/normal-cut` | not started | +| `7.4/multibody-sheet-metal` | not started | +| `7.4/sheet-metal-cut-list-properties` | not started | + +### 7.5 Weldments + +| Matrix ID | Recorded status | +|---|---| +| `7.5/structural-member` | not started | +| `7.5/structural-member/ansi-iso` | not started | +| `7.5/structural-member/custom-profiles` | not started | +| `7.5/structural-member/corner-treatments` | not started | +| `7.5/structural-member/trim-extend` | not started | +| `7.5/structural-member/groups` | not started | +| `7.5/end-caps` | not started | +| `7.5/gussets` | not started | +| `7.5/fillet-beads` | not started | +| `7.5/weld-beads` | not started | +| `7.5/cut-lists-with-properties` | not started | +| `7.5/weldment-drawings-cut-list-tables` | not started | +| `7.5/3d-sketch-driven-frames` | not started | + +### 7.6 Mold / tooling + +| Matrix ID | Recorded status | +|---|---| +| `7.6/draft-analysis` | not started | +| `7.6/undercut-analysis` | not started | +| `7.6/parting-lines` | not started | +| `7.6/shut-off-surfaces` | not started | +| `7.6/parting-surfaces` | not started | +| `7.6/tooling-split` | not started | +| `7.6/core-cavity` | not started | +| `7.6/core-pins` | not started | +| `7.6/scale-for-shrinkage` | not started | +| `7.6/ruled-surface-for-molds` | not started | +| `7.6/mold-base-integration` | not started | + +### 7.7 Assemblies + +| Matrix ID | Recorded status | +|---|---| +| `7.7/top-down-and-bottom-up-design` | not started | +| `7.7/insert-components` | not started | +| `7.7/virtual-components` | not started | +| `7.7/subassemblies` | not started | +| `7.7/subassemblies/rigid-flexible` | not started | +| `7.7/component-patterns` | not started | +| `7.7/component-patterns/linear` | not started | +| `7.7/component-patterns/circular` | not started | +| `7.7/component-patterns/pattern-driven` | not started | +| `7.7/component-patterns/sketch-driven` | not started | +| `7.7/component-patterns/curve-driven` | not started | +| `7.7/component-patterns/chain` | not started | +| `7.7/mirror-components` | not started | +| `7.7/mirror-components/opposite-hand` | not started | +| `7.7/smart-components` | not started | +| `7.7/smart-fasteners` | not started | +| `7.7/toolbox` | not started | +| `7.7/toolbox/bolts` | not started | +| `7.7/toolbox/screws` | not started | +| `7.7/toolbox/nuts` | not started | +| `7.7/toolbox/washers` | not started | +| `7.7/toolbox/pins` | not started | +| `7.7/toolbox/bearings` | not started | +| `7.7/toolbox/gears` | not started | +| `7.7/toolbox/cams` | not started | +| `7.7/toolbox/pulleys` | not started | +| `7.7/toolbox/sprockets` | not started | +| `7.7/toolbox/structural-steel` | not started | +| `7.7/toolbox/o-rings` | not started | +| `7.7/toolbox/keyways` | not started | +| `7.7/mates/standard` | not started | +| `7.7/mates/standard/coincident` | not started | +| `7.7/mates/standard/parallel` | not started | +| `7.7/mates/standard/perpendicular` | not started | +| `7.7/mates/standard/tangent` | not started | +| `7.7/mates/standard/concentric` | not started | +| `7.7/mates/standard/lock` | not started | +| `7.7/mates/standard/distance` | not started | +| `7.7/mates/standard/angle` | not started | +| `7.7/mates/advanced` | not started | +| `7.7/mates/advanced/profile-center` | not started | +| `7.7/mates/advanced/symmetric` | not started | +| `7.7/mates/advanced/width` | not started | +| `7.7/mates/advanced/path` | not started | +| `7.7/mates/advanced/linear-linear-coupler` | not started | +| `7.7/mates/advanced/limit-distance-angle` | not started | +| `7.7/mates/mechanical` | not started | +| `7.7/mates/mechanical/cam` | not started | +| `7.7/mates/mechanical/slot` | not started | +| `7.7/mates/mechanical/hinge` | not started | +| `7.7/mates/mechanical/gear` | not started | +| `7.7/mates/mechanical/rack-and-pinion` | not started | +| `7.7/mates/mechanical/screw` | not started | +| `7.7/mates/mechanical/universal-joint` | not started | +| `7.7/mates/mate-references` | not started | +| `7.7/mates/smartmates` | not started | +| `7.7/mates/quick-mates` | not started | +| `7.7/mates/matexpert-mate-diagnostics` | not started | +| `7.7/mates/mate-folders` | not started | +| `7.7/mates/mate-controller` | not started | +| `7.7/mates/copy-with-mates` | not started | +| `7.7/tools/move-rotate-component` | not started | +| `7.7/tools/move-rotate-component/with-collision-detection` | not started | +| `7.7/tools/move-rotate-component/dynamic-clearance` | not started | +| `7.7/tools/move-rotate-component/physical-dynamics` | not started | +| `7.7/tools/interference-detection` | not started | +| `7.7/tools/clearance-verification` | not started | +| `7.7/tools/hole-alignment` | not started | +| `7.7/tools/assembly-visualization` | not started | +| `7.7/tools/assemblyxpert` | not started | +| `7.7/tools/exploded-views` | not started | +| `7.7/tools/exploded-views/with-explode-lines` | not started | +| `7.7/tools/exploded-views/radial-regular-steps` | not started | +| `7.7/tools/exploded-views/animation` | not started | +| `7.7/tools/section-views` | not started | +| `7.7/tools/configurations` | not started | +| `7.7/tools/display-states` | not started | +| `7.7/tools/large-assembly-mode` | not started | +| `7.7/tools/large-design-review` | not started | +| `7.7/tools/lightweight-components` | not started | +| `7.7/tools/speedpak` | not started | +| `7.7/tools/defeature` | not started | +| `7.7/tools/envelopes` | not started | +| `7.7/tools/treehouse` | not started | +| `7.7/tools/treehouse/structure-planning` | not started | +| `7.7/tools/assembly-features` | not started | +| `7.7/tools/assembly-features/cuts` | not started | +| `7.7/tools/assembly-features/holes` | not started | +| `7.7/tools/assembly-features/weld-beads` | not started | +| `7.7/tools/in-context-references` | not started | +| `7.7/tools/in-context-references/external-reference-management` | not started | +| `7.7/tools/in-context-references/lock-break` | not started | +| `7.7/tools/replace-components` | not started | +| `7.7/tools/pack-and-go` | not started | +| `7.7/tools/magnetic-mates-asset-publisher` | not started | +| `7.7/tools/belts-chains` | not started | +| `7.7/tools/structure-system` | not started | +| `7.7/tools/assembly-layout-sketches` | not started | +| `7.7/tools/bom-in-assembly` | not started | +| `7.7/tools/isolate` | not started | +| `7.7/tools/component-preview` | not started | +| `7.7/tools/envelope-publisher` | not started | + +### 7.8 Motion + +| Matrix ID | Recorded status | +|---|---| +| `7.8/animation` | not started | +| `7.8/animation/keyframe-timeline` | not started | +| `7.8/animation/camera-animation` | not started | +| `7.8/animation/walk-through` | not started | +| `7.8/basic-motion` | not started | +| `7.8/basic-motion/motors` | not started | +| `7.8/basic-motion/springs` | not started | +| `7.8/basic-motion/contact` | not started | +| `7.8/basic-motion/gravity` | not started | +| `7.8/motion-analysis` | not started | +| `7.8/motion-analysis/forces` | not started | +| `7.8/motion-analysis/dampers` | not started | +| `7.8/motion-analysis/bushings` | not started | +| `7.8/motion-analysis/3d-contact` | not started | +| `7.8/motion-analysis/friction` | not started | +| `7.8/motion-analysis/results-and-plots` | not started | +| `7.8/motion-analysis/export-loads-to-fea` | not started | +| `7.8/motion-optimization` | not started | +| `7.8/event-based-motion` | not started | +| `7.8/interference-during-motion` | not started | +| `7.8/trace-paths` | not started | + +### 7.9 Drawings + +| Matrix ID | Recorded status | +|---|---| +| `7.9/sheets-and-formats` | not started | +| `7.9/sheets-and-formats/all-ansi-iso-din-jis-gb-templates` | not started | +| `7.9/sheets-and-formats/editable-title-blocks-with-property-links` | not started | +| `7.9/sheets-and-formats/multiple-sheets` | not started | +| `7.9/sheets-and-formats/sheet-scaling` | not started | +| `7.9/drafting-standards-editor` | not started | +| `7.9/views/standard-3-view` | not started | +| `7.9/views/model-view` | not started | +| `7.9/views/projected` | not started | +| `7.9/views/auxiliary` | not started | +| `7.9/views/section` | not started | +| `7.9/views/section/with-section-view-assist` | not started | +| `7.9/views/section/aligned` | not started | +| `7.9/views/section/half` | not started | +| `7.9/views/section/offset` | not started | +| `7.9/views/section/partial` | not started | +| `7.9/views/detail` | not started | +| `7.9/views/detail/circular-profile` | not started | +| `7.9/views/broken-out-section` | not started | +| `7.9/views/break` | not started | +| `7.9/views/crop` | not started | +| `7.9/views/alternate-position` | not started | +| `7.9/views/relative-to-model` | not started | +| `7.9/views/3d-drawing-view` | not started | +| `7.9/views/flat-pattern-views` | not started | +| `7.9/views/exploded-views` | not started | +| `7.9/views/empty-views` | not started | +| `7.9/views/view-palette` | not started | +| `7.9/views/rotate-views` | not started | +| `7.9/views/hlr-hlv` | not started | +| `7.9/views/tangent-edge-options` | not started | +| `7.9/views/shaded-wireframe` | not started | +| `7.9/views/isometric` | not started | +| `7.9/views/live-section` | not started | +| `7.9/annotations/model-items-import` | not started | +| `7.9/annotations/smart-dimension` | not started | +| `7.9/annotations/smart-dimension/all-types-incl-ordinate` | not started | +| `7.9/annotations/smart-dimension/chamfer` | not started | +| `7.9/annotations/smart-dimension/baseline` | not started | +| `7.9/annotations/smart-dimension/chain` | not started | +| `7.9/annotations/smart-dimension/angular-running` | not started | +| `7.9/annotations/dimxpert-for-drawings` | not started | +| `7.9/annotations/notes` | not started | +| `7.9/annotations/notes/linked-properties` | not started | +| `7.9/annotations/notes/hyperlinks` | not started | +| `7.9/annotations/notes/balloons-in-notes` | not started | +| `7.9/annotations/balloons` | not started | +| `7.9/annotations/balloons/auto-balloon` | not started | +| `7.9/annotations/balloons/stacked` | not started | +| `7.9/annotations/surface-finish` | not started | +| `7.9/annotations/weld-symbols` | not started | +| `7.9/annotations/weld-symbols/ansi-iso` | not started | +| `7.9/annotations/gdandt` | not started | +| `7.9/annotations/gdandt/feature-control-frames` | not started | +| `7.9/annotations/gdandt/datums` | not started | +| `7.9/annotations/gdandt/datum-targets` | not started | +| `7.9/annotations/gdandt/composite-frames` | not started | +| `7.9/annotations/center-marks` | not started | +| `7.9/annotations/centerlines` | not started | +| `7.9/annotations/cosmetic-threads` | not started | +| `7.9/annotations/hole-callouts` | not started | +| `7.9/annotations/revision-clouds` | not started | +| `7.9/annotations/area-hatch-fill` | not started | +| `7.9/annotations/blocks` | not started | +| `7.9/annotations/magnetic-lines` | not started | +| `7.9/annotations/layers` | not started | +| `7.9/annotations/dimension-tolerance-display` | not started | +| `7.9/annotations/dimension-tolerance-display/all-types` | not started | +| `7.9/annotations/dimension-tolerance-display/fits` | not started | +| `7.9/annotations/dimension-tolerance-display/tables` | not started | +| `7.9/tables/bom` | not started | +| `7.9/tables/bom/top-level` | not started | +| `7.9/tables/bom/parts-only` | not started | +| `7.9/tables/bom/indented` | not started | +| `7.9/tables/bom/weldment-cut-list` | not started | +| `7.9/tables/bom/with-custom-columns-and-equations` | not started | +| `7.9/tables/hole-table` | not started | +| `7.9/tables/revision-table` | not started | +| `7.9/tables/general-table` | not started | +| `7.9/tables/bend-table` | not started | +| `7.9/tables/punch-table` | not started | +| `7.9/tables/weld-table` | not started | +| `7.9/tables/design-table` | not started | +| `7.9/tables/title-block-table` | not started | +| `7.9/tables/general-table-templates` | not started | +| `7.9/drawing-tools/auto-arrange-dimensions` | not started | +| `7.9/drawing-tools/dimension-palette` | not started | +| `7.9/drawing-tools/format-painter` | not started | +| `7.9/drawing-tools/sketch-in-drawing` | not started | +| `7.9/drawing-tools/design-checker` | not started | +| `7.9/drawing-tools/drawing-compare` | not started | +| `7.9/drawing-tools/detailing-mode` | not started | +| `7.9/drawing-tools/dwg-dxf-editing-parity-basics` | not started | +| `7.9/drawing-tools/print-plot` | not started | +| `7.9/drawing-tools/print-plot/with-pen-tables` | not started | +| `7.9/drawing-tools/pdf-with-layers-3d-pdf` | not started | + +### 7.10 Model-Based Definition (MBD) + +| Matrix ID | Recorded status | +|---|---| +| `7.10/dimxpert` | not started | +| `7.10/3d-annotations` | not started | +| `7.10/3d-pmi-views` | not started | +| `7.10/annotation-views` | not started | +| `7.10/3d-pdf-publishing` | not started | +| `7.10/step-ap242-pmi-export` | not started | +| `7.10/tolerance-status-display` | not started | + +### 7.11 Tolerance & quality + +| Matrix ID | Recorded status | +|---|---| +| `7.11/tolanalyst` | not started | +| `7.11/tolanalyst/tolerance-stack-up` | not started | +| `7.11/tolanalyst/worst-case-rss` | not started | +| `7.11/inspection` | not started | +| `7.11/inspection/ballooning` | not started | +| `7.11/inspection/inspection-reports-from-drawings-and-3d` | not started | +| `7.11/inspection/cmm-data-import` | not started | +| `7.11/design-checker` | not started | +| `7.11/design-checker/standards-compliance` | not started | +| `7.11/compare-documents-features-geometry-boms` | not started | +| `7.11/equations-diagnostics` | not started | + +### 7.12 Analysis tools (in-part) + +| Matrix ID | Recorded status | +|---|---| +| `7.12/measure` | in progress | +| `7.12/measure/all-modes` | not started | +| `7.12/measure/point-to-point` | not started | +| `7.12/measure/min-max-normal` | not started | +| `7.12/measure/projected` | not started | +| `7.12/mass-properties` | in progress | +| `7.12/mass-properties/with-overrides` | not started | +| `7.12/mass-properties/per-config` | not started | +| `7.12/section-properties` | not started | +| `7.12/geometry-check` | in progress | +| `7.12/draft-analysis` | not started | +| `7.12/undercut-analysis` | not started | +| `7.12/thickness-analysis` | not started | +| `7.12/curvature-display` | not started | +| `7.12/zebra-stripes` | not started | +| `7.12/deviation-analysis` | not started | +| `7.12/parting-line-analysis` | not started | +| `7.12/symmetry-check` | not started | +| `7.12/interference-check-between-bodies` | done | +| `7.12/dfmxpress` | not started | +| `7.12/dfmxpress/manufacturability-rules` | not started | +| `7.12/costing` | not started | +| `7.12/costing/machining` | not started | +| `7.12/costing/sheet-metal` | not started | +| `7.12/costing/weldments` | not started | +| `7.12/costing/casting` | not started | +| `7.12/costing/plastic` | not started | +| `7.12/costing/3d-printed` | not started | +| `7.12/costing/cost-templates` | not started | +| `7.12/sustainability` | not started | +| `7.12/sustainability/environmental-impact` | not started | +| `7.12/sustainability/material-comparison` | not started | +| `7.12/feature-statistics` | not started | + +### 7.13 Simulation (FEA) + +| Matrix ID | Recorded status | +|---|---| +| `7.13/study-types/linear-static` | not started | +| `7.13/study-types/frequency` | not started | +| `7.13/study-types/buckling` | not started | +| `7.13/study-types/thermal` | not started | +| `7.13/study-types/thermal/steady-transient` | not started | +| `7.13/study-types/drop-test` | not started | +| `7.13/study-types/fatigue` | not started | +| `7.13/study-types/fatigue/s-n` | not started | +| `7.13/study-types/fatigue/event-based` | not started | +| `7.13/study-types/nonlinear` | not started | +| `7.13/study-types/nonlinear/static-dynamic` | not started | +| `7.13/study-types/nonlinear/material-and-geometric-nonlinearity` | not started | +| `7.13/study-types/nonlinear/contact` | not started | +| `7.13/study-types/linear-dynamic` | not started | +| `7.13/study-types/linear-dynamic/modal-time-history` | not started | +| `7.13/study-types/linear-dynamic/harmonic` | not started | +| `7.13/study-types/linear-dynamic/random-vibration` | not started | +| `7.13/study-types/linear-dynamic/response-spectrum` | not started | +| `7.13/study-types/pressure-vessel-design` | not started | +| `7.13/study-types/submodeling` | not started | +| `7.13/study-types/design-study-optimization` | not started | +| `7.13/study-types/topology-optimization` | not started | +| `7.13/study-types/topology-optimization/with-manufacturing-constraints` | not started | +| `7.13/study-types/2d-simplification` | not started | +| `7.13/study-types/beam-truss-elements` | not started | +| `7.13/study-types/shells` | not started | +| `7.13/study-types/shells/sheet-metal-midsurface-auto` | not started | +| `7.13/study-types/composites` | not started | +| `7.13/setup/materials` | not started | +| `7.13/setup/materials/linear-nonlinear-orthotropic-composite` | not started | +| `7.13/setup/fixtures` | not started | +| `7.13/setup/fixtures/all-types` | not started | +| `7.13/setup/loads` | not started | +| `7.13/setup/loads/force` | not started | +| `7.13/setup/loads/pressure` | not started | +| `7.13/setup/loads/torque` | not started | +| `7.13/setup/loads/gravity` | not started | +| `7.13/setup/loads/centrifugal` | not started | +| `7.13/setup/loads/bearing` | not started | +| `7.13/setup/loads/remote` | not started | +| `7.13/setup/loads/distributed-mass` | not started | +| `7.13/setup/loads/temperature` | not started | +| `7.13/setup/loads/thermal-loads` | not started | +| `7.13/setup/connectors` | not started | +| `7.13/setup/connectors/bolts` | not started | +| `7.13/setup/connectors/pins` | not started | +| `7.13/setup/connectors/springs` | not started | +| `7.13/setup/connectors/bearings` | not started | +| `7.13/setup/connectors/welds` | not started | +| `7.13/setup/connectors/rigid` | not started | +| `7.13/setup/connectors/link` | not started | +| `7.13/setup/connectors/edge-weld` | not started | +| `7.13/setup/contacts` | not started | +| `7.13/setup/contacts/bonded` | not started | +| `7.13/setup/contacts/no-penetration` | not started | +| `7.13/setup/contacts/shrink-fit` | not started | +| `7.13/setup/contacts/virtual-wall` | not started | +| `7.13/setup/contacts/contact-visualization` | not started | +| `7.13/setup/mesh` | not started | +| `7.13/setup/mesh/standard-curvature-based-blended` | not started | +| `7.13/setup/mesh/controls` | not started | +| `7.13/setup/mesh/adaptive-h-p` | not started | +| `7.13/setup/mesh/mesh-quality-diagnostics` | not started | +| `7.13/results/stress` | not started | +| `7.13/results/stress/von-mises` | not started | +| `7.13/results/stress/principal` | not started | +| `7.13/results/stress/components` | not started | +| `7.13/results/displacement` | not started | +| `7.13/results/strain` | not started | +| `7.13/results/factor-of-safety` | not started | +| `7.13/results/reaction-forces` | not started | +| `7.13/results/free-body-forces` | not started | +| `7.13/results/probing` | not started | +| `7.13/results/iso-clipping` | not started | +| `7.13/results/section-clipping` | not started | +| `7.13/results/animation` | not started | +| `7.13/results/charts` | not started | +| `7.13/results/compare-studies` | not started | +| `7.13/results/trend-tracking` | not started | +| `7.13/results/report-generator` | not started | +| `7.13/results/results-export` | not started | +| `7.13/results/results-export/csv` | not started | +| `7.13/results/results-export/images` | not started | +| `7.13/results/results-export/video` | not started | +| `7.13/motion-to-fea-load-transfer` | not started | +| `7.13/flow-to-fea-pressure-thermal-transfer` | not started | + +### 7.14 Flow Simulation (CFD) + +| Matrix ID | Recorded status | +|---|---| +| `7.14/internal-external-flow` | not started | +| `7.14/compressible-incompressible` | not started | +| `7.14/steady-transient` | not started | +| `7.14/heat-transfer` | not started | +| `7.14/heat-transfer/conduction` | not started | +| `7.14/heat-transfer/convection` | not started | +| `7.14/heat-transfer/radiation` | not started | +| `7.14/heat-transfer/conjugate` | not started | +| `7.14/rotating-regions` | not started | +| `7.14/porous-media` | not started | +| `7.14/fans` | not started | +| `7.14/perforated-plates` | not started | +| `7.14/electronics-cooling` | not started | +| `7.14/electronics-cooling/pcb` | not started | +| `7.14/electronics-cooling/heat-sinks` | not started | +| `7.14/electronics-cooling/tec` | not started | +| `7.14/electronics-cooling/heat-pipes` | not started | +| `7.14/hvac` | not started | +| `7.14/hvac/comfort-params` | not started | +| `7.14/free-surface` | not started | +| `7.14/cavitation` | not started | +| `7.14/humidity` | not started | +| `7.14/goals` | not started | +| `7.14/parametric-studies` | not started | +| `7.14/results` | not started | +| `7.14/results/cut-plots` | not started | +| `7.14/results/surface-plots` | not started | +| `7.14/results/flow-trajectories` | not started | +| `7.14/results/particle-studies` | not started | +| `7.14/results/iso-surfaces` | not started | +| `7.14/results/animations` | not started | +| `7.14/results/xy-plots` | not started | +| `7.14/mesh-control` | not started | +| `7.14/engineering-database` | not started | + +### 7.15 Plastics + +| Matrix ID | Recorded status | +|---|---| +| `7.15/mold-fill` | not started | +| `7.15/pack` | not started | +| `7.15/cool` | not started | +| `7.15/warp` | not started | +| `7.15/gate-location-advisor` | not started | +| `7.15/runner-design` | not started | +| `7.15/cooling-channel-design` | not started | +| `7.15/weld-line-air-trap-prediction` | not started | +| `7.15/sink-marks` | not started | +| `7.15/clamp-force` | not started | +| `7.15/material-database` | not started | +| `7.15/results-and-report` | not started | + +### 7.16 Routing & electrical + +| Matrix ID | Recorded status | +|---|---| +| `7.16/electrical-routing` | not started | +| `7.16/electrical-routing/cables` | not started | +| `7.16/electrical-routing/wires` | not started | +| `7.16/electrical-routing/harnesses` | not started | +| `7.16/electrical-routing/connectors` | not started | +| `7.16/electrical-routing/clips` | not started | +| `7.16/electrical-routing/from-to-lists` | not started | +| `7.16/electrical-routing/harness-flattening` | not started | +| `7.16/electrical-routing/harness-drawings` | not started | +| `7.16/piping` | not started | +| `7.16/piping/pipes` | not started | +| `7.16/piping/fittings` | not started | +| `7.16/piping/flanges` | not started | +| `7.16/piping/valves` | not started | +| `7.16/piping/spools` | not started | +| `7.16/piping/isometric-drawings-with-pcf-export` | not started | +| `7.16/tubing` | not started | +| `7.16/tubing/flexible-rigid` | not started | +| `7.16/tubing/bends` | not started | +| `7.16/routing-library-manager` | not started | +| `7.16/auto-route` | not started | +| `7.16/orthogonal-routing` | not started | +| `7.16/route-properties` | not started | +| `7.16/pandid-driven-routing` | not started | +| `7.16/electrical-schematic-module-schematics` | not started | +| `7.16/electrical-schematic-module-schematics/electrical-schematic-equivalent` | not started | +| `7.16/line-diagrams` | not started | +| `7.16/symbols-library` | not started | +| `7.16/wire-numbering` | not started | +| `7.16/terminal-strips` | not started | +| `7.16/plc-i-o` | not started | +| `7.16/reports` | not started | +| `7.16/bidirectional-2d-3d-sync` | not started | +| `7.16/pcb-import` | not started | +| `7.16/pcb-import/idf-idx-ecad-collaboration` | not started | +| `7.16/circuitworks-equivalent` | not started | + +### 7.17 Rendering & visualization + +| Matrix ID | Recorded status | +|---|---| +| `7.17/realview-style-realtime-pbr` | not started | +| `7.17/ambient-occlusion` | not started | +| `7.17/shadows` | not started | +| `7.17/perspective` | not started | +| `7.17/scenes-environments` | not started | +| `7.17/scenes-environments/hdri` | not started | +| `7.17/appearances-library` | not started | +| `7.17/decals` | not started | +| `7.17/lights` | not started | +| `7.17/lights/directional` | not started | +| `7.17/lights/point` | not started | +| `7.17/lights/spot` | not started | +| `7.17/lights/area` | not started | +| `7.17/cameras` | not started | +| `7.17/cameras/with-dof` | not started | +| `7.17/photoreal-path-traced-renderer` | not started | +| `7.17/photoreal-path-traced-renderer/photoview-360-visualize-parity-denoising` | not started | +| `7.17/photoreal-path-traced-renderer/render-regions` | not started | +| `7.17/photoreal-path-traced-renderer/turntables` | not started | +| `7.17/photoreal-path-traced-renderer/animation-rendering` | not started | +| `7.17/photoreal-path-traced-renderer/sun-study` | not started | +| `7.17/photoreal-path-traced-renderer/render-queue` | not started | +| `7.17/exploded-animated-presentations` | not started | +| `7.17/3d-views-and-pdf-web-publishing` | not started | +| `7.17/edrawings-equivalent-lightweight-viewer` | not started | +| `7.17/edrawings-equivalent-lightweight-viewer/mac` | not started | +| `7.17/edrawings-equivalent-lightweight-viewer/ios-visionos-stretch-goal` | not started | +| `7.17/edrawings-equivalent-lightweight-viewer/ar-quick-look-via-usdz-export` | not started | + +### 7.18 CAM + +| Matrix ID | Recorded status | +|---|---| +| `7.18/feature-recognition-for-machinable-features` | not started | +| `7.18/feature-recognition-for-machinable-features/afr` | not started | +| `7.18/2-5-axis-mill` | not started | +| `7.18/3-axis-mill` | not started | +| `7.18/4-5-axis-indexed-and-simultaneous` | not started | +| `7.18/4-5-axis-indexed-and-simultaneous/later-milestone` | not started | +| `7.18/turning` | not started | +| `7.18/mill-turn` | not started | +| `7.18/probing` | not started | +| `7.18/technology-database` | not started | +| `7.18/technology-database/tools` | not started | +| `7.18/technology-database/feeds-speeds` | not started | +| `7.18/technology-database/strategies` | not started | +| `7.18/stock-definition` | not started | +| `7.18/toolpath-simulation-with-material-removal` | not started | +| `7.18/collision-gouge-checking` | not started | +| `7.18/post-processors` | not started | +| `7.18/post-processors/fanuc` | not started | +| `7.18/post-processors/haas` | not started | +| `7.18/post-processors/mazak` | not started | +| `7.18/post-processors/siemens` | not started | +| `7.18/post-processors/heidenhain` | not started | +| `7.18/post-processors/grbl` | not started | +| `7.18/post-processors/and-a-custom-post-language` | not started | +| `7.18/setup-sheets` | not started | +| `7.18/g-code-output` | not started | + +### 7.19 Data management + +| Matrix ID | Recorded status | +|---|---| +| `7.19/pdm/vault` | not started | +| `7.19/pdm/vault/local-and-server-based` | not started | +| `7.19/pdm/check-in-out` | not started | +| `7.19/pdm/version-and-revision-control` | not started | +| `7.19/pdm/lifecycle-states-and-workflows` | not started | +| `7.19/pdm/where-used-contains` | not started | +| `7.19/pdm/references-management` | not started | +| `7.19/pdm/bom-management` | not started | +| `7.19/pdm/search` | not started | +| `7.19/pdm/change-requests-ecos` | not started | +| `7.19/pdm/permissions` | not started | +| `7.19/pdm/replication` | not started | +| `7.19/pdm/minimum-viable-git-backed-local-vault` | not started | +| `7.19/pdm/full-server-component` | not started | +| `7.19/pdm/full-server-component/swift-on-server-or-equivalent` | not started | +| `7.19/pack-and-go` | not started | +| `7.19/rename-with-references` | not started | +| `7.19/reference-repair` | not started | +| `7.19/task-scheduler` | not started | +| `7.19/task-scheduler/batch-export-print-convert` | not started | +| `7.19/design-library` | not started | +| `7.19/file-references-and-external-reference-management` | not started | +| `7.19/backup-auto-recover` | not started | +| `7.19/collaboration` | not started | +| `7.19/collaboration/shared-links` | not started | +| `7.19/collaboration/markup-comments-edrawings-markup-parity` | not started | + +### 7.20 Import / export + +| Matrix ID | Recorded status | +|---|---| +| `7.20/native/own-formats` | not started | +| `7.20/native/own-formats/section-4-5` | not started | +| `7.20/neutral/step-ap203-214-242` | in progress | +| `7.20/neutral/step-ap203-214-242/with-pmi` | not started | +| `7.20/neutral/iges` | not started | +| `7.20/neutral/parasolid-via-step-only` | not started | +| `7.20/neutral/parasolid-via-step-only/no-direct-x-t-unless-licensed` | not started | +| `7.20/neutral/acis-sat` | not started | +| `7.20/neutral/acis-sat/evaluate` | not started | +| `7.20/neutral/jt` | not started | +| `7.20/neutral/jt/evaluate` | not started | +| `7.20/neutral/vda-fs` | not started | +| `7.20/neutral/3mf` | not started | +| `7.20/neutral/stl` | in progress | +| `7.20/neutral/obj` | not started | +| `7.20/neutral/ply` | not started | +| `7.20/neutral/usdz-usd` | not started | +| `7.20/neutral/gltf` | not started | +| `7.20/neutral/vrml` | not started | +| `7.20/neutral/dxf-dwg` | not started | +| `7.20/neutral/dxf-dwg/2d-in-out` | not started | +| `7.20/neutral/dxf-dwg/3d-dwg-out` | not started | +| `7.20/neutral/pdf-3d-pdf` | not started | +| `7.20/neutral/svg` | not started | +| `7.20/neutral/ifc` | not started | +| `7.20/neutral/ifc/bim` | not started | +| `7.20/neutral/idf-idx` | not started | +| `7.20/neutral/idf-idx/ecad` | not started | +| `7.20/neutral/rhino-3dm` | not started | +| `7.20/neutral/rhino-3dm/via-opennurbs` | not started | +| `7.20/solidworks-native-files-sldprt-sldasm-slddrw` | not started | +| `7.20/3d-printing/3mf-with-color-materials` | not started | +| `7.20/3d-printing/print-bed-preview` | not started | +| `7.20/3d-printing/support-overhang-analysis` | not started | +| `7.20/3d-printing/hollowing` | not started | +| `7.20/3d-printing/lattice-generation` | not started | + +### 7.21 Customization & automation + +| Matrix ID | Recorded status | +|---|---| +| `7.21/full-api` | in progress | +| `7.21/full-api/section-5` | not started | +| `7.21/macros` | not started | +| `7.21/add-in-manager` | not started | +| `7.21/toolbar-palette-customization` | not started | +| `7.21/keyboard-mouse-gesture-mapping` | not started | +| `7.21/templates` | not started | +| `7.21/templates/part-assembly-drawing` | not started | +| `7.21/document-properties-and-system-options` | not started | +| `7.21/document-properties-and-system-options/every-solidworks-option-category-mapped` | not started | +| `7.21/units-systems` | in progress | +| `7.21/material-appearance-library-authoring` | not started | +| `7.21/task-scheduler` | not started | + +### Discovered (SolidWorks capabilities not listed in SPEC §7) + +| Matrix ID | Recorded status | +|---|---| +| `D/hide-show` | not started | +| `D/transparency` | not started | +| `D/section-view-part` | not started | +| `D/view-selector` | not started | +| `D/zoom-to-selection` | not started | +| `D/display-states-part` | not started | +| `D/feature-comments` | not started | +| `D/selection-sets` | not started | diff --git a/scripts/test-gtk-actions.sh b/scripts/test-gtk-actions.sh index e92da50..8b76958 100755 --- a/scripts/test-gtk-actions.sh +++ b/scripts/test-gtk-actions.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Native GTK action regression; does not require Swift or OCCT. +# Native GTK action/dialog regression; does not require Swift or OCCT. set -euo pipefail cd "$(dirname "$0")/.." forge_test_dir=$(mktemp -d) @@ -11,8 +11,8 @@ read -r -a forge_gtk_flags <<< "$(pkg-config --cflags --libs gtk4 epoxy)" Sources/CForgeWin/gtk/gtk_shell.c Sources/CForgeWin/gtk/gtk_icons.c Sources/CForgeWin/gtk/gtk_render.c \ "${forge_gtk_flags[@]}" -lm -o "$forge_test_dir/menu-actions" if command -v xvfb-run >/dev/null 2>&1; then - xvfb-run -a env GDK_BACKEND=x11 "$forge_test_dir/menu-actions" + timeout 30s xvfb-run -a env GDK_BACKEND=x11 "$forge_test_dir/menu-actions" else - # A local desktop can run this without showing a window; CI supplies Xvfb. - "$forge_test_dir/menu-actions" + echo "GTK tests require xvfb-run; refusing to open test dialogs on the desktop." >&2 + exit 1 fi