From 832a94062f2f5451bbf0af28d151fbccb865c3d7 Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Sat, 7 Nov 2026 12:49:01 +0000 Subject: [PATCH 01/22] feat: deliver 067G design workflows and verified installer scope --- CMakeLists.txt | 10 ++- docs/DESIGN_REVIEW_067G.md | 54 +++++++++++ docs/DESIGN_VARIANTS_067G.md | 73 +++++++++++++++ docs/DRAWING_LIBRARY_067G.md | 90 +++++++++++++++++++ docs/MULTI_AGENT_STUDIO.md | 8 +- docs/README.md | 3 + docs/ROADMAP.md | 13 ++- docs/iterations/067G.md | 65 ++++++++++++++ include/ark/design_review.hpp | 11 +++ include/ark/design_variants.hpp | 9 ++ include/ark/drawings.hpp | 3 + include/ark/model.hpp | 1 + include/ark/parametric_components.hpp | 3 + release.json | 16 ++-- src/agent.cpp | 15 ++-- src/agent_team.cpp | 13 +-- src/assistant.cpp | 2 +- src/assistant_steering.inl | 2 + src/design_review.cpp | 62 +++++++++++++ src/design_variants.cpp | 71 +++++++++++++++ src/drawing_pdf.inl | 56 ++++++++++++ src/drawings.cpp | 48 ++++++++-- src/iteration_history.cpp | 2 +- src/model.cpp | 2 +- src/onboarding.cpp | 24 ++++- src/parametric_component_library.inl | 30 +++++++ src/parametric_components.cpp | 12 ++- src/parametric_programs.cpp | 5 +- src/serialize.cpp | 7 +- src/view/action_icons_selftest.inl | 2 +- src/view/action_icons_set_c.inl | 7 ++ src/view/async_authoring_051a.inl | 6 +- src/view/component_library_067g.inl | 62 +++++++++++++ src/view/design_review_067g.inl | 46 ++++++++++ src/view/design_review_selftest_067g.inl | 27 ++++++ src/view/design_variants.inl | 31 +++++++ src/view/design_variants_selftest.inl | 29 ++++++ src/view/drawing_viewport.inl | 5 +- src/view/drawing_workspace.inl | 24 +++-- src/view/drawing_workspace_selftest.inl | 3 +- src/view/viewer.cpp | 44 +++++++-- tests/agent_features_tests.cpp | 2 +- ...agent_team_design_workflows_067g_tests.inl | 53 +++++++++++ tests/agent_team_tests.cpp | 3 +- tests/agent_tests.cpp | 4 +- tests/authoring_023b_contract_tests.cpp | 2 +- tests/authoring_024b_contract_tests.cpp | 2 +- tests/authoring_029b_integration_tests.cpp | 2 +- tests/datum_authoring_tests.cpp | 2 +- tests/design_review_tests.cpp | 44 +++++++++ tests/design_variants_tests.cpp | 37 ++++++++ tests/drawing_tests.cpp | 13 +++ tests/parametric_components_053b_tests.cpp | 4 + tests/profile_regions_046b_tests.cpp | 2 +- 54 files changed, 1097 insertions(+), 69 deletions(-) create mode 100644 docs/DESIGN_REVIEW_067G.md create mode 100644 docs/DESIGN_VARIANTS_067G.md create mode 100644 docs/DRAWING_LIBRARY_067G.md create mode 100644 docs/iterations/067G.md create mode 100644 include/ark/design_review.hpp create mode 100644 include/ark/design_variants.hpp create mode 100644 src/design_review.cpp create mode 100644 src/design_variants.cpp create mode 100644 src/drawing_pdf.inl create mode 100644 src/parametric_component_library.inl create mode 100644 src/view/component_library_067g.inl create mode 100644 src/view/design_review_067g.inl create mode 100644 src/view/design_review_selftest_067g.inl create mode 100644 src/view/design_variants.inl create mode 100644 src/view/design_variants_selftest.inl create mode 100644 tests/agent_team_design_workflows_067g_tests.inl create mode 100644 tests/design_review_tests.cpp create mode 100644 tests/design_variants_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d121ca9..55ad965 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,6 +58,7 @@ add_library(ark STATIC src/authoring_024b.cpp src/media_authoring.cpp src/appearance_024b.cpp src/plane_sections_024b.cpp src/authoring_023b.cpp src/cad_import.cpp src/holes_orchestrator.cpp src/design_containers.cpp src/parametric_components.cpp src/parametric_programs.cpp + src/design_variants.cpp src/design_review.cpp src/design_disciplines.cpp src/motion_cables.cpp src/assembly_patterns.cpp src/transmission_math_061c.cpp src/transmission_tools_061c.cpp src/transmission_design_061c.cpp @@ -182,6 +183,13 @@ if(ARK_WITH_OCCT) add_test(NAME parametric-components-053b COMMAND ark-parametric-components-053b-tests) set_tests_properties(parametric-components-053b PROPERTIES TIMEOUT 180) add_dependencies(ark-parametric-components-053b-tests ark-occt-worker) + foreach(feature design_variants design_review) + add_executable(ark-${feature}-tests tests/${feature}_tests.cpp) + target_link_libraries(ark-${feature}-tests PRIVATE ark) + add_test(NAME ${feature} COMMAND ark-${feature}-tests) + set_tests_properties(${feature} PROPERTIES TIMEOUT 240) + add_dependencies(ark-${feature}-tests ark-occt-worker) + endforeach() add_executable(ark-parametric-programs-tests tests/parametric_programs_tests.cpp) target_link_libraries(ark-parametric-programs-tests PRIVATE ark) add_test(NAME parametric-programs COMMAND ark-parametric-programs-tests) @@ -682,7 +690,7 @@ if(WIN32) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1280 800) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 300 RUN_SERIAL TRUE) endforeach() - foreach(check inertial-ui viewport-quality-ui connectors-ui local-models-ui viewport-dock-ui context-ui suspension-ui assistant-steering-ui assistant-chat-ui chat-dock-ui parametric-role-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui parametric-graph-ui design-disciplines-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) + foreach(check design-variants-ui component-library-ui design-review-ui inertial-ui viewport-quality-ui connectors-ui local-models-ui viewport-dock-ui context-ui suspension-ui assistant-steering-ui assistant-chat-ui chat-dock-ui parametric-role-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui parametric-graph-ui design-disciplines-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1440 900) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) endforeach() diff --git a/docs/DESIGN_REVIEW_067G.md b/docs/DESIGN_REVIEW_067G.md new file mode 100644 index 0000000..40ad018 --- /dev/null +++ b/docs/DESIGN_REVIEW_067G.md @@ -0,0 +1,54 @@ +# Revision review and guided repair — 067G + +Addresses **G.02**, **B.02** and **B.03**. Broader milestones remain **Parcial**. + +`design_review` offers three revision-bound actions: + +- `compare`: choose `before_id` from `history_info`; `after_id` defaults to + `current` or names another retained journal state. Both states are reconstructed + and evaluated privately. Reports distinguish feature additions/removals, + authored expression/reference/metadata changes, driven geometry changes, + named dimensions, assembly authoring and each revision's physical BOM. +- `diagnose`: evaluates private authoring and returns failed features, their + kernel/evaluation errors, current expressions, missing inputs, earlier + dependency choices and directly dependent features. The source SHA-256 binds + a correction to the inspected document. It also exposes retained rejected + single `feature.edit` operations at the current revision, including attempted + dimensions/references. This handles ordinary atomic edit rejection while the + current model remains valid; `failure_id` identifies that retained attempt. +- `prepare_repair`: supply `id`, the inspected `source_sha256`, and an explicit + `feature.edit` command correcting `p`, `native` or `inputs`. It creates an + ordinary `doc_preview` candidate. A separate revision-checked `doc_apply` + publishes the reviewed candidate. Invalid whole-document geometry rejects. + For a rejected operation, also supply its `failure_id`; the retained attempt + must belong to the same current revision and target exactly this feature. + +Every action requires `expected_revision`. Unknown revisions, stale sources, +deletion, suppression and unrelated feature edits reject. There is no automatic +reference substitution, tolerance inflation, discarded solid or silent rebase. +Repairs involving other operations must use the normal explicit authoring tools. +Multi-command rejected transactions remain visible in `rejected_operations`, +but are not reduced to a single-feature correction. Expired or older-revision +failure records cannot authorize a new repair. Changed tolerance/fuzzy fields +are rejected recursively, including inside native recipes. + +Studio exposes **Compare revisions**, **Repair failed feature** and **Hide review +overlay**. Comparison highlights before geometry in orange and after geometry +in cyan, with a selectable report window. Repair shows explicit editable +dimensions and reference/dependency recipes, then a checked candidate review +before Apply. Overlays invalidate on any revision or document change. + +Geometry comparison uses native B-rep fingerprints when present. Other geometry +is explicitly labelled `display_mesh_only`; tessellation is never production +authority. The overlay is derived wire geometry, not a geometric Boolean +difference or manufacturing qualification. Assembly quantities include the same +physical occurrences as the BOM contract. Only retained history can be compared; +this feature does not retrieve archived or external revisions or establish +distributed collaboration. + +Validation source: `tests/design_review_tests.cpp` covers driven native geometry, +named dimensions, assembly BOM quantities, no-mutation comparison, unknown/stale +revision rejection, failed-source diagnosis, retained repair preview, forbidden +suppression/tolerance changes, source fingerprint rejection, ordinary rejected +edits against a valid design and one atomic repair publication. +Executed results and UI captures are recorded in the iteration receipt. diff --git a/docs/DESIGN_VARIANTS_067G.md b/docs/DESIGN_VARIANTS_067G.md new file mode 100644 index 0000000..5a050e1 --- /dev/null +++ b/docs/DESIGN_VARIANTS_067G.md @@ -0,0 +1,73 @@ +# Design variants and parameter exploration — 067G + +Scope: **B.02/B.04/D.05/G.03 — Verificado no escopo local**. See the [iteration evidence](iterations/067G.md); broader milestones remain **Parcial**. + +The Studio **Design variants** window configures an installed parametric program. +**New family** installs one of the existing editable examples. The parameter list +shows authored values, units and declared bounds; **Edit value** stages a numeric +value. **Preview** evaluates the staged configuration without publishing it; +**Apply** prepares and publishes one revision-bound exact candidate. Undo restores +the previous editable source. + +**Save named variant** records a full parameter map, namespace and program-source +digest in the document. These are authored configurations, not cached B-reps. +The `.ark` file uses semantic version 56 only when this new data is present. +Saved values survive reopening. A changed program digest is explicitly stale; +it cannot silently apply to different program source. + +**Compare saved** evaluates every named alternative in an isolated session. The +window shows exact dimensions, summed terminal-part volume and mass when all +terminal parts have declared material densities. Three sampled mesh thumbnails +can be viewed side by side. Selecting a result loads its values for explicit +Save or Apply. Triangles are display evidence only and never select the production +geometry or measured dimensions. + +**Explore values** evaluates explicitly entered values for one parameter in the +native UI. Optional width/depth/height/mass limits filter feasibility. Explicit +feature pairs and a minimum gap use native B-rep distance/common-volume inspection +for each trial. Overlap, missing features or unavailable measurements cannot rank +as feasible. The Studio form accepts one pair; the tool accepts up to sixteen +through `clearance_pairs:[{a:"Left",b:"Right",min_mm:3}]`. + +The tool also supports a Cartesian grid of 1–4 parameter axes, with at most 64 combinations. +This is a bounded enumerator, not continuous or global optimization. Every trial, +including compile, assertion and geometry failures, remains in the result. + +## Agent contract + +`design_variants` exposes `inspect`, `save`, `remove`, `evaluate`, `explore` and +`prepare`. Except for inspection, every action requires `expected_revision`. +Save/remove/prepare return a `doc_preview` candidate; the caller explicitly sends +`doc_apply {candidate_id, expected_revision}` to publish it. + +```json +{"action":"evaluate","namespace":"shelf","expected_revision":12, + "variants":[ + {"name":"Compact","values":{"width":500,"shelves":3}}, + {"name":"Standard","values":{"width":800,"shelves":5}}, + {"name":"Wide","values":{"width":1100,"shelves":5}}], + "constraints":{"width_mm":{"max":1000}},"objective":"volume_mm3", + "direction":"min","thumbnails":true} +``` + +```json +{"action":"explore","namespace":"shelf","expected_revision":12, + "axes":{"width":[500,800,1100],"shelves":[3,5]}, + "constraints":{"height_mm":{"max":1900}},"objective":"volume_mm3"} +``` + +`ranked_indices` indexes `results` in objective order and includes only feasible +rows with the requested metric available. `mass_kg` is absent and cannot be ranked +when density is missing. `valid` means compilation and exact terminal-solid +inspection passed; `feasible` also checks caller-entered metric bounds. Program +assertions remain authored rules, not independently qualified requirements. + +The scope is terminal feature definitions owned by one program. It does not +multiply assembly occurrences or compute the union of overlapping components. +Replacement still rejects local edits and outside dependants under the existing +parametric-program contract. Stiffness, strength, fatigue, process cost, physical +clearance and manufacturing qualification are not inferred from volume or mass. +Pair clearance is static at the evaluated definition positions, not a +continuous-motion certificate. +AI authors can propose the value sets through this same tool; real-provider design +quality and savings require separate evidence. diff --git a/docs/DRAWING_LIBRARY_067G.md b/docs/DRAWING_LIBRARY_067G.md new file mode 100644 index 0000000..cbc0b5c --- /dev/null +++ b/docs/DRAWING_LIBRARY_067G.md @@ -0,0 +1,90 @@ +# Drawing delivery and the component library — 067G + +**B.05 / B.04 / F.03 — Verificado no escopo local.** See the [iteration evidence](iterations/067G.md). Broader milestones remain **Parcial**; local checks do not establish manufacturing approval. + +## Vector PDF and ordered sheet sets + +`drawing_export` accepts `format: "pdf"`, `expected_revision`, a new `path`, and +exactly one `name` or an ordered `names` array of 1–256 distinct sheet names. +Every sheet must have a current exact source binding and resolved dimensions. +One invalid or stale sheet rejects the entire export before publication. Existing +destinations are never replaced, including concurrent publication attempts. + +Each sheet keeps its own paper dimensions. The PDF contains vector paths and text, +page numbers and `/PrintScaling /None`; print at **Actual size / 100%** in the +recipient's PDF viewer. Physical printer calibration and non-printable margins +are outside ARK's local verification. The Studio Export dialog selects the format +and either the current sheet or all sheets in document order. + +PDF and SVG use the retained display polylines derived from exact drawing curves. +They are presentations, not exact geometry exchange; use the existing DXF route +for its separately documented canonical curve contract. PDF text supports Latin-1 +labels and rejects other scripts explicitly instead of replacing characters. + +## Authored geometric tolerance frames + +A drawing may retain up to 64 `geometric_tolerances` entries. Each has a unique +`name`, existing `view`, `characteristic`, positive numeric `value`, matching +sheet `units`, zero to three uppercase `datums`, and paper-coordinate +`position_mm` / `leader_mm` pairs. Characteristics include position, flatness, +straightness, circularity, cylindricity, parallelism, perpendicularity, angularity, +line/surface profile and runout/total runout. Form tolerances reject datum labels. + +The **Geometric tolerance** button in Manage Drawings authors or replaces a frame +by name, or removes it explicitly. Frames appear in Studio, SVG, PDF and the +derived DXF annotations. Unit edits preserve physical tolerance values; view +renames preserve annotation references. New frames require document semantics 56; +ordinary older drawings retain their existing version. + +These are caller-authored requirements with named characteristics, not a certified +ISO/ASME symbol layout, datum-system solver or inspection result. Leader positions +are authored presentation coordinates; they do not establish an exact face datum. + +## Visual parametric component library + +The **Component library** command opens a local folder of immutable `.arkprt` +parts and `.arktop` assemblies. Subfolders supply categories. Search matches the +name, filename, category and public parameter names; a kind filter separates parts +and assemblies. Selection displays the exposed parameter expressions and an +isometric thumbnail derived from evaluated geometry, with assembly placement. + +The agent-facing existing `parametric_components` tool gains two read actions: + +- `library`: explicit `directory`, optional `query`, `category`, `kind`. +- `thumbnail`: explicit component `path`; returns normalized display line segments + and the package digest. + +Catalog scans skip symlinks, examine at most 4096 entries and four subdirectory +levels, and return at most 256 matches with a `truncated` flag. Malformed packages +are reported separately. Thumbnail sampling is declared and is display-only. +Neither catalog scans nor thumbnails import a part or alter the open project. + +Insert and Update prepare the existing native candidate, show the checked result, +and apply only that candidate at the observed project revision. A file changed +since the catalog was read rejects until refresh. Updates require the same +component identity and its next explicit revision, preserving existing ownership, +local-edit and structural-change rejection rules. No network lookup or automatic +update runs. Catalog navigation and geometry preview execute through the Studio +worker/progress route. + +## Local verification + +- `associative-drawings` passed the existing exact source/export checks plus PDF, + ordered two-sheet delivery, authored frame persistence, semantic downgrade + rejection, stale-sheet atomic rejection and no-replace publication. +- `parametric-components-053b` passed 106 assertions, including public-parameter + catalog search, evaluated thumbnail and stale source-digest rejection. +- `studio-component-library-ui` exercised native search, insertion with public + overrides and explicit revision update; normal and 960×640 captures were + inspected. `studio-drawing-workspace-1180`, its 1440 variant and + `studio-drawing-viewport-ui` passed; frame authoring, PDF export and affected + controls were inspected in captures. +- Independent PDF readback identified one A4 sheet with 72 vector paths and an + ordered two-sheet A4 set with 72/90 paths, all with extractable text and zero + embedded images. All three rendered pages were inspected after correcting + label/leader placement. Local printer output and independent drafting-standard + qualification were not tested. + +Evidence files are local under the build's `verification-067g` and `ui-checks` +folders; only synthetic fixtures were used. The integrated native/UI receipt and +installer verification are recorded by the 067G delivery workflow. diff --git a/docs/MULTI_AGENT_STUDIO.md b/docs/MULTI_AGENT_STUDIO.md index f4a37d1..4e91e2f 100644 --- a/docs/MULTI_AGENT_STUDIO.md +++ b/docs/MULTI_AGENT_STUDIO.md @@ -71,8 +71,12 @@ The local `studio-parametric-role-ui` check covers this option offline. A scripted Focused team runs through Studio's own tool queue: the engineer assigns the role, it publishes one program candidate, native inspection measures both generated solids at their exact volumes, the reviewer reports and the goal is -reported complete. Its 117-function catalogue, 43 after deferral with the -`overview` and `programs` pack, is within the 128-function limit. Legacy settings +reported complete. In 067G its 117-function catalogue, 44 after deferral with the +`overview` and `programs` pack, is within the 128-function limit. Host receipt and +maintenance operations (`usage_record`, `compute_benchmark`, `history_compact`, +`history_migrate_derived`, `memory_maintain`, `failure_export`) remain available +outside shared Team turns. Variant and repair previews retain role ownership and +undergo ordinary command-scope checks before a Team can apply them. Legacy settings are read back with their owners, and a disabled role leaves a default run of three roles. Role cards stay inside the dock at eight window sizes from 1180x800 to 3840x2160, in normal and expanded docks. Captures up to 2560x1200 diff --git a/docs/README.md b/docs/README.md index 704ab4f..1d51858 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,6 +29,9 @@ current release claim. [release.json](../release.json) owns application identity | [029B assembly scaling](ASSEMBLY_SCALING_029B.md) | You need selective memory/I/O and configuration/pin ownership in isolated workspaces | | [023B test guide](AUTHORING_023B_TESTING.md) | You are testing STEP/IGES import, Arkitfy, functional holes or isolated design containers | | [Parametric programs](PARAMETRIC_PROGRAMS.md) | You want a configurable family written as code: counts, conditions, generated sketches and design assertions | +| [067G design variants](DESIGN_VARIANTS_067G.md) | You want saved configurations, visual comparison or bounded exploration of exact parametric alternatives | +| [067G revision review and repair](DESIGN_REVIEW_067G.md) | You want to compare retained design revisions or preview an explicit failed-feature correction | +| [067G drawing output and component library](DRAWING_LIBRARY_067G.md) | You want multipage PDF drawings, declared geometric tolerances or a visual reusable-component browser | | [023B Holes Orchestrator](HOLES_ORCHESTRATOR_023B.md) | You need parametric holes, thread preparation, dowels or retaining-ring grooves with published nominal sources | | [023B CAD import](CAD_IMPORT_023B.md) | You need portable exact STEP/IGES references and measured reconstruction checks | | [023B design containers](DESIGN_CONTAINERS_023B.md) | You need scoped editing in another document or ARK instance and guarded integration | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index f47353e..15ad629 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,5 +1,12 @@ # ARK roadmap A–G +067G (**B.02/B.03/B.04/B.05/D.02/D.05/F.03/G.02/G.03 — Verificado no escopo local**): +persistent program variants and measured grid exploration, retained-revision +comparison, reviewed repair of rejected edits, multipage vector PDF with declared +geometric tolerances and a visual parametric component library. Native CTest +182/182 and ten affected Studio suites passed. Broader milestones remain +**Parcial**; see [067G evidence and limits](iterations/067G.md). + 066D (**B.02/D.02/G.01 — Verificado no escopo local**): parametric programs write a design as bounded code that compiles to namespaced native features, with atomic re-runs. Agents load the `programs` skill, and Studio offers an optional Parametric @@ -401,7 +408,7 @@ Goal: create and revise a complete product with clear, reliable interactions. | B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. [Parametric programs](PARAMETRIC_PROGRAMS.md) compile code-defined families into namespaced native features, with atomic re-runs that reject local edits and outside dependants (local CTest only). | | B.03 | Advanced solids and surfaces | Parcial | Difficult loft/sweep/guide/patch/trim/thicken corpus, measured continuity and explicit repair; no mesh fallback concealing exact failures. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact sketch extrusion](iterations/020B.md). [021B bounded face/extrusion geometry](iterations/021B.md). [022B exact polyhedral vertex pull](NATIVE_VERTEX_PULL_022B.md) adds a bounded faceted-solid domain with input/output validity and selfinterference checks. 029B adds bounded exact orientation repair and a difficult geometry corpus; [repair evidence](SURFACE_REPAIR_029B.md). [046B hollow sweep sections](PROFILE_REGIONS_046B.md) sweep inner loops with one shared placement and a volume-conservation check. [051A native regression evidence](NATIVE_GEOMETRY_051A.md) covers shallow C0 offset classification and translated analytic C2 lofts with unchanged tolerances. | | B.04 | Large, configurable assemblies | Parcial | Subassemblies, reused instances, configurations, external references and selective loading; editing one definition updates all occurrences. Supported mechanisms are locally scoped. [022B source-linked component patterns](SPECIALIZED_PATTERNS_022B.md) cover inheritance, planar/spatial points, exact curve stations, chain alternation, skips and actual occurrence consumers; large configuration/loading qualification remains open. 029B adds semantic loading, measured derived-buffer/external-I/O reduction and scoped v2 configuration/pin ownership; [assembly evidence](ASSEMBLY_SCALING_029B.md). [048B exploded views](EXPLODED_VISUALIZE_048B.md) are display-only, revision-neutral and drivable by baked motions. [051A definition-owned sketches](SCOPED_SKETCHES_051A.md) are shared across occurrences and remapped with component checkout/merge. [053B reusable recipes](PARAMETRIC_COMPONENTS_053B.md) embed parts/assemblies with public overrides and explicit pinned revision updates. | -| B.05 | Technical drawings and exchange | Parcial | Local 022B binds part definitions, exact occurrences and root/group assemblies to source-linked views, isometric projections, planar sections/hatches, semantic dimensions and declared tolerances in the same CAD viewport. Agents author drawings only on explicit user request. 029B adds bounded exact DXF export with local readback and source metadata. Drafting standards, GD&T, PDF, independent recipient interoperability and physical qualification remain open. [Drawing contract](DRAWINGS.md) [022B viewport evidence](DRAWING_VIEWPORT_022B.md) [029B evidence](VERIFICATION_029B.md). [048B Visualize](EXPLODED_VISUALIZE_048B.md) renders exploded assembly images with balloons and a BOM table on explicit request. | +| B.05 | Technical drawings and exchange | Parcial | Local 022B binds part definitions, exact occurrences and root/group assemblies to source-linked views, isometric projections, planar sections/hatches, semantic dimensions and declared tolerances in the same CAD viewport. Agents author drawings only on explicit user request. 029B adds bounded exact DXF export with local readback and source metadata. Broader drafting standards, GD&T qualification, independent recipient interoperability and physical qualification remain open. [067G](DRAWING_LIBRARY_067G.md) adds local multipage vector PDF presentation and caller-declared named geometric tolerance frames. [Drawing contract](DRAWINGS.md) [022B viewport evidence](DRAWING_VIEWPORT_022B.md) [029B evidence](VERIFICATION_029B.md). [048B Visualize](EXPLODED_VISUALIZE_048B.md) renders exploded assembly images with balloons and a BOM table on explicit request. | ## C — Engineering and manufacturing @@ -477,8 +484,8 @@ Goal: explore alternatives and collaborate at complex-product scale. | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| | G.01 | Stable SDK and extensions | Parcial | Typed APIs/contracts/examples, permissions/sandbox and compatibility across two versions; define any SDK scope explicitly. [Parametric programs](PARAMETRIC_PROGRAMS.md) are a first typed, bounded design-source contract (`ark.parametric-program.v1`) with examples and no script execution; compatibility across two released versions and a general SDK remain open. | -| G.02 | Distributed collaboration and review | Planeado | Comments, geometric diffs and revision approvals; deterministic replay, conflict resolution and organization data isolation. | -| G.03 | Multi-objective parametric exploration | Planeado | Search mass/stiffness/cost/manufacturing within validated domains; establish feasibility before ranking and compare with a human baseline. | +| G.02 | Distributed collaboration and review | Parcial | [067G local revision review](DESIGN_REVIEW_067G.md) compares retained revisions with derived overlays and source/BOM changes; distributed collaboration remains unqualified. Comments, geometric diffs and revision approvals; deterministic replay, conflict resolution and organization data isolation. | +| G.03 | Multi-objective parametric exploration | Parcial | [067G bounded exploration](DESIGN_VARIANTS_067G.md) evaluates explicit grids, native dimensions/volume, density-backed mass and declared static clearance pairs, retaining invalid trials; global optimization and structural ranking remain unqualified. Search mass/stiffness/cost/manufacturing within validated domains; establish feasibility before ranking and compare with a human baseline. | | G.04 | Portability and remote execution | Verificado no escopo | 016F locally verified Ubuntu 24.04 Linux CLI/MCP/OCCT 8.0.1 worker: native CTest 65/65, core-only 42/42, clean-container relocated package with exact-solid/STEP/document readback. Linux Studio, network/authentication transports, OTA, remote workers and macOS remain outside that scope. [Linux build evidence](NATIVE_BUILD.md#local-linux-verification--016f) | | G.05 | Verifiable virtual product | Planeado | Assembly/material/load/motion/manufacturing/cost linked by revision; changes invalidate stale evidence; measured pilots show operational value. | diff --git a/docs/iterations/067G.md b/docs/iterations/067G.md new file mode 100644 index 0000000..9bb19c4 --- /dev/null +++ b/docs/iterations/067G.md @@ -0,0 +1,65 @@ +# 067G — configurable designs, review and drawing delivery + +Runtime identity: **067G / 0.9.68**. The implementation below is **Verificado no escopo local**; the broader roadmap milestones remain **Parcial**. + +## Delivered workflows + +| Roadmap | Usable scope | +|---|---| +| B.02 / B.04 | Studio configurator for installed parametric programs: typed public values, Preview/Apply, named saved variants, Undo and save/reopen. | +| D.05 | Agent-accessible alternatives evaluated in isolated native candidates, exact measurement table and three side-by-side display thumbnails. | +| G.03 | Explicit grids of up to four parameters and 64 combinations, metric constraints, declared static clearance pairs and ranking of feasible measured results. Failed trials remain visible. | +| G.02 | Compare retained journal revisions, with before/after overlays, parameter/native geometry changes and revision-specific assembly/BOM differences. | +| B.02 / B.03 | Diagnose failed source and retained rejected single-feature edits, edit the proposed correction, preview it and publish once at the observed revision. | +| B.05 | Ordered multipage vector PDF, caller-declared geometric tolerance frames, current/all-sheet output, sheet paper/scale and no automatic print scaling. | +| B.04 / F.03 | Local visual parametric component browser with name/category/parameter search, derived previews, explicit parameter overrides and reviewed revision insertion/update. | + +Open **All tools / Ctrl+K** and search for **Parametric configurator**, **Compare design revisions**, **Repair failed feature** or **Visual component library**. Drawing PDF and tolerance controls are in the existing drawing workspace. Agent onboarding includes `variants` and `design_review`. + +Contracts: [design variants](../DESIGN_VARIANTS_067G.md), [revision review and repair](../DESIGN_REVIEW_067G.md), [drawing output and library](../DRAWING_LIBRARY_067G.md). + +## Integrity and persistence + +- Native B-rep remains geometry authority. Thumbnails and overlays are derived presentation only. +- Saved variants retain program-source hashes and explicit numeric configurations. Source changes require review; stale revisions and candidates reject without rebasing. +- New variant/tolerance data uses document semantics 56. Documents without those fields retain their existing conditional semantic version; the application iteration alone does not change a drawing format. +- Repairs cannot delete/suppress bodies, relax tolerances or substitute references silently. A failed correction leaves the valid current document unchanged. +- Team-owned previews undergo the same role-scope checks as ordinary commands. The single catalogue has 124 tools; the tested ParametricDesigner provider catalogue has 117, or 44 after its topic deferral, within the 128-function limit. +- Source-file digest checks bind library preparation to the catalog selection. PDFs publish atomically to new paths and reject stale sheets as a whole set. + +## Observed verification + +| Check | Local result | +|---|---| +| Native CTest | **182/182 passed** | +| Affected Studio suites | **10/10 passed**: variants, library, revision review, parametric role, drawing viewport, drawing workspace at 1180 and 1440, action icons, asynchronous authoring and realtime controls | +| Variant contracts | Exact bounds/volume, declared-density mass, static gaps/overlap, retained invalid trials, stale-program/candidate rejection, named configuration persistence and Undo | +| Revision/repair contracts | Native fingerprints, driven dimensions, occurrence quantities, canonical metadata ordering, unchanged source during comparison, real rejected edit recovery and stale-failure rejection | +| Drawing/library contracts | PDF/GD&T/multiple sheets, semantic downgrade/stale export rejection; 106 component assertions including catalog, thumbnail and changed-package rejection | +| PDF readback | One-page and two-page A4 fixtures, 72 and 72/90 vector paths respectively, zero raster images, retained dimensions and tolerance text | +| Visual review | Normal/compact configurator and library, revision overlay/report/repaired model, both drawing workspace sizes and all three PDF pages inspected | +| Final executable recheck | **14/14 passed**, including all ten affected Studio suites and four native suites; staged-value preservation assertion present and exercised in the rebuilt binary | +| Portable package/public installer | Relocated native STEP export, installation, runtime receipt, launcher and uninstall passed in isolation | +| Installer upgrade/rollback | Isolated 066D-to-067G upgrade, rollback state, reinstall, licence payload, preserved synthetic documents/settings and unchanged real registration/shortcuts passed; options/completion captures inspected | + +Receipts remain in the local build output and alongside the delivered artifacts. The portable ZIP is `ark-windows-x64-0.9.68.zip`; the installer is `ARK-067G-windows-x64-setup.exe` (170231875 bytes). SHA-256: `d8fd121205313d6a97e08f807f892f851e66bbf7f1a41e9cff9a2b64ffca204f`. The real per-user installation remained at 066D; these checks did not upgrade the user's live application. + +### Failures found and resolved + +The initial native run passed 179/182: two tests still treated semantic version 56 as a future format, and new onboarding topics omitted the drawing-authorization policy. All were corrected and the complete suite passed. + +Initial modeless-window tests stalled because a continuously repainted native control could starve the worker completion check inside an unbounded message drain. The worker loops now drain bounded message batches, clear deferred internal paints and invalidate visible controls after work. The new windows then passed in approximately 1–2 seconds; existing asynchronous authoring and realtime tests also passed. This bounds UI event handling, not agent turns or tokens. + +Visual review corrected thumbnail painter ordering, tolerance-frame leaders/text sizing and revision-report labels. A named variant save preserves staged values for subsequent Apply. + +A pre-delivery ZIP was rejected before any installer or publication because its Studio compilation had started before the final staged-value preservation edit. It was retained outside the delivery folder as a rejected artifact; Studio was rebuilt from frozen source and the explicit staged-save assertion was checked in the rebuilt executable before repeating the affected suites. + +## Limits + +- Alternative generation uses the same callable contracts available to agents; model-provider quality, economic savings and autonomous design acceptance are not established by scripted tests. +- Exploration is a bounded explicit grid, not global or continuous optimization. It measures terminal program definitions, not union volume or multiplied assembly quantities. Mass requires declared densities; stiffness, FEA, fatigue and manufacturing qualification remain separate. +- Clearance is static at evaluated positions, not a continuous-motion certificate. Every failed attempt remains part of the result. +- Revision review covers retained local history, not distributed multi-user collaboration or archived/external revision retrieval. Overlays are visual comparisons, not exact Boolean difference solids. +- Tolerance frames are named authored requirements, not a certified ISO/ASME symbol/datum/metrology system. PDF uses existing derived drawing samples; exact DXF retains its separate contract. PDF labels are Latin-1; unsupported scripts reject explicitly. +- Only the affected ten Studio suites were rerun here; this does not claim that every historical Studio failure was repaired. +- Clean-machine qualification, Authenticode signing, hosted publication and online-update transport are not established by local installer checks. User drawings, sessions and installed application registration are outside test fixtures. diff --git a/include/ark/design_review.hpp b/include/ark/design_review.hpp new file mode 100644 index 0000000..686677e --- /dev/null +++ b/include/ark/design_review.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "ark/agent.hpp" +#include +namespace ark { +// Retained immutable journal snapshots are replayed into private documents. +// Comparisons never restore/publish a document or edit the journal. +arkjson::Value compareDesignRevisions(const Document& source,u64 revision,const std::string& beforeId,const std::string& afterId="current"); +arkjson::Value diagnoseDesignFeatures(const Document& source,u64 revision); +bool callDesignReviewTool(AgentSession&,const std::string&,const arkjson::Value&,arkjson::Value&); +void appendDesignReviewTools(arkjson::Value&); +} diff --git a/include/ark/design_variants.hpp b/include/ark/design_variants.hpp new file mode 100644 index 0000000..2f16ff1 --- /dev/null +++ b/include/ark/design_variants.hpp @@ -0,0 +1,9 @@ +#pragma once +#include "ark/agent.hpp" +namespace ark { +// Saved configurations contain authored parameter values, never cached geometry. +void validateDesignVariants(const arkjson::Value&); +bool applyDesignVariantCommand(Document&,const arkjson::Value&); +bool callDesignVariantsTool(AgentSession&,const std::string&,const arkjson::Value&,arkjson::Value&); +void appendDesignVariantsTools(arkjson::Value&); +} diff --git a/include/ark/drawings.hpp b/include/ark/drawings.hpp index 9c34115..b38052a 100644 --- a/include/ark/drawings.hpp +++ b/include/ark/drawings.hpp @@ -14,6 +14,9 @@ void applyDrawingCommand(Document&, const arkjson::Value& command); void refreshDrawing(Document&, const std::string& name, u64 observedRevision); arkjson::Value inspectDrawing(Document&, const arkjson::Value& args, u64 revision); arkjson::Value exportDrawing(Document&, const arkjson::Value& args, u64 revision); +// Vector presentation of current derived sheets. Curves use the retained display +// samples, not a new exact geometry authority. The caller owns file publication. +std::string drawingPdfPresentation(const std::vector& reports); } namespace ark::occt { diff --git a/include/ark/model.hpp b/include/ark/model.hpp index 86013b7..12c7b81 100644 --- a/include/ark/model.hpp +++ b/include/ark/model.hpp @@ -332,6 +332,7 @@ class Document { arkjson::Value parametricComponents; // embedded immutable .arkprt/.arktop definitions and explicit instance bindings arkjson::Value manufacturingPlans; // source-bound manufacturing DAGs; simulation remains derived arkjson::Value parametricPrograms; // ark.parametric-program.v1 sources, values and namespace ownership baselines + arkjson::Value designVariants; // named parameter configurations bound to a parametric program digest arkjson::Value schematics; // independent editable 2D circuit sheets, symbols, pins and explicit wires std::vector componentBindingsToSeal; // transient, only a component command can request a new evaluated baseline std::vector programBindingsToSeal; // transient, only program.bind can request a new evaluated baseline diff --git a/include/ark/parametric_components.hpp b/include/ark/parametric_components.hpp index 5fe6eaa..687979d 100644 --- a/include/ark/parametric_components.hpp +++ b/include/ark/parametric_components.hpp @@ -15,4 +15,7 @@ bool callParametricComponentTool(AgentSession&, const std::string&, const arkjso void appendParametricComponentTools(arkjson::Value&); // Same authored relation index as context_graph, without its agent response cap. arkjson::Value parametricGraphSnapshot(const Document&, u64 revision); +// Explicit local-folder catalog; no network, installation or source rewriting. +arkjson::Value parametricComponentLibrary(const arkjson::Value& args); +arkjson::Value parametricComponentThumbnail(const std::string& path); } diff --git a/release.json b/release.json index c2fdb73..1a68d00 100644 --- a/release.json +++ b/release.json @@ -1,11 +1,17 @@ { - "sequence": 66, - "phase": "D", - "code": "066D", - "version": "0.9.67", + "sequence": 67, + "phase": "G", + "code": "067G", + "version": "0.9.68", "milestones": [ "B.02", + "B.03", + "B.04", + "B.05", "D.02", - "G.01" + "D.05", + "F.03", + "G.02", + "G.03" ] } diff --git a/src/agent.cpp b/src/agent.cpp index 5692c8a..8838bea 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -17,6 +17,8 @@ #include "ark/design_containers.hpp" #include "ark/parametric_components.hpp" #include "ark/parametric_programs.hpp" +#include "ark/design_variants.hpp" +#include "ark/design_review.hpp" #include "ark/design_disciplines.hpp" #include "ark/holes_orchestrator.hpp" #include "ark/collision.hpp" @@ -809,7 +811,7 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(expected->t!=V::Num||expected->num!=(double)revision) throw std::runtime_error("Revision conflict; the current revision is in this result. Inspect only what your edit depends on and retry"); if(tool=="context_graph")return result(projectContextGraph(document,revision,args,contextGraphCache_,contextGraphSource_,contextGraphStamp_)); - V extension;if(callTransmissionTool(*this,tool,args,extension))return result(extension);if(callManufacturingTool(*this,tool,args,extension))return result(extension);if(callDesignDisciplineTool(*this,tool,args,extension))return result(extension);if(callParametricComponentTool(*this,tool,args,extension))return result(extension);if(callParametricProgramTool(*this,tool,args,extension))return result(extension);if(callProjectMemoryTool(*this,tool,args,extension))return result(extension);if(callAuthoring023Tool(*this,tool,args,extension))return result(extension);if(callComponentLibraryTool(*this,tool,args,extension))return result(extension);if(callAgentFeature(*this,tool,args,extension))return result(extension);if(callParametricHudTool(*this,tool,args,extension))return result(extension); + V extension;if(callDesignVariantsTool(*this,tool,args,extension))return result(extension);if(callDesignReviewTool(*this,tool,args,extension))return result(extension);if(callTransmissionTool(*this,tool,args,extension))return result(extension);if(callManufacturingTool(*this,tool,args,extension))return result(extension);if(callDesignDisciplineTool(*this,tool,args,extension))return result(extension);if(callParametricComponentTool(*this,tool,args,extension))return result(extension);if(callParametricProgramTool(*this,tool,args,extension))return result(extension);if(callProjectMemoryTool(*this,tool,args,extension))return result(extension);if(callAuthoring023Tool(*this,tool,args,extension))return result(extension);if(callComponentLibraryTool(*this,tool,args,extension))return result(extension);if(callAgentFeature(*this,tool,args,extension))return result(extension);if(callParametricHudTool(*this,tool,args,extension))return result(extension); {V out;if(callAuthoring024Tool(*this,tool,args,out))return result(out);if(callMotionTool(*this,tool,args,out))return result(out);if(callDragChainTool(*this,tool,args,out))return result(out);Image image;if(callExplodedViewTool(*this,tool,args,out,&image))return image.w?snapshotImageResult(image,out,std::string()):result(out);} if(tool=="collision_inspect"||tool=="skeleton_inspect"||tool=="skeleton_compile"){ if(const auto* expected=args.find("expected_revision"))if(expected->t!=V::Num||expected->num!=(double)revision)throw std::runtime_error("Revision conflict; inspect the current document before querying"); @@ -1322,7 +1324,8 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ const auto sketchName=op.rfind("sketch.",0)==0&&c.find("name")?sketchReference(c.find("owner_feature")?featureRef(next,*c.find("owner_feature")):0,str(c,"name")):std::string(); if(next.historyTip&&(op=="feature.add"||op=="sheet.create"||op=="skeleton.set"))throw std::runtime_error("Resume full feature history before adding features or changing Skeleton source"); if(op=="feature.move"&&skeletonOwnsFeature(next,featureRef(next,field(c,"id"))))throw std::runtime_error("Skeleton pattern is source-owned; change its source instead of reordering generated features"); - if(op.rfind("program.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Parametric program commands require expected_revision");if(!applyParametricProgramCommand(next,c))throw std::runtime_error("Unknown program command");} + if(op.rfind("variant.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Variant commands require expected_revision");if(!applyDesignVariantCommand(next,c))throw std::runtime_error("Unknown variant command");} + else if(op.rfind("program.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Parametric program commands require expected_revision");if(!applyParametricProgramCommand(next,c))throw std::runtime_error("Unknown program command");} else if(op.rfind("component.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Parametric component commands require expected_revision");if(!applyParametricComponentCommand(next,c))throw std::runtime_error("Unknown component command");validated(next);} else if(op.rfind("manufacturing.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Manufacturing commands require expected_revision");if(!applyManufacturingCommand(next,c))throw std::runtime_error("Unknown manufacturing command");} else if(op=="classification.set"||op.rfind("schematic.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Classification and schematic commands require expected_revision");if(!applyDesignDisciplineCommand(next,c))throw std::runtime_error("Unknown discipline command");} @@ -1694,7 +1697,7 @@ V AgentSession::tools(bool detailed){ {"assembly_authoring_info","Inspect named configurations, selected loading roots and pinned imported source references at the current revision. Source drift rejects instead of substituting geometry.",R"({"type":"object","properties":{},"additionalProperties":false})",true}, {"skeleton_inspect","Inspect native Skeleton code, editable inputs, source-owned relations/vector arrays and stable pattern ownership. Read-only; lengths mm.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0}},"additionalProperties":false})",true}, {"drawing_inspect","List authored technical drawings, or inspect one name with exact orthographic HLR/section curves and semantic dimensions. Changed source B-reps return stale and omit current measurements; missing references/source return invalid. Use explicit revision-checked drawing.refresh before export. Feature definitions, exact occurrence/copy or root/group assemblies. Empty args returns a passive source catalog with editable suggested_drawing recipes; users must request drawings before agents author them. Original templates, tolerances, exact sections and isometric views share Studio CAD viewport. SVG is display sampling, JSON retains exact derived curves.",R"({"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"expected_revision":{"type":"integer","minimum":0}},"additionalProperties":false})",true}, - {"drawing_export","Atomically publish a new local json, svg or dxf technical drawing at expected_revision. Requires a current exact source/occurrence binding and resolved dimensions. Only export when the user requests it. JSON retains derived exact B-rep curves, samples and measurements; SVG is a display preview with dimension/tolerance labels; DXF preserves exact projected curves and section hatches with source metadata and local readback checks. CAD associativity and drafting qualification are not claimed. Existing destinations and stale/invalid drawings reject.",R"({"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"expected_revision":{"type":"integer","minimum":0},"path":{"type":"string","minLength":1,"maxLength":4096},"format":{"enum":["json","svg","dxf"]}},"required":["name","expected_revision","path","format"],"additionalProperties":false})",false}, + {"drawing_export","Atomically publish a new local json, svg, dxf or multipage vector pdf technical drawing at expected_revision. Requires a current exact source/occurrence binding and resolved dimensions. Only export when the user requests it. JSON retains derived exact B-rep curves, samples and measurements; SVG and PDF present derived geometry with dimension/tolerance labels; names selects ordered sheets for PDF only. DXF preserves exact projected curves and section hatches with source metadata and local readback checks. CAD associativity and drafting qualification are not claimed. Existing destinations and stale/invalid drawings reject.",R"({"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"expected_revision":{"type":"integer","minimum":0},"path":{"type":"string","minLength":1,"maxLength":4096},"format":{"enum":["json","svg","dxf","pdf"]},"names":{"type":"array","minItems":1,"maxItems":256,"uniqueItems":true,"items":{"type":"string","minLength":1,"maxLength":128}}},"required":["expected_revision","path","format"],"oneOf":[{"required":["name"],"not":{"required":["names"]}},{"required":["names"],"not":{"required":["name"]}}],"additionalProperties":false})",false}, {"skeleton_compile","Read-only native declarative Skeleton syntax/relation preview. Declarations: input name = expression; relation name = expression; array name[count] = [x,y,z] using index; pattern name from feature count expression step [x,y,z]. No arbitrary code execution. Use doc_preview/doc_apply skeleton.set for geometry-checked atomic changes.",R"({"type":"object","properties":{"source":{"type":"string","maxLength":65536},"expected_revision":{"type":"integer","minimum":0}},"required":["source"],"additionalProperties":false})",true}, {"collision_inspect","Read-only collision feedback for two feature definitions or placed assembly occurrences. Exact single solids return contact, distance and intersection volume; triangle meshes return real boundary contacts and bounded containment evidence with explicit unknowns. Not dynamics or manufacturing qualification. mode exact rejects mesh inputs; auto uses existing native authority when both operands have B-reps. a/b are id/name or {id} / {node,copy}. Same operand rejects.",R"({"type":"object","properties":{"a":{"type":["integer","string","object"]},"b":{"type":["integer","string","object"]},"mode":{"type":"string","enum":["auto","exact","mesh"]},"expected_revision":{"type":"integer","minimum":0}},"required":["a","b"],"additionalProperties":false})",true}, {"mesh_inspect","Compact indexed topology audit: bounds, area, edge counts, components and signed volume for closed oriented edges. Does not certify solids or detect self intersections. Omit id to inspect final outputs only. node accepts a unique instance name or an id, and copy frames one pattern placement.",R"({"type":"object","properties":{"node":{"anyOf":[{"type":"integer","minimum":1},{"type":"string"}]},"copy":{"type":"integer","minimum":0,"maximum":31},"id":{"type":"integer","minimum":1}}})",true}, @@ -1807,11 +1810,11 @@ if(std::string(d.name)=="doc_apply"){ enrichModeling031BSchemas(list); {V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("context_graph"));tool.set("description",V::makeStr("Retrieve a small linked project context by query or exact keys. Includes authored dependencies/backlinks and attributed saved feedback; no geometry evaluation. Use known_scope and known_fingerprints to omit unchanged facts. Read object_context/native evidence before editing; this graph grants no write or manufacturing authority."));arkjson::parse(R"({"type":"object","properties":{"query":{"type":"string","maxLength":256},"keys":{"type":"array","minItems":1,"maxItems":64,"items":{"type":"string","maxLength":256}},"depth":{"type":"integer","minimum":0,"maximum":2},"limit":{"type":"integer","minimum":1,"maximum":64},"history_limit":{"type":"integer","minimum":0,"maximum":8},"expected_revision":{"type":"integer","minimum":0},"known_scope":{"type":"string","maxLength":256},"known_fingerprints":{"type":"object","additionalProperties":{"type":"string","maxLength":64}}},"additionalProperties":false})",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(true));tool.set("annotations",annotations);list.arr.push_back(tool);} for(auto& tool:list.arr)if(tool.find("name")->str=="doc_apply"){V schema=*tool.find("inputSchema"),props=*schema.find("properties"),flag=V::makeObj();flag.set("type",V::makeStr("boolean"));props.set("refresh_candidate",flag);schema.set("properties",props);tool.set("inputSchema",schema);} - appendProjectMemoryTools(list);appendParametricComponentTools(list);appendParametricProgramTools(list);appendDesignDisciplineTools(list);appendManufacturingTools(list);appendTransmissionTools(list); + appendDesignVariantsTools(list);appendDesignReviewTools(list);appendProjectMemoryTools(list);appendParametricComponentTools(list);appendParametricProgramTools(list);appendDesignDisciplineTools(list);appendManufacturingTools(list);appendTransmissionTools(list); for(auto& tool:list.arr)if(tool.find("name")->str=="doc_apply"||tool.find("name")->str=="doc_preview"){ V schema=*tool.find("inputSchema"),props=*schema.find("properties"),commands=*props.find("commands"),items=*commands.find("items"),cp=*items.find("properties"),op=*cp.find("op"),en=*op.find("enum"); - for(const auto* name:{"component.insert","component.update","component.configure"})en.arr.push_back(V::makeStr(name));op.set("enum",en);cp.set("op",op); - for(const auto* key:{"package","overrides"}){V shape=V::makeObj();shape.set("type",V::makeStr("object"));cp.set(key,shape);}for(const auto* key:{"namespace","package_sha256","expected_package_sha256"}){V shape=V::makeObj();shape.set("type",V::makeStr("string"));cp.set(key,shape);}items.set("properties",cp);commands.set("items",items);props.set("commands",commands);schema.set("properties",props);tool.set("inputSchema",schema); + for(const auto* name:{"component.insert","component.update","component.configure","program.bind","program.clear","program.detach","variant.set","variant.remove"})en.arr.push_back(V::makeStr(name));op.set("enum",en);cp.set("op",op); + for(const auto* key:{"package","overrides","program","values"}){V shape=V::makeObj();shape.set("type",V::makeStr("object"));cp.set(key,shape);}for(const auto* key:{"namespace","package_sha256","expected_package_sha256","program_sha256","expected_program_sha256"}){V shape=V::makeObj();shape.set("type",V::makeStr("string"));cp.set(key,shape);}items.set("properties",cp);commands.set("items",items);props.set("commands",commands);schema.set("properties",props);tool.set("inputSchema",schema); } return list; } diff --git a/src/agent_team.cpp b/src/agent_team.cpp index fb345ac..c3194a0 100644 --- a/src/agent_team.cpp +++ b/src/agent_team.cpp @@ -51,12 +51,12 @@ V revisionVerification032D(const V& result){ bool scopedTool(AgentTeamDiscipline discipline,const std::string& name){if(discipline==AgentTeamDiscipline::General||discipline==AgentTeamDiscipline::Orchestrator)return true;if(!documentMutation(name))return true;return name=="doc_apply"||name=="team_apply_step";} bool scopedCommand(AgentTeamDiscipline discipline,const std::string& op){if(discipline==AgentTeamDiscipline::General)return true;if(discipline==AgentTeamDiscipline::PhysicsReviewer)return false; // A program candidate is program.* plus the four creation ops it compiles to. - if(discipline==AgentTeamDiscipline::ParametricDesigner)return op.rfind("program.",0)==0||op=="feature.add"||op=="sketch.set"||op=="plane.set"||op=="material.set";if(op.rfind("program.",0)==0)return true;if(discipline==AgentTeamDiscipline::Orchestrator&&(op=="skeleton.set"||op=="skeleton.remove"||op.rfind("assembly.",0)==0||op.rfind("mate.",0)==0||op.rfind("configuration.",0)==0||op.rfind("motion.",0)==0||op.rfind("explode.",0)==0||op.rfind("drag_chain.",0)==0||op.rfind("manufacturing.",0)==0))return true;return op=="light_up"||op=="bom.initialize"||op.rfind("feature.",0)==0||op.rfind("sketch.",0)==0||op.rfind("drawing.",0)==0||op.rfind("canvas.",0)==0||op.rfind("plane.",0)==0||op.rfind("sheet.",0)==0||op.rfind("frame.",0)==0||op.rfind("material.",0)==0||op.rfind("param.",0)==0;} + if(discipline==AgentTeamDiscipline::ParametricDesigner)return op.rfind("program.",0)==0||op.rfind("variant.",0)==0||op=="feature.add"||op=="sketch.set"||op=="plane.set"||op=="material.set";if(op.rfind("program.",0)==0||op.rfind("variant.",0)==0)return true;if(discipline==AgentTeamDiscipline::Orchestrator&&(op=="skeleton.set"||op=="skeleton.remove"||op.rfind("assembly.",0)==0||op.rfind("mate.",0)==0||op.rfind("configuration.",0)==0||op.rfind("motion.",0)==0||op.rfind("explode.",0)==0||op.rfind("drag_chain.",0)==0||op.rfind("manufacturing.",0)==0))return true;return op=="light_up"||op=="bom.initialize"||op.rfind("feature.",0)==0||op.rfind("sketch.",0)==0||op.rfind("drawing.",0)==0||op.rfind("canvas.",0)==0||op.rfind("plane.",0)==0||op.rfind("sheet.",0)==0||op.rfind("frame.",0)==0||op.rfind("material.",0)==0||op.rfind("param.",0)==0;} std::string leadRoleId(const std::vector& roles){for(const auto& role:roles)if(role.discipline==AgentTeamDiscipline::Orchestrator)return role.id;for(const auto& role:roles)if(role.id=="engineer")return role.id;for(const auto& role:roles)if(role.canWrite)return role.id;return roles.empty()?std::string{}:roles.front().id;} std::string commandsError(const V& args,unsigned limit,AgentTeamDiscipline discipline,unsigned maxFeatures=1,unsigned maxPlacements=1){auto commands=args.find("commands");if(!commands){if(discipline!=AgentTeamDiscipline::General)return "Scoped team writes need explicit bounded commands; a cached candidate cannot conceal its operations.";return {};} if(commands->t!=V::Arr||commands->arr.empty()||commands->arr.size()>limit)return "Construction step must contain 1.."+std::to_string(limit)+" commands. Keep dependent changes atomic; propose smaller independently valid steps rather than splitting them blindly."; unsigned features=0,placements=0;for(const auto& command:commands->arr){if(command.t!=V::Obj||field(command,"op").empty())return "Construction commands must be objects with an operation.";auto op=field(command,"op");if(op=="feature.add"||op=="sheet.create")++features;if(op=="assembly.add")++placements;if(!scopedCommand(discipline,op))return "Operation "+op+" belongs to a different team discipline. Send a revision-bound proposal to its owner.";} - if(discipline==AgentTeamDiscipline::ParametricDesigner&&std::none_of(commands->arr.begin(),commands->arr.end(),[](const V& command){return field(command,"op").rfind("program.",0)==0;}))return "A parametric designer publishes compiled program candidates only. Prepare one with parametric_program; send other edits to their owner."; + if(discipline==AgentTeamDiscipline::ParametricDesigner&&std::none_of(commands->arr.begin(),commands->arr.end(),[](const V& command){return field(command,"op").rfind("program.",0)==0||field(command,"op").rfind("variant.",0)==0;}))return "A parametric designer publishes compiled program candidates only. Prepare one with parametric_program; send other edits to their owner."; if(features>maxFeatures||placements>maxPlacements)return "Construction step exceeds the configured feature/placement limit. Keep related changes atomic and choose a smaller complete batch; no partial geometry was committed.";return {}; } void closeInterruptedCalls(V& conversation){ @@ -170,7 +170,7 @@ V teamTools(V tools,unsigned maxCommands){ for(const auto& item:tools.arr)require(field(item,"name").rfind("team_",0)!=0,"ARK tool names collide with team coordination tools."); // Host receipts and machine/history maintenance stay outside shared team turns; // this also keeps the full role catalog within the 128-function provider limit. - static const std::set hostOnly{"usage_record","compute_benchmark","history_compact","history_migrate_derived"}; + static const std::set hostOnly{"usage_record","compute_benchmark","history_compact","history_migrate_derived","memory_maintain","failure_export"}; tools.arr.erase(std::remove_if(tools.arr.begin(),tools.arr.end(),[](const V& item){return hostOnly.count(field(item,"name"))!=0;}),tools.arr.end()); V commandItems,checksSchema; for(const auto& tool:tools.arr)if(field(tool,"name")=="doc_apply"){ @@ -739,11 +739,12 @@ struct AgentTeam::Impl { else {executing=true;{std::lock_guard lock(mutex);outcomeProjectEpoch=preparedProjectEpoch;}if(constructing){step.kind=AgentTeamEvent::ConstructionStart;step.text="Executing atomic "+step.stepId+"; draft remains uncommitted";emit(step);}try{result=executor(actualName,actual);}catch(...){result=errorResult("Shared ARK executor failed. Inspect the document and revision before retrying; a running operation may have completed.");std::lock_guard lock(mutex);roles[index].view.needsInspection=true;}} if(!isError(result)&&name=="doc_info"){std::uint64_t observed;if(receiptRevision(payload(result),observed)){std::lock_guard lock(mutex);roles[index].view.needsInspection=false;roles[index].hasInspectedRevision=true;roles[index].inspectedRevision=observed;}} if(!isError(result)){std::lock_guard lock(mutex);const auto project=field(payload(result),"activity_project_id");const bool changed=!project.empty()&&!preparedProjectId.empty()&&project!=preparedProjectId;const bool boundary=explicitProjectBoundary(actualName,actual,result)||changed;if(boundary){clearPreparedLocked();documentRevisionKnown=false;}std::uint64_t observed=0;if(receiptRevision(payload(result),observed)&&(!documentRevisionKnown||observed>=documentRevision)){documentRevisionKnown=true;documentRevision=observed;}if(!project.empty())preparedProjectId=project;outcomeProjectEpoch=preparedProjectEpoch;} - const bool programPreview=name=="parametric_program"&&field(args,"action")=="prepare"; + const auto previewAction=field(args,"action"); + const bool programPreview=(name=="parametric_program"&&previewAction=="prepare")||(name=="design_variants"&&(previewAction=="prepare"||previewAction=="save"||previewAction=="remove"))||(name=="design_review"&&previewAction=="prepare_repair"); if(!isError(result)&&(name=="doc_preview"||name=="manufacturing_propose"||programPreview)&&roles[index].config.canWrite){const auto& proof=payload(result);const auto* valid=proof.find("valid");const auto* cached=proof.find("candidate_cached");const auto* recipe=proof.find("recipe");const auto candidate=field(proof,"candidate_id");std::uint64_t observed=0; bool receiptMatches=valid&&valid->t==V::Bool&&valid->b&&cached&&cached->t==V::Bool&&cached->b&&recipe&&recipe->t==V::Obj&&!candidate.empty()&&candidate.size()<=256&&receiptRevision(proof,observed)&&revision(actual)&&observed==(std::uint64_t)actual.find("expected_revision")->num&&(programPreview||samePreparedRecipe(*recipe,authorized)); - // The host compiled this role's own program; its recipe must still fit the role's step scope. - if(programPreview&&receiptMatches){const auto scope=commandsError(*recipe,config.maxCommandsPerStep,discipline,config.maxFeaturesPerStep,config.maxPlacementsPerStep);if(!scope.empty()){receiptMatches=false;result=errorResult("Program candidate is outside this role's team step scope: "+scope+" No candidate ownership was granted.");}} + // Host-generated candidates still require this role's ordinary command scope checks. + if(programPreview&&receiptMatches){const auto scope=commandsError(*recipe,config.maxCommandsPerStep,discipline,config.maxFeaturesPerStep,config.maxPlacementsPerStep);if(!scope.empty()){receiptMatches=false;result=errorResult("Prepared design candidate is outside this role's team step scope: "+scope+" No candidate ownership was granted.");}} if(refreshing){const auto* refresh=proof.find("refresh");bool sameProject;{std::lock_guard lock(mutex);sameProject=authorizedProjectEpoch==preparedProjectEpoch;}receiptMatches=receiptMatches&&sameProject&&candidate!=authorizedCandidate&&refresh&&refresh->t==V::Obj&&field(*refresh,"source_candidate_id")==authorizedCandidate;if(!receiptMatches)result=errorResult("Prepared refresh receipt did not attest this role's unchanged authorized recipe at the requested revision; no candidate ownership was granted.");} if(receiptMatches){ V retained=V::makeObj();retained.set("commands",*recipe->find("commands"));if(auto checks=recipe->find("checks"))retained.set("checks",*checks);const auto bytes=retained.dump().size(); diff --git a/src/assistant.cpp b/src/assistant.cpp index 558a509..4d541b8 100644 --- a/src/assistant.cpp +++ b/src/assistant.cpp @@ -436,7 +436,7 @@ const std::vector>>& assistantSpe {"frames",{"frame_inspect","stock_preview"}},{"tube",{"tube_inspect","notch_inspect","notch_plan","source_inspect","stock_preview"}}, {"electronics",{"electronics_inspect","pcb_export"}},{"routing",{"electronics_inspect","pcb_export"}}, {"mesh",{"mesh_inspect","mesh_get","import_mesh","export_mesh"}},{"drawings",{"drawing_inspect","drawing_export","schematic_inspect","schematic_export"}},{"schematics",{"schematic_inspect","schematic_export"}}, - {"skeleton",{"skeleton_inspect","skeleton_compile"}},{"automation",{"skeleton_inspect","skeleton_compile","design_solve"}},{"programs",{"parametric_program"}}, + {"skeleton",{"skeleton_inspect","skeleton_compile"}},{"automation",{"skeleton_inspect","skeleton_compile","design_solve"}},{"programs",{"parametric_program","design_variants"}},{"variants",{"parametric_program","design_variants"}},{"design_review",{"design_review"}}, {"planes",{"plane_authoring"}},{"sketch",{"sketch_repair"}},{"containers",{"design_containers"}},{"hud",{"hud_info","hud_flex_check"}}, {"cad_import",{"import_step","import_cad","step_inspect","cad_inspect","image_asset","export_step","export_iges","doc_new","doc_load"}}, {"history",{"feature_history","history_info","iteration_restore","history_migrate_derived","history_compact","failure_replay","failure_export","usage_info","usage_record","memory_maintain"}}}; diff --git a/src/assistant_steering.inl b/src/assistant_steering.inl index 731435b..0a55ec3 100644 --- a/src/assistant_steering.inl +++ b/src/assistant_steering.inl @@ -3,6 +3,8 @@ bool assistantToolReadOnly(const V& tools,const std::string& name,const V& args) if(name=="snapshot"&&args.t==V::Obj&&!args.find("path"))return true; if(name=="image_asset"&&field(args,"action")=="inspect")return true; if(name=="parametric_program"&&(field(args,"action")=="validate"||field(args,"action")=="examples"||field(args,"action")=="inspect"))return true; + if(name=="design_variants"&&(field(args,"action")=="inspect"||field(args,"action")=="evaluate"||field(args,"action")=="explore"))return true; + if(name=="design_review"&&(field(args,"action")=="compare"||field(args,"action")=="diagnose"))return true; if(name=="library_vendors"&&args.t==V::Obj&&(!args.find("operation")||field(args,"operation")=="list"))return true; for(const auto& tool:tools.arr)if(field(tool,"name")==name){ const auto* annotations=tool.find("annotations");const auto* hint=annotations?annotations->find("readOnlyHint"):nullptr; diff --git a/src/design_review.cpp b/src/design_review.cpp new file mode 100644 index 0000000..c5c4f55 --- /dev/null +++ b/src/design_review.cpp @@ -0,0 +1,62 @@ +#include "ark/design_review.hpp" +#include "ark/iteration_history.hpp" +#include "ark/bom.hpp" +#include +#include +#include +#include +#include +namespace ark { namespace { +using V=arkjson::Value; +const V& field(const V& v,const char* k){static V nil;auto* p=v.find(k);return p?*p:nil;} +std::string text(const V& v,const char* k){return field(v,k).asStr();} +V number(u64 n){return V::makeNum(static_cast(n));} +void canonical(V& value){if(value.t==V::Obj){for(auto& kv:value.obj)canonical(kv.second);std::sort(value.obj.begin(),value.obj.end(),[](const auto& a,const auto& b){return a.first& values){V a=V::makeArr();for(const auto& s:values)a.arr.push_back(V::makeStr(s));return a;} +V featureSource(const Feature& f){V row=V::makeObj(),p=V::makeObj(),inputs=V::makeArr();std::map sorted(f.p.begin(),f.p.end());for(const auto& kv:sorted)p.set(kv.first,V::makeStr(kv.second));for(auto id:f.inputs)inputs.arr.push_back(number(id));row.set("name",V::makeStr(f.name));row.set("type",V::makeStr(featureTypeName(f.type)));row.set("parameters",p);row.set("inputs",inputs);row.set("native",f.nativeSpec);row.set("part",f.part);row.set("material",V::makeStr(f.material));row.set("suppressed",V::makeBool(f.suppressed));row.set("source",f.sourceData);row.set("appearance",f.appearance);row.set("classification",f.classification);row.set("manufacturing_route",V::makeStr(f.manufacturingRoute));row.set("manufacturing_process",f.manufacturingProcess);canonical(row);return row;} +std::string sourceHash(const Document& d){return iterationSha256(iterationAuthoring(d).dump());} +V delta(const V& a,const V& b){V out=V::makeArr();std::set keys;for(const auto& kv:a.obj)keys.insert(kv.first);for(const auto& kv:b.obj)keys.insert(kv.first);for(const auto& key:keys)if(canonicalText(field(a,key.c_str()))!=canonicalText(field(b,key.c_str()))){V row=V::makeObj();row.set("field",V::makeStr(key));row.set("before",field(a,key.c_str()));row.set("after",field(b,key.c_str()));out.arr.push_back(row);}return out;} +V parameters(const Document& d){V out=V::makeObj();for(const auto& p:d.params)out.set(p.name,V::makeStr(p.expr));return out;} +V bodyInfo(const Document& d,u64 id){V out=V::makeObj();for(const auto& b:d.evalBodies)if(b.id==id){const auto* topology=b.nativeData.find("topology");const auto* hash=topology?topology->find("brep_sha256"):nullptr;if(const auto* report=b.nativeData.find("report")){for(const char* key:{"bounds_mm","volume_mm3"})if(const auto* value=report->find(key))out.set(key,*value);}if(hash){out.set("geometry_sha256",*hash);out.set("geometry_authority",V::makeStr("native_brep"));}else{auto mesh=b.tessellate(d.tessOpt);std::string bytes(reinterpret_cast(mesh.pos.data()),mesh.pos.size()*sizeof(float));bytes.append(reinterpret_cast(mesh.idx.data()),mesh.idx.size()*sizeof(u32));out.set("geometry_sha256",V::makeStr(iterationSha256(bytes)));out.set("geometry_authority",V::makeStr("display_mesh_only"));}break;}for(const auto& r:d.lastResults)if(r.id==id){out.set("ok",V::makeBool(r.ok));if(!r.ok)out.set("error",V::makeStr(r.error));}return out;} +V bomRows(const Document& d,u64 revision){try{return inspectBom(d,revision);}catch(const std::exception& e){V o=V::makeObj();o.set("unavailable",V::makeStr(e.what()));return o;}} +V indexedBom(const V& bom){V out=V::makeObj();for(const auto& row:field(bom,"items").arr)out.set(std::to_string((u64)field(row,"feature").num),row);return out;} +V placements(const Document& d){V out=V::makeObj();if(d.assembly.empty())return out;std::vector places;std::string error;if(!resolveAssembly(d,places,error)){out.set("error",V::makeStr(error));return out;}for(const auto& p:places){V rows=field(out,std::to_string(p.feature).c_str());if(rows.t!=V::Obj)rows=V::makeObj();V row=V::makeObj(),matrix=V::makeArr();for(double x:p.world.m)matrix.arr.push_back(V::makeNum(x));row.set("transform",matrix);row.set("visible",V::makeBool(p.visible));row.set("name",V::makeStr(p.name));rows.set(std::to_string(p.node)+":"+std::to_string(p.copy),row);out.set(std::to_string(p.feature),rows);}return out;} +void guardRevision(const AgentSession& s,const V& args){const auto& r=field(args,"expected_revision");if(r.t!=V::Num||r.num<0||std::floor(r.num)!=r.num||r.num!=static_cast(s.revision))throw std::runtime_error("Design review requires current expected_revision; inspect again after edits");} +void rejectToleranceChanges(const V& before,const V& after,bool complete=false){if(complete){for(const auto& kv:before.obj)if(!after.find(kv.first.c_str())){auto key=kv.first;std::transform(key.begin(),key.end(),key.begin(),[](unsigned char c){return (char)std::tolower(c);});if(key.find("tolerance")!=std::string::npos||key.find("fuzzy")!=std::string::npos||key=="tol"||(key.size()>4&&key.substr(key.size()-4)=="_tol"))throw std::runtime_error("Repair cannot remove explicit kernel tolerances");if(kv.second.t==V::Obj)rejectToleranceChanges(kv.second,V(),true);}}for(const auto& kv:after.obj){auto name=kv.first;std::transform(name.begin(),name.end(),name.begin(),[](unsigned char c){return (char)std::tolower(c);});const auto& prior=field(before,kv.first.c_str());if((name.find("tolerance")!=std::string::npos||name.find("fuzzy")!=std::string::npos||name=="tol"||(name.size()>4&&name.substr(name.size()-4)=="_tol"))&&prior.dump()!=kv.second.dump())throw std::runtime_error("Repair cannot change kernel tolerances; correct geometry or references explicitly");if(complete&&prior.t==V::Obj&&kv.second.t!=V::Obj)rejectToleranceChanges(prior,V(),true);if(kv.second.t==V::Obj)rejectToleranceChanges(prior,kv.second,complete);else if(kv.second.t==V::Arr)for(size_t i=0;i=1&&target.num<=9007199254740991.&&std::floor(target.num)==target.num)feature=(u64)target.num;else if(target.t==V::Str)for(const auto& f:session.document.features)if(f.name==target.str){if(feature)throw std::runtime_error("Ambiguous failed feature name");feature=f.id;} + if(!feature||!session.document.find(feature))throw std::runtime_error("The rejected feature no longer exists");return record; +} +void appendRejectedEdits(AgentSession& session,V& diagnostics){ + V failures=field(diagnostics,"failures");const auto inventory=session.failureInfo(V::makeObj());diagnostics.set("rejected_operations",field(inventory,"records")); + for(const auto& entry:field(inventory,"records").arr){u64 id=0;V record;try{record=rejectedEdit(session,text(entry,"id"),id);}catch(const std::exception&){continue;}const auto* f=session.document.find(id);V row=featureSource(*f);row.set("id",number(id));row.set("failure_id",field(record,"id"));row.set("diagnostic_origin",V::makeStr("rejected_edit; current geometry remains unchanged"));const auto& command=field(field(record,"replay_request"),"commands").arr[0];row.set("attempted_command",command);V p=field(row,"parameters");for(const auto& kv:field(command,"p").obj)p.set(kv.first,kv.second.t==V::Str?kv.second:V::makeStr(kv.second.dump()));row.set("parameters",p);for(const char* key:{"native","inputs"})if(const auto* value=command.find(key))row.set(key,*value);const auto error=field(record,"error");row.set("error",V::makeStr(field(error,"error").t==V::Str?text(error,"error"):error.dump()));V earlier=V::makeArr(),dependents=V::makeArr();for(const auto& candidate:session.document.features){if(candidate.id==id)break;V item=V::makeObj();item.set("id",number(candidate.id));item.set("name",V::makeStr(candidate.name));earlier.arr.push_back(item);}for(const auto& child:session.document.features)if(std::find(child.inputs.begin(),child.inputs.end(),id)!=child.inputs.end())dependents.arr.push_back(number(child.id));row.set("earlier_dependencies",earlier);row.set("dependents",dependents);row.set("guidance",V::makeStr("Correct the retained rejected edit. The current valid design is preserved until a reviewed candidate is applied."));failures.arr.push_back(row);} + diagnostics.set("failures",failures); +} +} +arkjson::Value compareDesignRevisions(const Document& source,u64 revision,const std::string& beforeId,const std::string& afterId){ + if(beforeId.empty())throw std::runtime_error("Choose a retained before_id from history_info"); + Document before,after;iterationRestore(source,beforeId,before);if(afterId=="current")after=source.authoringCopy();else iterationRestore(source,afterId,after); + before.recompute();after.recompute();const auto beforePlaces=placements(before),afterPlaces=placements(after);V out=V::makeObj(),rows=V::makeArr();std::set ids;for(const auto& f:before.features)ids.insert(f.id);for(const auto& f:after.features)ids.insert(f.id);size_t added=0,removed=0,changed=0,unchanged=0; + for(auto id:ids){auto* a=before.find(id);auto* b=after.find(id);V av=a?featureSource(*a):V(),bv=b?featureSource(*b):V();V ag=a?bodyInfo(before,id):V(),bg=b?bodyInfo(after,id):V();const bool geometry=text(ag,"geometry_sha256")!=text(bg,"geometry_sha256")||field(ag,"ok").dump()!=field(bg,"ok").dump();const auto occurrenceChanges=delta(field(beforePlaces,std::to_string(id).c_str()),field(afterPlaces,std::to_string(id).c_str()));std::string status=!a?"added":!b?"removed":av.dump()!=bv.dump()||geometry||!occurrenceChanges.arr.empty()?"changed":"unchanged";if(status=="added")++added;else if(status=="removed")++removed;else if(status=="changed")++changed;else ++unchanged;V row=V::makeObj();row.set("id",number(id));row.set("name",V::makeStr(b?b->name:a->name));row.set("status",V::makeStr(status));row.set("geometry_changed",V::makeBool(geometry));row.set("changes",delta(av,bv));row.set("occurrence_changes",occurrenceChanges);row.set("geometry_metrics_changes",delta(ag,bg));row.set("parameter_changes",delta(field(av,"parameters"),field(bv,"parameters")));row.set("before_geometry",ag);row.set("after_geometry",bg);rows.arr.push_back(row);} + const auto ba=iterationAuthoring(before),aa=iterationAuthoring(after);out.set("format",V::makeStr("ark.design-review.v1"));out.set("revision",number(revision));out.set("before_id",V::makeStr(beforeId));out.set("after_id",V::makeStr(afterId));out.set("source_sha256",V::makeStr(sourceHash(source)));out.set("hash_scope",V::makeStr("reconstructed authoring; retained identifiers use current allocator high-water marks"));out.set("before_sha256",V::makeStr(sourceHash(before)));out.set("after_sha256",V::makeStr(sourceHash(after)));out.set("features",rows);out.set("added",number(added));out.set("removed",number(removed));out.set("changed",number(changed));out.set("unchanged",number(unchanged));out.set("parameter_changes",delta(parameters(before),parameters(after)));out.set("placement_comparison_available",V::makeBool(!beforePlaces.find("error")&&!afterPlaces.find("error")));if(beforePlaces.find("error"))out.set("before_placement_error",field(beforePlaces,"error"));if(afterPlaces.find("error"))out.set("after_placement_error",field(afterPlaces,"error"));out.set("assembly_changed",V::makeBool(field(ba,"assembly").dump()!=field(aa,"assembly").dump()));out.set("assembly_before",field(ba,"assembly"));out.set("assembly_after",field(aa,"assembly"));const auto beforeBom=bomRows(before,revision),afterBom=bomRows(after,revision);out.set("bom_before",beforeBom);out.set("bom_after",afterBom);out.set("bom_changes",delta(indexedBom(beforeBom),indexedBom(afterBom)));out.set("display_only",V::makeBool(true));return out; +} +arkjson::Value diagnoseDesignFeatures(const Document& source,u64 revision){ + Document evaluated=source.authoringCopy();evaluated.recompute();V out=V::makeObj(),rows=V::makeArr();for(const auto& f:evaluated.features){const FeatureResult* result=nullptr;for(const auto& r:evaluated.lastResults)if(r.id==f.id)result=&r;V missing=V::makeArr(),earlier=V::makeArr(),dependents=V::makeArr();for(auto id:f.inputs)if(!evaluated.find(id))missing.arr.push_back(number(id));for(const auto& candidate:evaluated.features){if(candidate.id==f.id)break;V item=V::makeObj();item.set("id",number(candidate.id));item.set("name",V::makeStr(candidate.name));earlier.arr.push_back(item);}for(const auto& child:evaluated.features)if(std::find(child.inputs.begin(),child.inputs.end(),f.id)!=child.inputs.end())dependents.arr.push_back(number(child.id));if((!result||result->ok)&&missing.arr.empty())continue;V row=featureSource(f);row.set("id",number(f.id));row.set("error",V::makeStr(result?result->error:"Missing dependency"));row.set("missing_inputs",missing);row.set("earlier_dependencies",earlier);row.set("dependents",dependents);row.set("guidance",V::makeStr("Inspect the reported error. Correct explicit parameter expressions, native references or earlier inputs, then prepare_repair. No deletion, suppression or automatic tolerance change is proposed."));rows.arr.push_back(row);} + out.set("format",V::makeStr("ark.design-diagnostics.v1"));out.set("revision",number(revision));out.set("source_sha256",V::makeStr(sourceHash(source)));out.set("failures",rows);return out; +} +bool callDesignReviewTool(AgentSession& session,const std::string& tool,const V& args,V& result){ + if(tool!="design_review")return false;guardRevision(session,args);for(const auto& kv:args.obj)if(kv.first!="action"&&kv.first!="expected_revision"&&kv.first!="before_id"&&kv.first!="after_id"&&kv.first!="source_sha256"&&kv.first!="id"&&kv.first!="failure_id"&&kv.first!="command")throw std::runtime_error("Unknown design_review field: "+kv.first);const auto action=text(args,"action"); + if(action=="compare")result=compareDesignRevisions(session.document,session.revision,text(args,"before_id"),args.find("after_id")?text(args,"after_id"):"current"); + else if(action=="diagnose"){result=diagnoseDesignFeatures(session.document,session.revision);appendRejectedEdits(session,result);} + else if(action=="prepare_repair"){ + if(text(args,"source_sha256")!=sourceHash(session.document))throw std::runtime_error("Repair source fingerprint changed; diagnose again");const auto& idValue=field(args,"id");if(idValue.t!=V::Num||idValue.num<1||idValue.num>9007199254740991.||std::floor(idValue.num)!=idValue.num)throw std::runtime_error("Repair requires numeric feature id");const auto id=static_cast(idValue.num);auto diagnostics=diagnoseDesignFeatures(session.document,session.revision);bool found=false;if(args.find("failure_id")){u64 rejectedId=0;rejectedEdit(session,text(args,"failure_id"),rejectedId);if(rejectedId!=id)throw std::runtime_error("Repair target differs from the retained rejected edit");found=true;}for(const auto& r:field(diagnostics,"failures").arr)if(field(r,"id").num==idValue.num)found=true;if(!found)throw std::runtime_error("Selected feature is not failing and no current retained failure_id was supplied; use ordinary authoring for a normal edit"); + V command=field(args,"command");if(command.t!=V::Obj||text(command,"op")!="feature.edit"||field(command,"id").t!=V::Num||field(command,"id").num!=idValue.num)throw std::runtime_error("Repair command must edit exactly the inspected feature");for(const auto& kv:command.obj)if(kv.first!="op"&&kv.first!="id"&&kv.first!="p"&&kv.first!="native"&&kv.first!="inputs")throw std::runtime_error("Repair accepts explicit p, native or inputs only; deletion and suppression are not repairs");const auto* sourceFeature=session.document.find(id);rejectToleranceChanges(field(featureSource(*sourceFeature),"parameters"),field(command,"p"));if(command.find("native"))rejectToleranceChanges(sourceFeature->nativeSpec,field(command,"native"),true);if(command.obj.size()<3)throw std::runtime_error("Repair contains no correction");V preview=V::makeObj(),commands=V::makeArr();commands.arr.push_back(command);preview.set("expected_revision",number(session.revision));preview.set("commands",commands);preview.set("detail",V::makeStr("changes"));auto response=session.call("doc_preview",preview);if(field(response,"isError").b)throw std::runtime_error(response.dump());result=field(response,"structuredContent");if(!field(result,"valid").b||!field(result,"candidate_cached").b||text(result,"candidate_id").empty())throw std::runtime_error("Repair rejected by full-document validation: "+result.dump());result.set("repair_feature",number(id));result.set("source_sha256",field(diagnostics,"source_sha256")); + }else throw std::runtime_error("Unknown design_review action");return true; +} +void appendDesignReviewTools(V& tools){V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("design_review"));tool.set("description",V::makeStr("Compare retained history revisions without restoring; diagnose failed features and explicitly preview parameter/reference/input repairs. All actions require current expected_revision. prepare_repair requires diagnose source_sha256 and one feature.edit command; rejected edits also require their current failure_id; publish the reviewed preview through doc_apply. No deletion, suppression, relaxed tolerances or automatic substitutions."));arkjson::parse(R"JSON({"type":"object","properties":{"action":{"type":"string","enum":["compare","diagnose","prepare_repair"]},"expected_revision":{"type":"integer","minimum":0},"before_id":{"type":"string"},"after_id":{"type":"string"},"source_sha256":{"type":"string"},"failure_id":{"type":"string"},"id":{"type":"integer","minimum":1},"command":{"type":"object"}},"required":["action","expected_revision"],"additionalProperties":false})JSON",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(false));tool.set("annotations",annotations);tools.arr.push_back(tool);} +} diff --git a/src/design_variants.cpp b/src/design_variants.cpp new file mode 100644 index 0000000..c0705c6 --- /dev/null +++ b/src/design_variants.cpp @@ -0,0 +1,71 @@ +#include "ark/design_variants.hpp" +#include "ark/parametric_programs.hpp" +#include +#include +#include +#include +#include +#include + +namespace ark { namespace { +using V=arkjson::Value; +const V& get(const V& v,const char* key){static const V empty;const auto* p=v.find(key);return p?*p:empty;} +[[noreturn]] void fail(const std::string& s){throw std::runtime_error("VARIANT: "+s);} +void only(const V& v,std::initializer_list keys){if(v.t!=V::Obj)fail("Expected an object");for(const auto& kv:v.obj){bool found=false;for(const auto* k:keys)found|=kv.first==k;if(!found)fail("Unknown field "+kv.first);}} +std::string text(const V& v,const char* key,size_t limit=128){const auto& x=get(v,key);if(x.t!=V::Str||x.str.empty()||x.str.size()>limit||x.str.find_first_of("\r\n\t")!=std::string::npos)fail(std::string(key)+" must be nonempty text");return x.str;} +void expected(AgentSession& s,const V& a){const auto& r=get(a,"expected_revision");if(r.t!=V::Num||r.num!=double(s.revision))fail("expected_revision must match the observed current revision");} +const V& binding(const Document& d,const std::string& ns){for(const auto& e:d.parametricPrograms.arr)if(get(e,"namespace").asStr()==ns)return e;fail("Install a parametric program in namespace "+ns+" first");} +const V& saved(const Document& d,const std::string& ns,const std::string& name){for(const auto& v:d.designVariants.arr)if(get(v,"namespace").asStr()==ns&&get(v,"name").asStr()==name)return v;fail("Saved variant not found: "+name);} +V data(const V& response){if(get(response,"isError").b){const auto& details=get(response,"structuredContent");const auto& error=get(details,"error");fail(error.t==V::Str?error.str:details.dump());}return get(response,"structuredContent");} +V config(AgentSession& s,const std::string& ns,const V& values){V a=V::makeObj();a.set("action",V::makeStr("prepare"));a.set("mode",V::makeStr("configure"));a.set("namespace",V::makeStr(ns));a.set("values",values);a.set("expected_revision",V::makeNum(double(s.revision)));return data(s.call("parametric_program",a));} +void publish(AgentSession& s,const V& preview){V a=V::makeObj();a.set("candidate_id",get(preview,"candidate_id"));a.set("expected_revision",V::makeNum(double(s.revision)));data(s.call("doc_apply",a));} +V chosenValues(const Document& d,const V& a,const std::string& ns){if(a.find("name")&&!a.find("values")){const auto& v=saved(d,ns,text(a,"name"));if(get(v,"program_sha256").str!=get(binding(d,ns),"program_sha256").str)fail("Saved variant belongs to a different program revision; review and save new values explicitly");return get(v,"values");}if(a.find("values")){if(get(a,"values").t!=V::Obj)fail("values must be an object");return get(a,"values");}return get(binding(d,ns),"values");} +V mergedValues(const V& entry,const V& overrides){V values=get(entry,"values");for(const auto& p:overrides.obj)values.set(p.first,p.second);return get(compileParametricProgram(get(entry,"program"),values,get(entry,"namespace").str),"values");} +V previewCommand(AgentSession& s,V c){V a=V::makeObj(),commands=V::makeArr();commands.arr.push_back(std::move(c));a.set("commands",std::move(commands));a.set("expected_revision",V::makeNum(double(s.revision)));return data(s.call("doc_preview",a));} +// Only terminal definitions owned by this program are counted. Assembly copies +// and overlapping-part union volume are deliberately not inferred. +V evaluate(AgentSession& source,const std::string& ns,const V& values,const std::string& name,bool thumbnail,const V& clearancePairs=V{}){ + V row=V::makeObj();row.set("name",V::makeStr(name));row.set("values",values);row.set("valid",V::makeBool(false)); + try{ + auto scratch=std::make_unique();scratch->document=source.document;scratch->revision=source.revision;scratch->suppressIterationHistory();scratch->suppressFailureCapture(); + const auto prepared=config(*scratch,ns,values);publish(*scratch,prepared);const auto& entry=binding(scratch->document,ns);row.set("values",get(entry,"values")); + std::set names;for(const auto& n:get(get(entry,"owned"),"features").arr)names.insert(n.str);std::set consumed; + for(const auto& f:scratch->document.features)if(names.count(f.name))for(size_t i=0;idocument.features){if(!names.count(f.name)||consumed.count(f.id)||f.suppressed)continue; + V a=V::makeObj();a.set("id",V::makeNum(double(f.id)));a.set("detail",V::makeStr("properties"));const V inspected=data(scratch->call("native_inspect",a));const auto& report=get(inspected,"report"); + if(!get(report,"brep_valid").b||get(report,"volume_mm3").t!=V::Num||get(report,"volume_mm3").num<=0||get(report,"bounds_mm").arr.size()!=6)fail("Terminal feature "+f.name+" is not a validated exact solid"); + volume+=get(report,"volume_mm3").num;const bool hasMass=get(inspected,"mass_checked").b&&get(inspected,"mass_kg").t==V::Num;allMass&=hasMass;if(hasMass)mass+=get(inspected,"mass_kg").num; + for(int i=0;i<3;++i){bounds[i]=std::min(bounds[i],get(report,"bounds_mm").arr[i].num);bounds[i+3]=std::max(bounds[i+3],get(report,"bounds_mm").arr[i+3].num);}++solids; + V part=V::makeObj();part.set("name",V::makeStr(f.name));part.set("volume_mm3",get(report,"volume_mm3"));parts.arr.push_back(part); + if(thumbnail&&triangles.arr.size()<1024)for(const auto& body:scratch->document.evalBodies)if(body.id==f.id&&body.baked){const auto& mesh=*body.baked;const size_t stride=std::max(1,mesh.triCount()/128);for(size_t t=0;t=mesh.vertCount())fail("Invalid display mesh index");for(int k=0;k<3;++k)tri.arr.push_back(V::makeNum(mesh.pos[vertex*3+k]));}triangles.arr.push_back(tri);}} + } + if(!solids)fail("Program has no terminal exact solid definitions");V metrics=V::makeObj(),box=V::makeArr();for(double b:bounds)box.arr.push_back(V::makeNum(b));metrics.set("volume_mm3",V::makeNum(volume));metrics.set("bounds_mm",box);metrics.set("width_mm",V::makeNum(bounds[3]-bounds[0]));metrics.set("depth_mm",V::makeNum(bounds[4]-bounds[1]));metrics.set("height_mm",V::makeNum(bounds[5]-bounds[2]));metrics.set("solid_definitions",V::makeNum(double(solids)));metrics.set("mass_available",V::makeBool(allMass));if(allMass)metrics.set("mass_kg",V::makeNum(mass)); + V gaps=V::makeArr();for(const auto& pair:clearancePairs.arr){const auto nameA=text(pair,"a"),nameB=text(pair,"b");const std::string aName=names.count(nameA)?nameA:ns+" / "+nameA,bName=names.count(nameB)?nameB:ns+" / "+nameB;if(!names.count(aName)||!names.count(bName)||aName==bName)fail("Clearance pairs must name two distinct features owned by this program");V query=V::makeObj();query.set("a",V::makeStr(aName));query.set("b",V::makeStr(bName));query.set("mode",V::makeStr("exact"));query.set("expected_revision",V::makeNum(double(scratch->revision)));const auto measured=data(scratch->call("collision_inspect",query));if(get(measured,"min_distance_mm").t!=V::Num||get(measured,"common_volume_mm3").t!=V::Num)fail("Exact pair clearance unavailable");V gap=V::makeObj();gap.set("a",V::makeStr(aName));gap.set("b",V::makeStr(bName));gap.set("minimum_mm",get(pair,"min_mm"));gap.set("distance_mm",get(measured,"min_distance_mm"));gap.set("overlap_volume_mm3",get(measured,"common_volume_mm3"));gap.set("passed",V::makeBool(!get(measured,"interference").b&&get(measured,"min_distance_mm").num>=get(pair,"min_mm").num));gaps.arr.push_back(gap);}row.set("clearance_checks",gaps); + row.set("metrics",metrics);row.set("parts",parts);row.set("valid",V::makeBool(true));row.set("geometry_authority",V::makeStr("native_brep"));if(thumbnail){row.set("display_triangles",triangles);row.set("thumbnail_authority",V::makeStr("display_only_sampled_mesh"));} + }catch(const std::exception& e){row.set("error",V::makeStr(e.what()));}return row; +} +const std::set metricNames{"volume_mm3","mass_kg","width_mm","depth_mm","height_mm","solid_definitions"}; +bool feasible(V& row,const V& constraints){V violations=V::makeArr();if(!get(row,"valid").b){row.set("feasible",V::makeBool(false));return false;}for(const auto& c:constraints.obj){const auto& measured=get(get(row,"metrics"),c.first.c_str());bool ok=measured.t==V::Num;if(c.second.find("min"))ok&=measured.num>=get(c.second,"min").num;if(c.second.find("max"))ok&=measured.num<=get(c.second,"max").num;if(!ok)violations.arr.push_back(V::makeStr(c.first+": required range not met or measurement unavailable"));}for(const auto& gap:get(row,"clearance_checks").arr)if(!get(gap,"passed").b)violations.arr.push_back(V::makeStr("Clearance requirement not met: "+get(gap,"a").str+" / "+get(gap,"b").str));row.set("violations",violations);row.set("feasible",V::makeBool(violations.arr.empty()));return violations.arr.empty();} +} +void validateDesignVariants(const V& rows){if(rows.isNull())return;if(rows.t!=V::Arr||rows.arr.size()>128)fail("Saved variants must be an array with at most 128 entries");std::set keys;for(const auto& v:rows.arr){only(v,{"name","namespace","program_sha256","values"});const auto ns=text(v,"namespace",32),name=text(v,"name");if(!keys.insert(ns+"\n"+name).second)fail("Duplicate variant name in namespace");const auto hash=text(v,"program_sha256",64);if(hash.size()!=64||hash.find_first_not_of("0123456789abcdef")!=std::string::npos)fail("Invalid program digest");const auto& values=get(v,"values");if(values.t!=V::Obj||values.obj.size()>64)fail("Invalid variant values");for(const auto& p:values.obj)if(p.first.empty()||p.second.t!=V::Num||!std::isfinite(p.second.num))fail("Variant parameters must be finite numbers");}} +bool applyDesignVariantCommand(Document& d,const V& c){const auto op=get(c,"op").asStr();if(op!="variant.set"&&op!="variant.remove")return false;if(d.historyTip||!d.designContainerCheckout.isNull())fail("Variants require the full owning document");only(c,{"op","namespace","name","values","program_sha256"});const auto ns=text(c,"namespace",32),name=text(c,"name");V rows=d.designVariants.isNull()?V::makeArr():d.designVariants;auto it=std::find_if(rows.arr.begin(),rows.arr.end(),[&](const V& v){return get(v,"namespace").str==ns&&get(v,"name").str==name;});if(op=="variant.remove"){if(it==rows.arr.end())fail("Variant not found");rows.arr.erase(it);}else{const auto& entry=binding(d,ns);if(get(c,"program_sha256").str!=get(entry,"program_sha256").str)fail("Program revision changed");V row=V::makeObj();row.set("name",V::makeStr(name));row.set("namespace",V::makeStr(ns));row.set("program_sha256",get(entry,"program_sha256"));row.set("values",mergedValues(entry,get(c,"values")));if(it==rows.arr.end())rows.arr.push_back(row);else *it=row;}validateDesignVariants(rows);d.designVariants=rows.arr.empty()?V{}:rows;return true;} +bool callDesignVariantsTool(AgentSession& s,const std::string& tool,const V& a,V& out){if(tool!="design_variants")return false;only(a,{"action","namespace","name","values","variants","axes","constraints","clearance_pairs","objective","direction","thumbnails","expected_revision"});const auto action=text(a,"action"); + if(action=="inspect"){if(a.find("expected_revision"))expected(s,a);if(a.find("namespace"))text(a,"namespace",32);out=V::makeObj();out.set("revision",V::makeNum(double(s.revision)));V rows=V::makeArr();for(auto row:s.document.designVariants.arr){if(a.find("namespace")&&get(row,"namespace").str!=text(a,"namespace",32))continue;bool current=false;for(const auto& e:s.document.parametricPrograms.arr)if(get(e,"namespace").str==get(row,"namespace").str)current=get(e,"program_sha256").str==get(row,"program_sha256").str;row.set("program_current",V::makeBool(current));rows.arr.push_back(row);}out.set("variants",rows);return true;} + expected(s,a);const auto ns=text(a,"namespace",32); + if(action=="remove"){if(a.find("values"))fail("remove selects a saved name and does not accept values");V c=V::makeObj();c.set("op",V::makeStr("variant.remove"));c.set("namespace",V::makeStr(ns));c.set("name",V::makeStr(text(a,"name")));out=previewCommand(s,c);out.set("publication",V::makeStr("doc_apply candidate_id + expected_revision"));return true;} + const auto& entry=binding(s.document,ns); + if(action=="prepare"){if(a.find("name")&&a.find("values"))fail("prepare accepts either a saved name or explicit values, not both");out=config(s,ns,chosenValues(s.document,a,ns));return true;} + if(action=="save"||action=="remove"){V c=V::makeObj();c.set("op",V::makeStr(action=="save"?"variant.set":"variant.remove"));c.set("namespace",V::makeStr(ns));c.set("name",V::makeStr(text(a,"name")));if(action=="save"){const auto values=a.find("values")?get(a,"values"):get(entry,"values");auto checked=evaluate(s,ns,values,text(a,"name"),false);if(!get(checked,"valid").b)fail(get(checked,"error").str);c.set("values",get(checked,"values"));c.set("program_sha256",get(entry,"program_sha256"));}out=previewCommand(s,c);out.set("publication",V::makeStr("doc_apply candidate_id + expected_revision"));return true;} + if(action!="evaluate"&&action!="explore")fail("Use inspect, save, remove, evaluate, explore or prepare"); + const auto& clearancePairs=get(a,"clearance_pairs");if(!clearancePairs.isNull()){if(clearancePairs.t!=V::Arr||clearancePairs.arr.size()>16)fail("clearance_pairs must contain at most 16 explicit pairs");for(const auto& pair:clearancePairs.arr){only(pair,{"a","b","min_mm"});text(pair,"a");text(pair,"b");if(get(pair,"min_mm").t!=V::Num||!std::isfinite(get(pair,"min_mm").num)||get(pair,"min_mm").num<0)fail("Pair minimum clearance must be a finite nonnegative millimetre distance");}} + const auto& constraints=get(a,"constraints");if(!constraints.isNull()){if(constraints.t!=V::Obj)fail("constraints must map exact metric names to min/max");for(const auto& p:constraints.obj){if(!metricNames.count(p.first))fail("Unsupported constraint metric "+p.first);only(p.second,{"min","max"});if(p.second.obj.empty())fail("Constraint needs min or max");for(const auto& bound:p.second.obj)if(bound.second.t!=V::Num||!std::isfinite(bound.second.num))fail("Constraint limits must be finite");if(p.second.find("min")&&p.second.find("max")&&get(p.second,"min").num>get(p.second,"max").num)fail("Constraint minimum exceeds maximum");}} + const std::string objective=a.find("objective")?text(a,"objective"):"volume_mm3",direction=a.find("direction")?text(a,"direction"):"min";if(!metricNames.count(objective)||(direction!="min"&&direction!="max"))fail("Choose a supported metric and min/max direction"); + V inputs=V::makeArr();if(action=="evaluate"){if(a.find("variants")){inputs=get(a,"variants");if(inputs.t!=V::Arr)fail("variants must be an array");}else if(a.find("values")||a.find("name")){V item=V::makeObj();item.set("name",V::makeStr(a.find("name")?text(a,"name"):"Current"));item.set("values",chosenValues(s.document,a,ns));inputs.arr.push_back(item);}else for(const auto& v:s.document.designVariants.arr)if(get(v,"namespace").str==ns){V item=V::makeObj();item.set("name",get(v,"name"));if(get(v,"program_sha256").str==get(entry,"program_sha256").str)item.set("values",get(v,"values"));else item.set("stale",V::makeBool(true));inputs.arr.push_back(item);}} + else{const auto& axes=get(a,"axes");if(axes.t!=V::Obj||axes.obj.empty()||axes.obj.size()>4)fail("explore needs 1..4 parameter axes with explicit numeric values");size_t total=1;for(const auto& axis:axes.obj){if(!get(get(entry,"program"),"parameters").find(axis.first.c_str()))fail("Unknown parameter axis "+axis.first);if(axis.second.t!=V::Arr||axis.second.arr.empty()||axis.second.arr.size()>64)fail("Each axis needs 1..64 numeric values");for(const auto& x:axis.second.arr)if(x.t!=V::Num||!std::isfinite(x.num))fail("Axis values must be finite numbers");total*=axis.second.arr.size();if(total>64)fail("Exploration supports at most 64 explicitly enumerated combinations");}V base=a.find("values")?get(a,"values"):get(entry,"values");if(base.t!=V::Obj)fail("values must be an object");std::function expand=[&](size_t i,V values){if(i==axes.obj.size()){V item=V::makeObj();item.set("name",V::makeStr("Trial "+std::to_string(inputs.arr.size()+1)));item.set("values",values);inputs.arr.push_back(item);return;}for(const auto& x:axes.obj[i].second.arr){V next=values;next.set(axes.obj[i].first,x);expand(i+1,next);}};expand(0,base);} + if(inputs.arr.empty()||inputs.arr.size()>64)fail("Choose between 1 and 64 variants");V rows=V::makeArr(),ranked=V::makeArr();std::vector order;size_t failures=0;for(const auto& input:inputs.arr){only(input,{"name","values","stale"});const auto name=text(input,"name");V row;if(get(input,"stale").b){row=input;row.set("valid",V::makeBool(false));row.set("error",V::makeStr("Saved program revision is stale"));}else row=evaluate(s,ns,get(input,"values"),name,get(a,"thumbnails").b,clearancePairs);if(!get(row,"valid").b)++failures;if(feasible(row,constraints)&&get(get(row,"metrics"),objective.c_str()).t==V::Num)order.push_back(rows.arr.size());rows.arr.push_back(row);} + std::stable_sort(order.begin(),order.end(),[&](size_t x,size_t y){const double ax=get(get(rows.arr[x],"metrics"),objective.c_str()).num,ay=get(get(rows.arr[y],"metrics"),objective.c_str()).num;return direction=="min"?axay;});for(size_t i:order)ranked.arr.push_back(V::makeNum(double(i))); + out=V::makeObj();out.set("revision",V::makeNum(double(s.revision)));out.set("namespace",V::makeStr(ns));out.set("program_sha256",get(entry,"program_sha256"));out.set("results",rows);out.set("ranked_indices",ranked);out.set("attempted",V::makeNum(double(rows.arr.size())));out.set("failed",V::makeNum(double(failures)));out.set("objective",V::makeStr(objective));out.set("direction",V::makeStr(direction));out.set("scope",V::makeStr("Exact program terminal part definitions; summed part volumes, not union volume or assembly occurrence quantities. Mass only with assigned densities. Explicit pair checks measure static native clearance only; no stiffness, strength, cost or manufacturing qualification. All failed trials retained. No automatic publication."));return true; +} +void appendDesignVariantsTools(V& list){V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("design_variants"));tool.set("description",V::makeStr("Configure installed parametric programs, save named configurations, compare exact editable alternatives, or enumerate up to 64 parameter combinations. inspect reads saved values; evaluate/explore isolate every trial and retain failures, exact bounds/volume and mass when assigned. constraints accepts min/max exact metrics; ranking includes only feasible measured rows. save/remove/prepare return revision-bound doc_preview candidates for explicit doc_apply. No inferred structural strength, cost or silent publication. Use parametric_program examples/install first."));arkjson::parse(R"({"type":"object","properties":{"action":{"type":"string","enum":["inspect","save","remove","evaluate","explore","prepare"]},"namespace":{"type":"string"},"name":{"type":"string"},"values":{"type":"object","additionalProperties":{"type":"number"}},"variants":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"values":{"type":"object","additionalProperties":{"type":"number"}}},"required":["name","values"],"additionalProperties":false},"maxItems":64},"axes":{"type":"object","additionalProperties":{"type":"array","items":{"type":"number"}}},"constraints":{"type":"object","additionalProperties":{"type":"object","properties":{"min":{"type":"number"},"max":{"type":"number"}},"additionalProperties":false}},"clearance_pairs":{"type":"array","maxItems":16,"items":{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"},"min_mm":{"type":"number","minimum":0}},"required":["a","b","min_mm"],"additionalProperties":false}},"objective":{"type":"string","enum":["volume_mm3","mass_kg","width_mm","depth_mm","height_mm","solid_definitions"]},"direction":{"type":"string","enum":["min","max"]},"thumbnails":{"type":"boolean"},"expected_revision":{"type":"integer","minimum":0}},"required":["action"],"additionalProperties":false})",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(false));tool.set("annotations",annotations);list.arr.push_back(tool);} +} diff --git a/src/drawing_pdf.inl b/src/drawing_pdf.inl new file mode 100644 index 0000000..f27ae89 --- /dev/null +++ b/src/drawing_pdf.inl @@ -0,0 +1,56 @@ +// PDF 1.4 writer. The vector presentation consumes the same derived display +// polylines and annotations as SVG. No mesh or PDF data re-enters the CAD model. +std::string drawingPdfPresentation(const std::vector& reports) { + require(!reports.empty()&&reports.size()<=256,"PDF needs 1..256 current sheets"); + auto literal=[](const std::string& utf8){ + std::string bytes; + for(size_t i=0;i=0xc2&&cp<=0xdf){require(i=128)throw std::runtime_error("PDF_FONT_UNSUPPORTED: use Latin-1 sheet labels or export SVG for this script"); + require(cp==9||cp==10||cp==13||(cp>=32&&cp<=255&&!(cp>=127&&cp<=159)),"PDF_FONT_UNSUPPORTED: sheet text requires Latin-1"); + if(cp==9||cp==10||cp==13)cp=' '; + if(cp=='('||cp==')'||cp=='\\')bytes+='\\'; + bytes+=(char)cp; + } + return "("+bytes+")"; + }; + std::vector objects(3); + objects[0]="<< /Type /Catalog /Pages 2 0 R /ViewerPreferences << /PrintScaling /None >> >>"; + objects[2]="<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"; + std::ostringstream kids;kids<<"<< /Type /Pages /Count "<>16)&255)/255.<<' '<<((rgb>>8)&255)/255.<<' '<<(rgb&255)/255.<<(fill?" rg\n":" RG\n");}; + color(blueprint?0x132d4b:0xfcfdfe,true);content<<"0 0 "<arr){ + const auto& points=need(edge,"display_polyline_mm");require(points.t==V::Arr&&points.arr.size()>=2,"PDF curve has no display samples"); + const auto role=word(edge,"visibility");const bool hidden=role=="hidden",hatch=std::string(collection)=="hatches",centre=std::string(collection)=="centrelines"; + color(blueprint?(hidden||hatch?0x628fb1:0xcee7f6):(hidden||hatch?0x788692:0x25394b),false);content<<(hatch?.12:hidden?.15:.25)<<" w\n"<<(centre?"[4 1 0.5 1] 0 d\n":hidden?"[2 1] 0 d\n":"[] 0 d\n"); + bool first=true;for(const auto& p:points.arr){content<> >> /Contents "<>"; + objects.push_back(pageObject.str());objects.push_back("<< /Length "+std::to_string(stream.size())+" >>\nstream\n"+stream+"endstream");kids<>";objects[1]=kids.str(); + std::string pdf="%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";std::vector offsets; + for(size_t i=0;i>\nstartxref\n"<";for(double x=48;x";}}; - if(auto hatch=view.find("hatches"))rows(*hatch,fine,.12,nullptr);for(bool hidden:{true,false})for(const auto& edge:need(view,"edges").arr){if((word(edge,"visibility")=="hidden")!=hidden)continue;V single=V::makeArr();single.arr.push_back(edge);rows(single,hidden?fine:ink,hidden?.15:.25,hidden?"2 1":nullptr);}if(auto centre=view.find("centrelines"))rows(*centre,dimInk,.14,"4 1 0.5 1");const auto& box=need(view,"projected_bounds_mm");text(word(view,"name"),offset.arr[0].num+box.arr[0].num*scale,offset.arr[1].num-box.arr[1].num*scale+16,2.7); + if(auto hatch=view.find("hatches"))rows(*hatch,fine,.12,nullptr);for(bool hidden:{true,false})for(const auto& edge:need(view,"edges").arr){if((word(edge,"visibility")=="hidden")!=hidden)continue;V single=V::makeArr();single.arr.push_back(edge);rows(single,hidden?fine:ink,hidden?.15:.25,hidden?"2 1":nullptr);}if(auto centre=view.find("centrelines"))rows(*centre,dimInk,.14,"4 1 0.5 1");const auto& box=need(view,"projected_bounds_mm");text(word(view,"name"),offset.arr[0].num+box.arr[0].num*scale,offset.arr[1].num-box.arr[1].num*scale+22,2.7); } bool toleranceDeclared=false;for(const auto& d:need(report,"dimensions").arr){annotationScope="dimension:"+word(d,"name");const V* view=nullptr;for(const auto& v:need(authored,"views").arr)if(word(v,"name")==word(d,"view"))view=&v;const auto& offset=need(*view,"offset_mm");const auto& a=need(d,"a_mm"),&b=need(d,"b_mm"),&p=need(d,"position_mm");double ax=offset.arr[0].num+a.arr[0].num*scale,ay=offset.arr[1].num-a.arr[1].num*scale,bx=offset.arr[0].num+b.arr[0].num*scale,by=offset.arr[1].num-b.arr[1].num*scale;auto kind=word(d,"kind");if(kind=="extent_horizontal")kind="horizontal";if(kind=="extent_vertical")kind="vertical"; if(kind=="horizontal"){line(ax,ay,ax,p.arr[1].num);line(bx,by,bx,p.arr[1].num);line(ax,p.arr[1].num,bx,p.arr[1].num,true);}else if(kind=="vertical"){line(ax,ay,p.arr[0].num,ay);line(bx,by,p.arr[0].num,by);line(p.arr[0].num,ay,p.arr[0].num,by,true);}else if(kind=="linear"){double dx=bx-ax,dy=by-ay,len=std::hypot(dx,dy),nx=-dy/len,ny=dx/len,shift=(p.arr[0].num-ax)*nx+(p.arr[1].num-ay)*ny;line(ax,ay,ax+nx*shift,ay+ny*shift);line(bx,by,bx+nx*shift,by+ny*shift);line(ax+nx*shift,ay+ny*shift,bx+nx*shift,by+ny*shift,true);}else line(p.arr[0].num,p.arr[1].num,bx,by,true); std::ostringstream label;label<find("title")?recipe->find("title")->str:word(authored,"name");text(title,12,titleY+9,4.2);text(toleranceDeclared?"Tolerances: declared per dimension":"Tolerances: not declared",12,titleY+17,2.6);if(recipe&&recipe->find("notes"))text(recipe->find("notes")->str.substr(0,110),12,titleY+25,2.4); + if(const auto* frames=authored.find("geometric_tolerances"))for(const auto& frame:frames->arr){ + toleranceDeclared=true;annotationScope="geometric_tolerance:"+word(frame,"name");const auto& p=need(frame,"position_mm");const auto& leader=need(frame,"leader_mm"); + std::ostringstream value;value< cells{word(frame,"characteristic"),value.str()};for(const auto& datum:need(frame,"datums").arr)cells.push_back(datum.str); + double x=p.arr[0].num,y=p.arr[1].num;const double start=x; + for(const auto& cell:cells){const double width=std::max(9.,3.+cell.size()*1.65);line(x,y,x+width,y);line(x,y+7,x+width,y+7);line(x,y,x,y+7);text(cell,x+1.5,y+4.8,2.7);x+=width;}line(x,y,x,y+7);const double cx=(start+x)/2,cy=y+3.5,dx=leader.arr[0].num-cx,dy=leader.arr[1].num-cy;const double attach=std::min(std::abs(dx)>1e-9?(x-start)/2/std::abs(dx):1e30,std::abs(dy)>1e-9?3.5/std::abs(dy):1e30);if(attach<1)line(cx+dx*attach,cy+dy*attach,leader.arr[0].num,leader.arr[1].num,true); + } + annotationScope="title_block";const double titleY=height-40;line(8,titleY,width-8,titleY);line(width*.64,titleY,width*.64,height-8);line(width*.64,titleY+16,width-8,titleY+16);std::string title=recipe&&recipe->find("title")?recipe->find("title")->str:word(authored,"name");text(title,12,titleY+9,4.2);text(toleranceDeclared?"Tolerances: caller-declared":"Tolerances: not declared",12,titleY+17,2.6);if(recipe&&recipe->find("notes"))text(recipe->find("notes")->str.substr(0,110),12,titleY+25,2.4); std::ostringstream meta;meta<<"Scale "<find("drawing_number")?recipe->find("drawing_number")->str:"SOURCE-LINKED SHEET",width*.64+4,titleY+13,2.5);text("REV "+(recipe&&recipe->find("revision_label")?recipe->find("revision_label")->str:std::string("UNDECLARED")),width*.64+4,titleY+23,2.6);text("Manufacturing qualification: pending",width*.64+4,titleY+29,2.2);s<<"";return s.str(); } } +#include "drawing_pdf.inl" + bool drawingRequiresVersion37(const V& drawing){ if(drawing.find("source")||drawing.find("template")||drawing.find("layout"))return true; if(auto views=drawing.find("views"))for(const auto& v:views->arr)if(v.find("direction")&&v.find("direction")->str=="isometric")return true; @@ -172,10 +181,12 @@ V drawingAuthoringSchema(){ "fraction_a":{"type":"number","minimum":0,"maximum":1},"fraction_b":{"type":"number","minimum":0,"maximum":1},"position_mm":{"type":"array","minItems":2,"maxItems":2,"items":{"type":"number"}}, "tolerance":{"type":"object","additionalProperties":false,"required":["lower","upper","units"],"properties":{"lower":{"type":"number","maximum":0},"upper":{"type":"number","minimum":0},"units":{"enum":["mm","in"]}}} }}} - }})",schema),"Internal drawing schema is malformed");return schema; + }})",schema),"Internal drawing schema is malformed"); + V frames;require(arkjson::parse(R"({"type":"array","maxItems":64,"items":{"type":"object","additionalProperties":false,"required":["name","view","characteristic","value","units","datums","position_mm","leader_mm"],"properties":{"name":{"type":"string"},"view":{"type":"string"},"characteristic":{"enum":["position","flatness","straightness","circularity","cylindricity","parallelism","perpendicularity","angularity","profile_line","profile_surface","runout","total_runout"]},"value":{"type":"number","exclusiveMinimum":0,"maximum":1000},"units":{"enum":["mm","in"]},"datums":{"type":"array","maxItems":3,"items":{"type":"string"}},"position_mm":{"type":"array","minItems":2,"maxItems":2,"items":{"type":"number"}},"leader_mm":{"type":"array","minItems":2,"maxItems":2,"items":{"type":"number"}}}}})",frames),"Geometric tolerance schema"); + V properties=*schema.find("properties");properties.set("geometric_tolerances",frames);schema.set("properties",properties);return schema; } void validateDrawing(const V& drawing,bool bound){ - fields(drawing,{"name","feature","source","layout","template","units","scale","paper_mm","views","dimensions","binding"});word(drawing,"name");require((drawing.find("feature")!=nullptr)!=(drawing.find("source")!=nullptr),"Drawing requires exactly one explicit feature or source recipe");if(auto feature=drawing.find("feature"))id(*feature);else validateSource(need(drawing,"source"),true);if(auto layout=drawing.find("layout"))require(layout->t==V::Str&&(layout->str=="auto"||layout->str=="manual"),"Drawing layout must be auto or manual"); + fields(drawing,{"name","feature","source","layout","template","units","scale","paper_mm","views","dimensions","geometric_tolerances","binding"});word(drawing,"name");require((drawing.find("feature")!=nullptr)!=(drawing.find("source")!=nullptr),"Drawing requires exactly one explicit feature or source recipe");if(auto feature=drawing.find("feature"))id(*feature);else validateSource(need(drawing,"source"),true);if(auto layout=drawing.find("layout"))require(layout->t==V::Str&&(layout->str=="auto"||layout->str=="manual"),"Drawing layout must be auto or manual"); if(auto t=drawing.find("template")){fields(*t,{"id","title","drawing_number","revision_label","notes"});const auto templateId=word(*t,"id");require(templateId=="ark_precision"||templateId=="ark_blueprint","Unsupported drawing template");for(const char* key:{"title","drawing_number","revision_label","notes"})if(auto text=t->find(key))require(text->t==V::Str&&text->str.size()<=(std::string(key)=="notes"?2000u:128u),"Invalid drawing template text");} const auto units=word(drawing,"units");require(units=="mm"||units=="in","Drawing units must be mm or in");const double scale=number(need(drawing,"scale"));require(scale>0&&scale<=100,"Drawing scale must be in (0,100]");xy(need(drawing,"paper_mm"),2);for(const auto& n:need(drawing,"paper_mm").arr)require(n.num>=50&&n.num<=2000,"Drawing paper size must be 50..2000 mm"); const auto& views=need(drawing,"views");require(views.t==V::Arr&&!views.arr.empty()&&views.arr.size()<=12,"Drawing requires 1..12 views");std::set names; @@ -184,6 +195,24 @@ void validateDrawing(const V& drawing,bool bound){ for(const auto& dimension:dimensions.arr){fields(dimension,{"name","view","kind","reference_a","reference_b","fraction_a","fraction_b","occurrence_a","occurrence_b","position_mm","tolerance"});require(dimNames.insert(word(dimension,"name")).second,"Duplicate drawing dimension name");require(names.count(word(dimension,"view"))!=0,"Dimension view not found");const auto kind=word(dimension,"kind");const bool extent=kind=="extent_horizontal"||kind=="extent_vertical";require(extent||kind=="linear"||kind=="horizontal"||kind=="vertical"||kind=="radius"||kind=="diameter","Unsupported drawing dimension kind");if(extent){for(const char* key:{"reference_a","reference_b","fraction_a","fraction_b","occurrence_a","occurrence_b"})require(!dimension.find(key),"Extent dimensions derive exact projected bounds and cannot author semantic references");}else{word(dimension,"reference_a");if(kind=="radius"||kind=="diameter")require(!dimension.find("reference_b")&&!dimension.find("fraction_b")&&!dimension.find("occurrence_b"),"Radial dimensions use one exact circular axis reference");else word(dimension,"reference_b");} for(const char* key:{"occurrence_a","occurrence_b"})if(auto occurrence=dimension.find(key)){fields(*occurrence,{"node","copy"});id(need(*occurrence,"node"));const double c=number(need(*occurrence,"copy"));require(c>=0&&c<=4095&&c==std::floor(c),"Dimension occurrence copy must be an explicit stable slot");} xy(need(dimension,"position_mm"),2);for(const char* key:{"fraction_a","fraction_b"})if(auto f=dimension.find(key))require(number(*f)>=0&&f->num<=1,"Drawing reference fraction must be in [0,1]");if(auto tolerance=dimension.find("tolerance")){fields(*tolerance,{"lower","upper","units"});require(word(*tolerance,"units")==units,"Tolerance units must match the drawing units");require(number(need(*tolerance,"lower"))<=0&&number(need(*tolerance,"upper"))>=0,"Tolerance lower must be <=0 and upper >=0");}} + if(const auto* frames=drawing.find("geometric_tolerances")) { + require(frames->t==V::Arr&&frames->arr.size()<=64,"Drawing permits at most 64 geometric tolerance frames"); + std::set frameNames; + const std::set characteristics{"position","flatness","straightness","circularity","cylindricity","parallelism","perpendicularity","angularity","profile_line","profile_surface","runout","total_runout"}; + for(const auto& frame:frames->arr) { + fields(frame,{"name","view","characteristic","value","units","datums","position_mm","leader_mm"}); + require(frameNames.insert(word(frame,"name")).second,"Duplicate geometric tolerance name"); + require(names.count(word(frame,"view"))!=0,"Geometric tolerance view not found"); + require(characteristics.count(word(frame,"characteristic"))!=0,"Unsupported geometric tolerance characteristic"); + require(word(frame,"units")==units,"Geometric tolerance units must match the sheet"); + require(number(need(frame,"value"))>0&&number(need(frame,"value"))<=1000,"Geometric tolerance must be positive and bounded"); + xy(need(frame,"position_mm"),2);xy(need(frame,"leader_mm"),2); + const auto& datums=need(frame,"datums");require(datums.t==V::Arr&&datums.arr.size()<=3,"Declare zero to three datum identifiers"); + std::set seen;for(const auto& datum:datums.arr)require(datum.t==V::Str&&!datum.str.empty()&&datum.str.size()<=8&&datum.str.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")==std::string::npos&&seen.insert(datum.str).second,"Datum identifiers must be unique uppercase labels"); + const auto characteristic=word(frame,"characteristic"); + if(characteristic=="flatness"||characteristic=="straightness"||characteristic=="circularity"||characteristic=="cylindricity")require(datums.arr.empty(),"Form tolerance frames must not reference datums"); + } + } if(bound||drawing.find("binding")){const auto& binding=need(drawing,"binding");fields(binding,{"brep_base64_sha256","topology_sha256","observed_revision"});for(const char* key:{"brep_base64_sha256","topology_sha256"}){const auto hash=word(binding,key);require(hash.size()==64&&hash.find_first_not_of("0123456789abcdef")==std::string::npos,"Invalid drawing source digest");}const double revision=number(need(binding,"observed_revision"));require(revision>=0&&revision<=9007199254740990.&&revision==std::floor(revision),"Invalid drawing observed revision");} } void applyDrawingCommand(Document& doc,const V& command){ @@ -201,11 +230,16 @@ V inspectDrawing(Document& doc,const V& args,u64 revision){ const auto& drawing=findDrawing(doc,word(args,"name"));try{return evaluate(doc,drawing,revision,false);}catch(const std::exception& error){V out=V::makeObj();out.set("schema",V::makeStr("ark.drawing.v1"));out.set("name",*drawing.find("name"));out.set("revision",V::makeNum((double)revision));out.set("authored",drawing);out.set("status",V::makeStr("invalid"));out.set("reason",V::makeStr(error.what()));out.set("measurements_current",V::makeBool(false));return out;} } V exportDrawing(Document& doc,const V& args,u64 revision){ - fields(args,{"name","expected_revision","path","format"});const auto& expected=need(args,"expected_revision");require(expected.t==V::Num&&expected.num==(double)revision,"Revision conflict; inspect current drawing before export");const auto format=word(args,"format");require(format=="json"||format=="svg"||format=="dxf","Drawing export supports json, svg or dxf");const auto& path=need(args,"path");require(path.t==V::Str&&!path.str.empty()&&path.str.size()<=4096,"Drawing export path is invalid");V probe=V::makeObj();probe.set("name",need(args,"name"));const auto report=inspectDrawing(doc,probe,revision);require(word(report,"status")=="current","Drawing export requires current geometry and resolved semantic dimensions"); + fields(args,{"name","names","expected_revision","path","format"});const auto& expected=need(args,"expected_revision");require(expected.t==V::Num&&expected.num==(double)revision,"Revision conflict; inspect current drawing before export");const auto format=word(args,"format");require(format=="json"||format=="svg"||format=="dxf"||format=="pdf","Drawing export supports json, svg, dxf or pdf");const auto& path=need(args,"path");require(path.t==V::Str&&!path.str.empty()&&path.str.size()<=4096,"Drawing export path is invalid"); + require((args.find("name")!=nullptr)!=(args.find("names")!=nullptr),"Provide exactly one name or ordered names list"); + V names=V::makeArr();if(args.find("name"))names.arr.push_back(need(args,"name"));else{require(format=="pdf","Multiple sheets require PDF export");names=need(args,"names");} + require(names.t==V::Arr&&!names.arr.empty()&&names.arr.size()<=256,"PDF needs 1..256 selected sheets");std::set seen;std::vector reports; + for(const auto& name:names.arr){require(name.t==V::Str&&!name.str.empty()&&name.str.size()<=128&&seen.insert(name.str).second,"Sheet names must be unique bounded strings");V probe=V::makeObj();probe.set("name",name);auto page=inspectDrawing(doc,probe,revision);require(word(page,"status")=="current","Drawing export requires current geometry and resolved semantic dimensions: "+name.str);reports.push_back(std::move(page));} + const auto& report=reports.front(); if(format=="dxf"){ const auto destination=fs::absolute(fs::u8path(path.str)).lexically_normal();require(!fs::exists(destination)&&fs::is_directory(destination.parent_path()),"Drawing destination exists or its parent is unavailable");V annotations=V::makeArr();svg(report,&annotations);V request=V::makeObj(),worker=V::makeObj();request.set("report",report);request.set("annotations",annotations);const auto encoded=destination.u8string();request.set("path",V::makeStr(std::string(reinterpret_cast(encoded.data()),encoded.size())));worker.set("operation",V::makeStr("drawing_dxf"));worker.set("request",request);V receipt=nativeWorkerRequest(worker);receipt.set("path",path);receipt.set("format",V::makeStr(format));receipt.set("revision",V::makeNum((double)revision));receipt.set("sha256",need(receipt,"file_sha256"));receipt.set("authority",V::makeStr("exact_nonassociative_derived_curves_and_source_metadata"));receipt.set("source_binding_sha256",need(report,"current_brep_base64_sha256"));receipt.set("document_unchanged",V::makeBool(true));return receipt; } - const auto bytes=format=="json"?report.dump():svg(report);require(bytes.size()<=16u*1024u*1024u,"Drawing export exceeds 16 MiB"); - const auto destination=fs::absolute(fs::u8path(path.str)).lexically_normal();require(!fs::exists(destination)&&fs::is_directory(destination.parent_path()),"Drawing destination exists or its parent is unavailable");const auto stamp=std::chrono::steady_clock::now().time_since_epoch().count();auto staged=destination.parent_path()/(".ark-drawing-"+iterationSha256(bytes+std::to_string(stamp))+".tmp");struct Cleanup{fs::path path;~Cleanup(){std::error_code ignored;fs::remove(path,ignored);}}cleanup{staged};{std::ofstream out(staged,std::ios::binary);require((bool)out,"Cannot stage drawing export");out.write(bytes.data(),(std::streamsize)bytes.size());out.flush();require((bool)out,"Cannot flush drawing export");}std::error_code error;fs::create_hard_link(staged,destination,error);require(!error,"Atomic no-replace drawing publication failed: "+error.message());V receipt=V::makeObj();receipt.set("path",path);receipt.set("format",V::makeStr(format));receipt.set("revision",V::makeNum((double)revision));receipt.set("sha256",V::makeStr(iterationSha256(bytes)));receipt.set("authority",V::makeStr(format=="svg"?"display_samples":"exact_derived_curves_and_semantic_measurements"));receipt.set("document_unchanged",V::makeBool(true));return receipt; + const auto bytes=format=="pdf"?drawingPdfPresentation(reports):format=="json"?report.dump():svg(report);require(bytes.size()<=16u*1024u*1024u,"Drawing export exceeds 16 MiB"); + const auto destination=fs::absolute(fs::u8path(path.str)).lexically_normal();require(!fs::exists(destination)&&fs::is_directory(destination.parent_path()),"Drawing destination exists or its parent is unavailable");const auto stamp=std::chrono::steady_clock::now().time_since_epoch().count();auto staged=destination.parent_path()/(".ark-drawing-"+iterationSha256(bytes+std::to_string(stamp))+".tmp");struct Cleanup{fs::path path;~Cleanup(){std::error_code ignored;fs::remove(path,ignored);}}cleanup{staged};{std::ofstream out(staged,std::ios::binary);require((bool)out,"Cannot stage drawing export");out.write(bytes.data(),(std::streamsize)bytes.size());out.flush();require((bool)out,"Cannot flush drawing export");}std::error_code error;fs::create_hard_link(staged,destination,error);require(!error,"Atomic no-replace drawing publication failed: "+error.message());V receipt=V::makeObj();receipt.set("path",path);receipt.set("format",V::makeStr(format));receipt.set("revision",V::makeNum((double)revision));receipt.set("sha256",V::makeStr(iterationSha256(bytes)));receipt.set("authority",V::makeStr((format=="svg"||format=="pdf")?"display_samples":"exact_derived_curves_and_semantic_measurements"));receipt.set("document_unchanged",V::makeBool(true));if(format=="pdf"){receipt.set("pages",V::makeNum((double)reports.size()));receipt.set("sheet_names",names);receipt.set("vector_presentation",V::makeBool(true));receipt.set("print_scale",V::makeStr("actual_size"));receipt.set("tolerance_authority",V::makeStr("caller_declared_not_verified"));}return receipt; } } diff --git a/src/iteration_history.cpp b/src/iteration_history.cpp index 2cf19a9..1a3b0a7 100644 --- a/src/iteration_history.cpp +++ b/src/iteration_history.cpp @@ -229,7 +229,7 @@ V iterationCompact(const Document& source,size_t keepRecent,const V& receipt,con record.set("archived_branch_heads",V::makeNum(omittedHeads));record.set("policy",V::makeStr("head_ancestor_suffix_contiguous_undo_clear_redo")); V signedRecord=record;canonical(signedRecord);record.set("sha256",V::makeStr(iterationSha256(signedRecord.dump())));out.set("compaction",record);out.set("compacted",V::makeBool(true));return out; } -bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>55))throw std::runtime_error("Iteration history requires a supported document version 27 or later");if(h->find("compaction")&&root.find("version")->num<50)throw std::runtime_error("Compacted history requires document version 50");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} +bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>56))throw std::runtime_error("Iteration history requires a supported document version 27 or later");if(h->find("compaction")&&root.find("version")->num<50)throw std::runtime_error("Compacted history requires document version 50");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} bool iterationValidate(const Document& document,const V& h,std::string& error){ try{if(h.t!=V::Obj||need(h,"schema").t!=V::Num||(need(h,"schema").num!=1&&need(h,"schema").num!=2))throw std::runtime_error("Unsupported iteration history schema");const V& blobs=need(h,"blobs"),nodes=need(h,"nodes");if(blobs.t!=V::Obj||nodes.t!=V::Arr||nodes.arr.size()>maxNodes)throw std::runtime_error("Invalid history blob/node storage"); const bool derivedOnly=need(h,"schema").num==2;if(derivedOnly)validateMigrations(h);else if(h.find("migrations"))throw std::runtime_error("History migration records require schema 2"); diff --git a/src/model.cpp b/src/model.cpp index 546bae8..43c8d6d 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -541,7 +541,7 @@ Document Document::authoringCopy() const { Document out;out.params=params;out.parameterError=parameterError;out.sketches=sketches;out.planes=planes;out.canvases=canvases; out.imageAssets=imageAssets;out.stamps=stamps; out.features=features;out.materials=materials;out.usage=usage;out.agentActivity=agentActivity;out.bomDocumentId=bomDocumentId;out.iterationHistory=iterationHistory;out.skeleton=skeleton; - out.drawings=drawings;out.designContainerCheckout=designContainerCheckout;out.parametricComponents=parametricComponents;out.schematics=schematics;out.manufacturingPlans=manufacturingPlans;out.parametricPrograms=parametricPrograms; + out.drawings=drawings;out.designContainerCheckout=designContainerCheckout;out.parametricComponents=parametricComponents;out.schematics=schematics;out.manufacturingPlans=manufacturingPlans;out.parametricPrograms=parametricPrograms;out.designVariants=designVariants; out.historyTip=historyTip;out.assemblyConfigurations=assemblyConfigurations; out.assemblyLoadSelection=assemblyLoadSelection;out.assemblyExternalReferences=assemblyExternalReferences;out.motions=motions;out.explodedViews=explodedViews; out.dragChains=dragChains; diff --git a/src/onboarding.cpp b/src/onboarding.cpp index a285a3a..0940fe0 100644 --- a/src/onboarding.cpp +++ b/src/onboarding.cpp @@ -35,13 +35,33 @@ arkjson::Value agentOnboard(const AgentSession& session,const arkjson::Value& ar const char* drawingAuthorization="Agents create, edit, refresh or export 2D technical/manufacturing drawings only when the user explicitly requests that drawing work. Design completion, a BOM review or an available drawing template does not authorize drawing writes. Read-only drawing_inspect discovery remains available; human Studio drawing controls remain manual."; if(topic=="commands"){auto catalog=agentCommandCatalog(args);catalog.set("drawing_authorization",V::makeStr(drawingAuthorization));return catalog;} for(const auto& field:args.obj)if(field.first!="topic"&&field.first!="detail")throw std::runtime_error("Unknown agent_onboard field: "+field.first); - if(topic!="bom"&&topic!="fasteners"&&topic!="components"&&topic!="vendors"&&topic!="plastics"&&topic!="motion"&&topic!="manufacturing"&&topic!="physics"&&topic!="automation"&&topic!="overview"&&topic!="sketch"&&topic!="tube"&&topic!="assembly"&&topic!="surfacing"&&topic!="sheet"&&topic!="solids"&&topic!="mesh"&&topic!="materials"&&topic!="frames"&&topic!="electronics"&&topic!="routing"&&topic!="suspension"&&topic!="skeleton"&&topic!="drawings"&&topic!="holes"&&topic!="cad_import"&&topic!="containers"&&topic!="stamps"&&topic!="planes"&&topic!="history"&&topic!="configurations"&&topic!="wood"&&topic!="networks"&&topic!="lighting"&&topic!="hud"&&topic!="exploded_views"&&topic!="schematics"&&topic!="rubber"&&topic!="transmission"&&topic!="programs")throw std::runtime_error("Unknown onboarding topic; use available_topics from agent_onboard overview"); + if(topic!="bom"&&topic!="fasteners"&&topic!="components"&&topic!="vendors"&&topic!="plastics"&&topic!="motion"&&topic!="manufacturing"&&topic!="physics"&&topic!="automation"&&topic!="overview"&&topic!="sketch"&&topic!="tube"&&topic!="assembly"&&topic!="surfacing"&&topic!="sheet"&&topic!="solids"&&topic!="mesh"&&topic!="materials"&&topic!="frames"&&topic!="electronics"&&topic!="routing"&&topic!="suspension"&&topic!="skeleton"&&topic!="drawings"&&topic!="holes"&&topic!="cad_import"&&topic!="containers"&&topic!="stamps"&&topic!="planes"&&topic!="history"&&topic!="configurations"&&topic!="wood"&&topic!="networks"&&topic!="lighting"&&topic!="hud"&&topic!="exploded_views"&&topic!="schematics"&&topic!="rubber"&&topic!="transmission"&&topic!="programs"&&topic!="variants"&&topic!="design_review")throw std::runtime_error("Unknown onboarding topic; use available_topics from agent_onboard overview"); V r=V::makeObj();r.set("product",V::makeStr("ARK"));r.set("name",V::makeStr("Agent-Ready Kernel"));r.set("tagline",V::makeStr("Parametric CAD for people and agents."));r.set("version",V::makeStr(ark::app_version()));r.set("iteration_code",V::makeStr(ark::app_iteration_code()));r.set("topic",V::makeStr(topic));if(detail=="full")r.set("document",session.info()); r.set("detail",V::makeStr(detail));r.set("document_state_included",V::makeBool(detail=="full")); r.set("units",V::makeStr("Lengths mm; plane/feature rotations degrees; sketch angle constraints and trig radians. deg(x) converts degrees to radians.")); auto list=[](std::initializer_list strings){V a=V::makeArr();for(auto s:strings)a.arr.push_back(V::makeStr(s));return a;}; r.set("workflow",list({"Reuse agent_onboard detail:guide for static guidance. Read doc_info detail:revision for current revision/status, or doc_info detail:digest for a compact per-revision inventory whose fingerprints, sent back as known_fingerprints, return only later changes. Then use object_context for selected targets or filtered doc_info detail:design for required operations/dependencies and measured evidence. Use doc_get only when the full document is needed.","Use doc_preview detail:changes for compact checked proposals and doc_apply with expected_revision. One batch recomputes once; any failure rolls back the entire batch.","Use created_ids returned by a batch for later feature inputs. Do not assume IDs or use triangle IDs as persistent references.","Inspect native_inspect detail:properties for current native validity/physical properties, report for operation diagnostics, full for reference topology. Mesh/raycast evidence is display tessellation.","Keep queries compact; request meshes or snapshots only when needed. Save the parametric document with doc_save."})); - r.set("available_topics",list({"bom","fasteners","components","vendors","plastics","motion","manufacturing","physics","automation","overview","sketch","tube","assembly","surfacing","sheet","solids","mesh","materials","frames","electronics","routing","suspension","skeleton","drawings","holes","cad_import","containers","stamps","planes","history","configurations","wood","networks","lighting","hud","exploded_views","schematics","rubber","transmission","programs"})); + r.set("available_topics",list({"bom","fasteners","components","vendors","plastics","motion","manufacturing","physics","automation","overview","sketch","tube","assembly","surfacing","sheet","solids","mesh","materials","frames","electronics","routing","suspension","skeleton","drawings","holes","cad_import","containers","stamps","planes","history","configurations","wood","networks","lighting","hud","exploded_views","schematics","rubber","transmission","programs","variants","design_review"})); + r.set("drawing_authorization",V::makeStr(drawingAuthorization)); + if(topic=="variants"){ + r.set("tools",list({"design_variants","parametric_program","doc_info","doc_apply","snapshot","native_inspect"})); + r.set("rules",list({ + "Start from an installed parametric program and inspect its namespace, public numeric parameters, bounds and source hash. Load programs guidance to author or install a family when needed. A proposal is not a created part.", + "design_variants saves named parameter configurations, evaluates alternatives in isolated native candidates and explores an explicit bounded parameter grid. Read the tool schema for action-specific fields. Every document-bound request uses the observed expected_revision.", + "Compare actual measured volume, bounds and mass only where material density is explicitly known. Keep invalid candidates and their failure reasons in the result. Program assertions constrain the design but do not certify stiffness, strength, fatigue or manufacture.", + "save/remove/prepare return revision-bound preview candidates. Inspect the returned recipe and candidate, then explicitly publish its candidate_id through doc_apply or your Team-owned team_apply_step. Changed program sources or revisions require reinspection and a new candidate; never silently rebase.", + "For requests such as three alternatives, use the same program, declared requirements and measurement scope. Explain which inputs vary and report rejected attempts. Keep chosen variants editable; do not substitute screenshot geometry." + }));return r; + } + if(topic=="design_review"){ + r.set("tools",list({"design_review","history_info","object_context","doc_info","doc_apply","native_inspect"})); + r.set("rules",list({ + "Use history_info to select retained iteration IDs, then design_review action compare with before_id, after_id and current expected_revision. The comparison reports authored changes and recomputed geometric evidence; display overlays are not manufacturing geometry.", + "Use diagnose for current failed features and their upstream/downstream dependencies. Read references and parameters before proposing a repair. prepare_repair accepts an explicit correction and returns a normal doc_preview candidate for review.", + "Publish only the reviewed candidate at its observed revision. A repair does not justify increasing tolerance, suppressing or deleting a solid, silently remapping references or discarding other failures. Recompute must validate the resulting document.", + "Compare source dimensions, occurrence/BOM quantities and native results separately. Unknown or failed geometry remains explicit; unchanged tessellation is not proof of exact B-rep equivalence." + }));return r; + } if(topic=="programs"){ r.set("tools",list({"parametric_program","doc_info","doc_apply","native_inspect","geometry_query","snapshot"})); r.set("rules",list({ diff --git a/src/parametric_component_library.inl b/src/parametric_component_library.inl new file mode 100644 index 0000000..a5d209d --- /dev/null +++ b/src/parametric_component_library.inl @@ -0,0 +1,30 @@ +V parametricComponentLibrary(const V& args){ + namespace fs=std::filesystem;const auto root=fs::absolute(fs::u8path(text(args,"directory"))).lexically_normal(); + if(!fs::is_directory(root))fail("LIBRARY_DIRECTORY","Choose an existing local component folder"); + auto lower=[](std::string value){for(auto& c:value)c=(char)std::tolower((unsigned char)c);return value;}; + const auto query=lower(get(args,"query").asStr()),category=get(args,"category").asStr(),kind=get(args,"kind").asStr(); + if(!kind.empty()&&kind!="part"&&kind!="assembly")fail("LIBRARY_KIND","Choose part or assembly"); + V out=V::makeObj(),rows=V::makeArr(),errors=V::makeArr();std::vector paths; + size_t examined=0;bool truncated=false; + fs::recursive_directory_iterator it(root,fs::directory_options::skip_permission_denied),end; + for(;it!=end;++it){if(++examined>4096){truncated=true;break;}if(it.depth()>=4&&it->is_directory())it.disable_recursion_pending();if(it->is_symlink()){if(it->is_directory())it.disable_recursion_pending();continue;}if(!it->is_regular_file())continue;const auto ext=it->path().extension().string();if(ext==".arkprt"||ext==".arktop")paths.push_back(it->path());} + std::sort(paths.begin(),paths.end()); + for(const auto& path:paths){if(rows.arr.size()>=256){truncated=true;break;}const auto utf=path.u8string();const std::string file(utf.begin(),utf.end());try{const auto package=loadParametricComponent(file);const auto relative=fs::relative(path.parent_path(),root).generic_u8string();const std::string group(relative.begin(),relative.end());if(!kind.empty()&&get(package,"kind").asStr()!=kind)continue;if(!category.empty()&&category!=group)continue; + std::string haystack=get(package,"name").asStr()+" "+group+" "+path.filename().string();for(const auto& parameter:get(package,"parameters").arr)haystack+=" "+parameter.str; + if(!query.empty()&&lower(haystack).find(query)==std::string::npos)continue; + V row=brief(package);row.set("path",V::makeStr(file));row.set("category",V::makeStr(group));V values=V::makeObj();for(const auto& name:get(package,"parameters").arr)for(const auto& parameter:get(get(package,"document"),"params").arr)if(get(parameter,"name").str==name.str)values.set(name.str,get(parameter,"expr"));row.set("parameter_expressions",values);rows.arr.push_back(row); + }catch(const std::exception& e){V rejection=V::makeObj();rejection.set("path",V::makeStr(file));rejection.set("error",V::makeStr(e.what()));errors.arr.push_back(rejection);}} + out.set("schema",V::makeStr("ark.component-library.v1"));out.set("components",rows);out.set("rejected",errors);out.set("truncated",V::makeBool(truncated));out.set("authority",V::makeStr("authored_component_packages"));out.set("automatic_updates",V::makeBool(false));return out; +} +V parametricComponentThumbnail(const std::string& path){ + const auto package=loadParametricComponent(path);Document d=parse(get(package,"document"));d.recompute();for(const auto& result:d.lastResults)if(!result.ok)fail("THUMBNAIL_GEOMETRY",result.error); + std::vector placements;std::string error;if(!resolveAssembly(d,placements,error))fail("THUMBNAIL_ASSEMBLY",error); + std::vector> segments;double xmin=1e300,ymin=1e300,xmax=-1e300,ymax=-1e300;bool sampled=false; + for(const auto& placement:placements){if(!placement.visible)continue;for(const auto& body:d.evalBodies)if(body.id==placement.feature){const auto& mesh=body.tessellate(d.tessOpt);const size_t stride=std::max(1,(mesh.triCount()+999)/1000);sampled|=stride>1; + auto point=[&](u32 index){if(index>=mesh.vertCount())fail("THUMBNAIL_MESH","Invalid derived display index");const Vec3 p=placement.world.transformPoint({mesh.pos[index*3],mesh.pos[index*3+1],mesh.pos[index*3+2]});return std::array{(p.x-p.y)*.7071067811865476,(p.x+p.y)*.408248290463863-p.z*.816496580927726};}; + for(size_t t=0;t24000)fail("THUMBNAIL_LIMIT","Too many component display segments");}} + }} + if(segments.empty())fail("THUMBNAIL_EMPTY","Component has no visible evaluated geometry"); + const double scale=220./std::max({xmax-xmin,ymax-ymin,1e-9});V lines=V::makeArr();for(const auto& segment:segments){V line=V::makeArr();for(int i=0;i<4;++i)line.arr.push_back(V::makeNum(128+(segment[i]-(i%2?(ymin+ymax)/2:(xmin+xmax)/2))*scale));lines.arr.push_back(line);} + V out=V::makeObj();out.set("schema",V::makeStr("ark.component-thumbnail.v1"));out.set("size",V::makeNum(256));out.set("lines",lines);out.set("sampled",V::makeBool(sampled));out.set("package_sha256",V::makeStr(hash(package)));out.set("authority",V::makeStr("derived_display_only"));return out; +} diff --git a/src/parametric_components.cpp b/src/parametric_components.cpp index 69e42d3..0d750f5 100644 --- a/src/parametric_components.cpp +++ b/src/parametric_components.cpp @@ -5,6 +5,8 @@ #include "ark/history_authoring.hpp" #include #include +#include +#include "ark/assembly.hpp" #include #include #include @@ -22,7 +24,7 @@ void canonical(V& v){if(v.t==V::Obj){for(auto& p:v.obj)canonical(p.second);std:: std::string hash(V v){canonical(v);return iterationSha256(v.dump());} bool digest(const V& v){return v.t==V::Str&&v.str.size()==64&&v.str.find_first_not_of("0123456789abcdef")==std::string::npos;} u64 id(const V& v){if(v.t!=V::Num||!std::isfinite(v.num)||v.num<1||v.num>9007199254740991.||v.num!=std::floor(v.num))fail("ID","Expected a positive exact integer");return (u64)v.num;} -std::string text(const V& v,const char* key){const auto& p=get(v,key);const size_t limit=std::string(key)=="path"?32768:128;if(p.t!=V::Str||p.str.empty()||p.str.size()>limit)fail("TEXT",std::string(key)+" needs nonempty bounded text");return p.str;} +std::string text(const V& v,const char* key){const auto& p=get(v,key);const size_t limit=(std::string(key)=="path"||std::string(key)=="directory")?32768:128;if(p.t!=V::Str||p.str.empty()||p.str.size()>limit)fail("TEXT",std::string(key)+" needs nonempty bounded text");return p.str;} bool numeric(const std::string& c){return c=="features"||c=="assembly"||c=="mates";} std::string rowKey(const std::string& c,const V& row){return numeric(c)?std::to_string(id(get(row,"id"))):text(row,"name");} V authored(const Document& d){V out;if(!arkjson::parse(documentToJson(d,false,false),out))fail("SOURCE","Cannot serialize authored source");return out;} @@ -153,15 +155,19 @@ bool applyParametricComponentCommand(Document& d,const V& command){ validateParametricComponents(entries);next.parametricComponents=entries;next.componentBindingsToSeal=d.componentBindingsToSeal;next.componentBindingsToSeal.push_back(ns);d=std::move(next);return true; } void sealParametricComponentBindings(Document& d){if(d.componentBindingsToSeal.empty())return;const auto root=authored(d);for(auto& e:d.parametricComponents.arr)if(std::find(d.componentBindingsToSeal.begin(),d.componentBindingsToSeal.end(),get(e,"namespace").asStr())!=d.componentBindingsToSeal.end())e.set("baseline",fingerprints(root,get(e,"mapping"),get(e,"package")));d.componentBindingsToSeal.clear();} +#include "parametric_component_library.inl" + bool callParametricComponentTool(AgentSession& s,const std::string& tool,const V& args,V& out){ if(tool!="parametric_components")return false;const auto action=text(args,"action"); + if(action=="library"){out=parametricComponentLibrary(args);return true;} + if(action=="thumbnail"){out=parametricComponentThumbnail(text(args,"path"));return true;} if(action=="inspect"){out=V::makeObj();out.set("revision",V::makeNum((double)s.revision));if(args.find("path"))out.set("package",brief(loadParametricComponent(text(args,"path"))));else{V entries=V::makeArr();for(const auto& e:s.document.parametricComponents.arr){V row=brief(get(e,"package"));row.set("namespace",get(e,"namespace"));row.set("overrides",get(e,"overrides"));row.set("mapping",get(e,"mapping"));entries.arr.push_back(row);}out.set("components",entries);}return true;} expected(s,args); if(action=="export"){const auto p=makeParametricComponent(s.document,args);const auto path=text(args,"path");saveParametricComponent(p,path);out=brief(p);out.set("path",V::makeStr(path));return true;} if(action!="prepare")fail("ACTION","Use inspect, export or prepare"); const auto mode=text(args,"mode");if(mode!="insert"&&mode!="update"&&mode!="configure")fail("ACTION","Prepare insert, update or configure"); V command=V::makeObj();command.set("op",V::makeStr("component."+mode));command.set("namespace",V::makeStr(text(args,"namespace"))); - V package;if(mode!="configure"){package=loadParametricComponent(text(args,"path"));command.set("package",package);command.set("package_sha256",V::makeStr(hash(package)));} + V package;if(mode!="configure"){package=loadParametricComponent(text(args,"path"));if(args.find("expected_source_sha256")&&get(args,"expected_source_sha256").asStr()!=hash(package))fail("STALE_SOURCE","Component file changed since catalog inspection");command.set("package",package);command.set("package_sha256",V::makeStr(hash(package)));} if(mode!="insert"){bool found=false;for(const auto& e:s.document.parametricComponents.arr)if(get(e,"namespace").asStr()==get(command,"namespace").str){command.set("expected_package_sha256",get(e,"package_sha256"));found=true;}if(!found)fail("NAMESPACE","Installed component not found");} if(args.find("overrides"))command.set("overrides",get(args,"overrides")); V commands=V::makeArr();commands.arr.push_back(command);V apply=V::makeObj();apply.set("commands",commands);apply.set("expected_revision",V::makeNum((double)s.revision)); @@ -169,5 +175,5 @@ bool callParametricComponentTool(AgentSession& s,const std::string& tool,const V // including exact geometry. The returned candidate_id freezes what was reviewed. const auto preview=s.call("doc_preview",apply);const auto& evaluated=get(preview,"structuredContent");if(get(preview,"isError").b||!get(evaluated,"valid").b||!evaluated.find("candidate_id"))fail("PREVIEW",evaluated.dump());out=evaluated;erase(out,"apply");if(!package.isNull())out.set("package",brief(package));out.set("namespace",get(command,"namespace"));out.set("mode",V::makeStr(mode));out.set("publication",V::makeStr("doc_apply candidate_id + expected_revision"));return true; } -void appendParametricComponentTools(V& list){V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("parametric_components"));tool.set("description",V::makeStr("Portable parametric .arkprt parts / .arktop assemblies embedded in .ark projects. inspect reads installed revisions or a file; export writes an immutable new file (previous_path creates the next revision); prepare insert/update/configure evaluates an isolated candidate for explicit doc_apply. Numeric overrides only target public parameters. Updates reject local edits and structural identity changes. No network or automatic source updates."));arkjson::parse(R"({"type":"object","properties":{"action":{"type":"string","enum":["inspect","export","prepare"]},"mode":{"type":"string","enum":["insert","update","configure"]},"kind":{"type":"string","enum":["part","assembly"]},"feature":{"type":"integer","minimum":1},"node":{"type":["integer","string"]},"name":{"type":"string"},"namespace":{"type":"string"},"path":{"type":"string"},"previous_path":{"type":"string"},"parameters":{"type":"array","items":{"type":"string"}},"interfaces":{"type":"array","items":{"type":"string"}},"overrides":{"type":"object","additionalProperties":{"type":"number"}},"expected_revision":{"type":"integer","minimum":0}},"required":["action"],"additionalProperties":false})",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(false));tool.set("annotations",annotations);list.arr.push_back(tool);} +void appendParametricComponentTools(V& list){V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("parametric_components"));tool.set("description",V::makeStr("Portable parametric .arkprt parts / .arktop assemblies embedded in .ark projects. inspect reads installed revisions or a file; export writes an immutable new file (previous_path creates the next revision); prepare insert/update/configure evaluates an isolated candidate for explicit doc_apply. Numeric overrides only target public parameters. Updates reject local edits and structural identity changes. library scans an explicit local directory with query/category/kind filters; thumbnail derives a display-only geometry preview. No network or automatic source updates."));arkjson::parse(R"({"type":"object","properties":{"action":{"type":"string","enum":["inspect","export","prepare","library","thumbnail"]},"mode":{"type":"string","enum":["insert","update","configure"]},"kind":{"type":"string","enum":["part","assembly"]},"feature":{"type":"integer","minimum":1},"node":{"type":["integer","string"]},"name":{"type":"string"},"namespace":{"type":"string"},"path":{"type":"string"},"directory":{"type":"string"},"query":{"type":"string"},"category":{"type":"string"},"expected_source_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"},"previous_path":{"type":"string"},"parameters":{"type":"array","items":{"type":"string"}},"interfaces":{"type":"array","items":{"type":"string"}},"overrides":{"type":"object","additionalProperties":{"type":"number"}},"expected_revision":{"type":"integer","minimum":0}},"required":["action"],"additionalProperties":false})",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(false));tool.set("annotations",annotations);list.arr.push_back(tool);} } diff --git a/src/parametric_programs.cpp b/src/parametric_programs.cpp index 1ad2f5f..ed26f58 100644 --- a/src/parametric_programs.cpp +++ b/src/parametric_programs.cpp @@ -269,7 +269,10 @@ void requireNoDependants(const Document& d,const V& root,const V& owned){ }; // Skeleton source is text; a quoted program-owned name in it is a dependency. if(const auto* skeleton=root.find("skeleton")){const auto source=skeleton->dump();for(const auto& n:names)if(source.find(n)!=std::string::npos)fail("DEPENDANTS","Skeleton source references program-owned "+n+"; edit the Skeleton first, or detach the program");} - for(const auto& kv:root.obj){if(kv.first=="parametric_programs"||kv.first=="skeleton")continue; + // Saved configurations contain labels and numeric inputs, never references + // to generated feature identities. A label matching a feature is not a user + // of that feature and must not block an atomic program re-run. + for(const auto& kv:root.obj){if(kv.first=="parametric_programs"||kv.first=="design_variants"||kv.first=="skeleton")continue; const bool rows=std::any_of(std::begin(kOwned),std::end(kOwned),[&](const char* c){return kv.first==c;}); if(rows&&kv.second.t==V::Arr){for(const auto& row:kv.second.arr)if(!names.count(get(row,"name").asStr()))scan(row,"",kv.first+":"+get(row,"name").asStr());} else scan(kv.second,kv.first,kv.first);} diff --git a/src/serialize.cpp b/src/serialize.cpp index 6acaf48..e2ca719 100644 --- a/src/serialize.cpp +++ b/src/serialize.cpp @@ -1,6 +1,7 @@ #include "ark/design_containers.hpp" #include "ark/parametric_components.hpp" #include "ark/parametric_programs.hpp" +#include "ark/design_variants.hpp" #include "ark/design_disciplines.hpp" #include "ark/cad_import.hpp" // ARK-Point :: serialize.cpp — document persistence over arkjson. @@ -668,6 +669,8 @@ std::string documentToJson(const Document& doc,bool includeAudit,bool includeHis if(!doc.manufacturingPlans.isNull()){validateManufacturingPlans(doc);r.set("manufacturing_plans",doc.manufacturingPlans);r.set("version",Value::makeNum(53));} if(extendedTransmissionDocument(doc))r.set("version",Value::makeNum(54)); if(!doc.parametricPrograms.isNull()){validateParametricPrograms(doc.parametricPrograms);r.set("parametric_programs",doc.parametricPrograms);r.set("version",Value::makeNum(55));} + if(!doc.designVariants.isNull()){validateDesignVariants(doc.designVariants);r.set("design_variants",doc.designVariants);r.set("version",Value::makeNum(56));} + for(const auto& drawing:doc.drawings)if(drawing.find("geometric_tolerances")){r.set("version",Value::makeNum(56));break;} if(includeAudit&&includeHistory)iterationPersist(r,doc); canonicalDocumentKeys(r); std::string serialized=r.dump(); @@ -678,7 +681,7 @@ std::string documentToJson(const Document& doc,bool includeAudit,bool includeHis static bool documentFromValue(Value& v,Document& doc,std::string* err){ auto fail=[&](const std::string& m){ if(err)*err=m; return false; }; if(v.t!=Value::Obj) return fail("root must be object"); - if(auto ver=v.find("version"); ver && (ver->t!=Value::Num || !std::isfinite(ver->num)||ver->num!=std::floor(ver->num)||ver->num<1||ver->num>55)) + if(auto ver=v.find("version"); ver && (ver->t!=Value::Num || !std::isfinite(ver->num)||ver->num!=std::floor(ver->num)||ver->num<1||ver->num>56)) return fail("unsupported document version"); Value history;std::string historyError;if(!iterationExpand(v,history,historyError))return fail(historyError); if(const auto* nodes=v.find("assembly");nodes&&nodes->t==Value::Arr)for(const auto& node:nodes->arr)if(const auto* pattern=node.find("pattern");pattern&&pattern->find("carry_frame")){ @@ -941,6 +944,8 @@ static bool documentFromValue(Value& v,Document& doc,std::string* err){ std::string manufacturingError;if(!validateManufacturingRoutes(nd,manufacturingError))return fail(manufacturingError); if(const auto* sheets=v.find("schematics"))nd.schematics=*sheets;try{validateDesignDisciplines(nd);if(requiresDesignDisciplines054B(nd)&&(!v.find("version")||v.find("version")->num<52))return fail("Classification and schematics require document version 52");}catch(const std::exception& error){return fail(error.what());} if(const auto* programs=v.find("parametric_programs")){const auto* version=v.find("version");if(!version||version->num<55)return fail("Embedded parametric programs require document version 55");try{validateParametricPrograms(*programs);nd.parametricPrograms=*programs;}catch(const std::exception& error){return fail(error.what());}} + if(const auto* variants=v.find("design_variants")){const auto* version=v.find("version");if(!version||version->num<56)return fail("Saved design variants require document version 56");try{validateDesignVariants(*variants);nd.designVariants=*variants;}catch(const std::exception& error){return fail(error.what());}} + for(const auto& drawing:nd.drawings)if(drawing.find("geometric_tolerances")){const auto* version=v.find("version");if(!version||version->num<56)return fail("Geometric tolerances require document version 56");} if(const auto* plans=v.find("manufacturing_plans")){const auto* version=v.find("version");if(!version||version->num<53)return fail("Manufacturing plans require document version 53");nd.manufacturingPlans=*plans;try{validateManufacturingPlans(nd);}catch(const std::exception& error){return fail(error.what());}} if(extendedTransmissionDocument(nd)){const auto* version=v.find("version");if(!version||version->num<54)return fail("Extended transmission mates require document version 54");} if(history.t!=Value::Null){if(!iterationValidate(nd,history,historyError))return fail(historyError);nd.iterationHistory=std::move(history);} diff --git a/src/view/action_icons_selftest.inl b/src/view/action_icons_selftest.inl index 51b629a..432e70d 100644 --- a/src/view/action_icons_selftest.inl +++ b/src/view/action_icons_selftest.inl @@ -1,7 +1,7 @@ const u64 revision=g_session.revision,epoch=g_documentEpoch; const int originalW=winW,originalH=winH,originalModule=g_toolModule;const bool originalDock=g_assistantDockOpen; auto failure=[&](const std::string& detail){std::ofstream(shotPath+".action-icons-test.log")<<"FAIL: "< actions{58,357,585,586,587,590,549,152,153,154,650,659,687,710,730,731,732,750,755}; + const std::vector actions{58,357,585,586,587,590,549,152,153,154,650,659,687,710,730,731,732,750,755,49960,49920,49921,49922,49940,49941,49942}; HMENU menu=CreatePopupMenu();for(int action:actions)AppendMenuA(menu,MF_STRING,(UINT_PTR)action,"Action icon");decorateMenu(menu); for(size_t i=0;i& r){ {auto& more=r[459];for(float x:{.24f,.5f,.76f})circle(more,x,.5f,.06f);} {auto& library=r[484];rect(library,.14f,.2f,.14f,.64f);rect(library,.32f,.2f,.14f,.64f);closed(library,{{.52f,.26f},{.65f,.22f},{.82f,.8f},{.69f,.84f}});line(library,.1f,.88f,.9f,.88f);} {auto& grid=r[579];for(float v:{.3f,.5f,.7f}){line(grid,v,.14f,v,.86f);line(grid,.14f,v,.86f,v);}} + {auto& library=r[49960];for(float x:{.16f,.56f})for(float y:{.16f,.56f})rect(library,x,y,.28f,.28f);} + {auto& config=r[49920];for(float y:{.25f,.5f,.75f})line(config,.14f,y,.86f,y);for(auto p:{std::pair{.34f,.25f},{.66f,.5f},{.46f,.75f}})rect(config,p.first-.06f,p.second-.08f,.12f,.16f);} + {auto& compare=r[49921];cube(compare,.28f,.5f,.38f);cube(compare,.72f,.5f,.38f);} + {auto& explore=r[49922];line(explore,.16f,.84f,.16f,.16f);line(explore,.16f,.84f,.86f,.84f);poly(explore,{{.25f,.68f},{.43f,.49f},{.61f,.58f},{.81f,.23f}});for(auto p:{std::pair{.25f,.68f},{.43f,.49f},{.61f,.58f},{.81f,.23f}})circle(explore,p.first,p.second,.04f);} + {auto& compare=r[49940];rect(compare,.14f,.16f,.44f,.54f);rect(compare,.42f,.3f,.44f,.54f);} + {auto& repair=r[49941];cube(repair,.4f,.4f,.5f);pencil(repair,.5f,.5f,.35f);} + {auto& hide=r[49942];rect(hide,.18f,.22f,.64f,.56f);line(hide,.15f,.85f,.85f,.15f);} // Configurations: one part shown as three stacked variants with a selected front. {auto& configs=r[44080];rect(configs,.34f,.14f,.52f,.4f);poly(configs,{{.24f,.62f},{.24f,.24f},{.34f,.24f}});poly(configs,{{.14f,.72f},{.14f,.34f},{.24f,.34f}}); poly(configs,{{.14f,.72f},{.14f,.86f},{.66f,.86f},{.66f,.54f}});check(configs,.6f,.34f,.22f);} diff --git a/src/view/async_authoring_051a.inl b/src/view/async_authoring_051a.inl index a336dc7..e695504 100644 --- a/src/view/async_authoring_051a.inl +++ b/src/view/async_authoring_051a.inl @@ -3,16 +3,16 @@ static arkjson::Value prepareAuthoringWithProgress(const arkjson::Value& args){ const auto captured=std::chrono::steady_clock::now();const auto epoch=g_objectDocumentEpoch; g_authoringWorker->start(g_doc,g_session.revision,epoch,args);g_progressTiming030.captureMs=realtimeMs030(captured); HDC hdc=GetDC(g_window);if(!hdc){g_authoringWorker->cancel();auto result=g_authoringWorker->take();if(result)return AsyncAuthoringWorker::publish(std::move(*result),g_session,g_objectDocumentEpoch);return g_session.completePreparedApply(args,nullptr);} - struct Finish {HDC dc;~Finish(){g_preparingEdit=false;g_cameraDrag.active=false;ReleaseCapture();ReleaseDC(g_window,dc);if(g_busyClosePending){g_busyClosePending=false;PostMessage(g_window,WM_CLOSE,0,0);}}} finish{hdc}; + struct Finish {HDC dc;~Finish(){g_preparingEdit=false;g_cameraDrag.active=false;ReleaseCapture();ReleaseDC(g_window,dc);invalidateStudioWindowsAfterWork();if(g_busyClosePending){g_busyClosePending=false;PostMessage(g_window,WM_CLOSE,0,0);}}} finish{hdc}; g_preparingEdit=true;g_busyStarted=std::chrono::steady_clock::now();g_busyLabel="Preparing edit / drawing remains interactive";g_componentDragIntent={}; {std::lock_guard lock(g_busyProgressMutex);g_busyFeatureProgress={};} std::optional completed; for(;;){ if(g_closing||(g_authoringExternalCancel&&g_authoringExternalCancel()))g_authoringWorker->cancel(); - MSG message{};while(PeekMessageA(&message,nullptr,0,0,PM_REMOVE)){ + MSG message{};for(unsigned pumped=0;pumped<256&&PeekMessageA(&message,nullptr,0,0,PM_REMOVE);++pumped){ if(message.message==WM_QUIT){g_busyClosePending=true;g_authoringWorker->cancel();continue;} if(message.hwnd==g_window){TranslateMessage(&message);DispatchMessageA(&message);++g_busyPumpCount;} - else if(message.message==WM_PAINT&&message.hwnd)ValidateRect(message.hwnd,nullptr); + else if(message.message==WM_PAINT&&message.hwnd)RedrawWindow(message.hwnd,nullptr,nullptr,RDW_VALIDATE|RDW_NOINTERNALPAINT|RDW_NOERASE); } if((completed=g_authoringWorker->take()))break; const auto progress=g_authoringWorker->progress();{std::lock_guard lock(g_busyProgressMutex);g_busyFeatureProgress={progress.feature,progress.name,progress.index,progress.total,progress.completed,progress.reused};} diff --git a/src/view/component_library_067g.inl b/src/view/component_library_067g.inl new file mode 100644 index 0000000..0383864 --- /dev/null +++ b/src/view/component_library_067g.inl @@ -0,0 +1,62 @@ +// Local reusable authored recipes, deliberately separate from the STEP catalog. +namespace component_library_067g { +using V=arkjson::Value; +struct State {HWND window=nullptr,search=nullptr,kind=nullptr,list=nullptr;HFONT font=nullptr,title=nullptr;std::string directory,error;V catalog,thumbnail;int selected=-1;bool updating=false;}; +static State state; +static std::function testHook; +static const V& get(const V& v,const char* key){static V nil;const auto* p=v.find(key);return p?*p:nil;} +static std::string input(HWND w){int length=GetWindowTextLengthW(w);std::wstring text((size_t)length+1,0);GetWindowTextW(w,text.data(),length+1);const int size=WideCharToMultiByte(CP_UTF8,0,text.data(),length,nullptr,0,nullptr,nullptr);std::string out((size_t)size,0);if(size)WideCharToMultiByte(CP_UTF8,0,text.data(),length,out.data(),size,nullptr,nullptr);return out;} +static void select(){state.thumbnail={};state.selected=(int)SendMessage(state.list,LB_GETCURSEL,0,0);state.error.clear();if(state.selected>=0&&(size_t)state.selected0)args.set("kind",V::makeStr(kind==1?"part":"assembly"));state.catalog=callSessionWithProgress("component_library",args,[args]{return parametricComponentLibrary(args);});state.updating=true;SendMessage(state.list,LB_RESETCONTENT,0,0);for(const auto& row:get(state.catalog,"components").arr){const auto label=get(row,"name").str+" / r"+std::to_string((int)get(row,"revision").num)+" / "+get(row,"category").str;SendMessageW(state.list,LB_ADDSTRING,0,(LPARAM)bomWide(label).c_str());}state.updating=false;if(!get(state.catalog,"components").arr.empty())SendMessage(state.list,LB_SETCURSEL,0,0);select();} +static void folder(){std::vector fields{{"Component library folder",state.directory}};if(!editFields("Open component library","Choose a local folder of .arkprt and .arktop recipes. Subfolders act as categories; search also matches public parameter names.",fields))return;state.directory=trimField(fields[0].value);refresh();} +static void prepare(bool update){if(g_busy)throw std::runtime_error("Wait for the current model operation");if(state.selected<0||(size_t)state.selected>=get(state.catalog,"components").arr.size())throw std::runtime_error("Select a component first");const V row=get(state.catalog,"components").arr[state.selected];const u64 revision=g_session.revision,epoch=g_documentEpoch; + std::vector installed;for(const auto& entry:g_doc.parametricComponents.arr)if(!update||get(get(entry,"package"),"component_id").str==get(row,"component_id").str)installed.push_back(get(entry,"namespace").str); + if(update&&installed.empty())throw std::runtime_error("This component identity is not installed in the project"); + std::vector fields{{"Namespace",update?installed.front():"component",false,installed},{"Public parameter overrides (JSON)","{}"}}; + if(!editFields(update?"Review component update":"Insert library component","Only declared public parameters can be overridden. The chosen file is pinned by its reviewed digest.",fields))return; + if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Project changed; prepare again");V overrides;if(!arkjson::parse(fields[1].value,overrides)||overrides.t!=V::Obj)throw std::runtime_error("Overrides must be a numeric JSON object"); + // Refuse a changed file instead of silently choosing a new catalog revision. + if(parametricComponentHash(loadParametricComponent(get(row,"path").str))!=get(row,"sha256").str)throw std::runtime_error("Library file changed; refresh the catalog before preparing"); + V args=V::makeObj();args.set("action",V::makeStr("prepare"));args.set("mode",V::makeStr(update?"update":"insert"));args.set("path",get(row,"path"));args.set("expected_source_sha256",get(row,"sha256"));args.set("namespace",V::makeStr(trimField(fields[0].value)));args.set("overrides",overrides);args.set("expected_revision",V::makeNum((double)revision));auto response=runTool("parametric_components",args);if(g_error)return;const auto candidate=get(response,"structuredContent");if(!candidate.find("candidate_id"))throw std::runtime_error("Exact component preview returned no candidate"); + std::vector review{{"Checked candidate",containerReviewText(candidate)}};if(!editFields("Review exact component candidate","Apply this checked revision to the current project. Other installed copies keep their pinned revision.",review,true,"Apply",nullptr,true))return; + if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Project changed during review; prepare again");V apply=V::makeObj();apply.set("candidate_id",get(candidate,"candidate_id"));apply.set("expected_revision",V::makeNum((double)revision));runTool("doc_apply",apply);if(!g_error){frameScene();g_status="Library component applied / exact reviewed candidate";} +} +static void layout(){RECT r{};GetClientRect(state.window,&r);MoveWindow(state.search,22,76,std::max(200L,r.right-410),29,TRUE);MoveWindow(state.kind,r.right-370,76,140,200,TRUE);MoveWindow(GetDlgItem(state.window,3),r.right-214,76,90,29,TRUE);MoveWindow(GetDlgItem(state.window,4),r.right-116,76,94,29,TRUE);const int left=std::max(300L,r.right*45/100);MoveWindow(state.list,22,122,left-32,r.bottom-196,TRUE);MoveWindow(GetDlgItem(state.window,5),left+20,r.bottom-60,170,34,TRUE);MoveWindow(GetDlgItem(state.window,6),left+204,r.bottom-60,180,34,TRUE);InvalidateRect(state.window,nullptr,FALSE);} +static void paint(HDC dc){RECT r{};GetClientRect(state.window,&r);bomFill(dc,r,bomBg);bomLabel(dc,L"Parametric component library",{22,14,r.right-22,45},state.title,bomWhite);bomLabel(dc,bomWide(state.directory),{22,46,r.right-22,69},state.font,bomMuted);const int left=std::max(300L,r.right*45/100);RECT preview{left+20,122,r.right-22,std::min(r.bottom-175,430L)};bomFill(dc,preview,bomPanelBg,8); + const auto& lines=get(state.thumbnail,"lines");if(!lines.arr.empty()){auto pen=CreatePen(PS_SOLID,1,RGB(188,197,207));auto old=SelectObject(dc,pen);const double scale=std::min(preview.right-preview.left,preview.bottom-preview.top)/256.;const double x=(preview.left+preview.right)/2.-128*scale,y=(preview.top+preview.bottom)/2.-128*scale;for(const auto& line:lines.arr){MoveToEx(dc,(int)(x+line.arr[0].num*scale),(int)(y+line.arr[1].num*scale),nullptr);LineTo(dc,(int)(x+line.arr[2].num*scale),(int)(y+line.arr[3].num*scale));}SelectObject(dc,old);DeleteObject(pen);} + if(state.selected>=0&&(size_t)state.selectedptMinTrackSize={960,640};return 0;} + if(m==WM_PAINT){PAINTSTRUCT p{};auto dc=BeginPaint(w,&p);paint(dc);EndPaint(w,&p);return 0;}if(m==WM_PRINTCLIENT){paint((HDC)wp);return 0;} + if(m==WM_COMMAND){try{const int id=LOWORD(wp);if(id==3||(id==2&&HIWORD(wp)==CBN_SELCHANGE))refresh();else if(id==4)folder();else if(id==5)prepare(false);else if(id==6)prepare(true);else if(id==7&&HIWORD(wp)==LBN_SELCHANGE&&!state.updating)select();}catch(const std::exception& e){state.error=e.what();InvalidateRect(w,nullptr,FALSE);}return 0;} + if(m==WM_CLOSE){DestroyWindow(w);return 0;}if(m==WM_DESTROY){DeleteObject(state.font);DeleteObject(state.title);state.window=nullptr;return 0;}return DefWindowProcW(w,m,wp,lp); +} +static void open(){if(state.window){ShowWindow(state.window,SW_RESTORE);SetForegroundWindow(state.window);return;}if(g_busy)throw std::runtime_error("Wait for the current model operation");if(state.directory.empty()){wchar_t documents[MAX_PATH]{};SHGetFolderPathW(nullptr,CSIDL_PERSONAL,nullptr,SHGFP_TYPE_CURRENT,documents);const auto bytes=std::filesystem::path(documents).u8string();state.directory=std::string(bytes.begin(),bytes.end())+"/ARK/Components";} + WNDCLASSW wc{};wc.lpfnWndProc=procedure;wc.hInstance=GetModuleHandle(nullptr);wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.lpszClassName=L"ARKComponentLibrary067G";RegisterClassW(&wc);auto w=CreateWindowExW(WS_EX_APPWINDOW,wc.lpszClassName,L"ARK / Parametric component library",WS_OVERLAPPEDWINDOW,110,70,1120,760,g_window,nullptr,wc.hInstance,nullptr);if(!w)throw std::runtime_error("Cannot open component library");layout();ShowWindow(w,SW_SHOW);try{refresh();}catch(const std::exception& e){state.error=e.what();}UpdateWindow(w);if(testHook)testHook(w); +} +} +static bool componentLibraryAction067G(int id){if(id!=49960)return false;component_library_067g::open();return true;} +static int testComponentLibrary067G(const std::string& shotPath){ + using namespace component_library_067g; + auto verify=[](bool ok,const std::string& message){if(!ok)throw std::runtime_error(message);}; + auto json=[&](const char* text){V value;verify(arkjson::parse(text,value),"Library fixture JSON");return value;}; + auto apply=[&](const char* text){V args=json(text);args.set("expected_revision",V::makeNum((double)g_session.revision));runTool("doc_apply",args);verify(!g_error,g_status);}; + const bool previousBusyTest=g_busyTestMode; + try{ + g_busyTestMode=true;g_session=AgentSession{};++g_documentEpoch;rebuildScene(); + apply(R"({"commands":[{"op":"param.set","name":"width","expr":60},{"op":"feature.add","type":"native_solid","name":"Mounting plate","native":{"op":"box"},"p":{"width":"width","depth":36,"height":6}}]})"); + const auto folder=std::filesystem::absolute(std::filesystem::path(shotPath).parent_path()/("library-fixture-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())));std::filesystem::create_directories(folder); + V definition=json(R"({"kind":"part","feature":1,"name":"Adjustable mounting plate","parameters":["width"],"interfaces":[]})"); + const auto first=folder/"mount-r1.arkprt";saveParametricComponent(makeParametricComponent(g_doc,definition),first.string()); + apply(R"({"commands":[{"op":"feature.edit","id":1,"p":{"height":8}}]})");definition.set("previous_path",V::makeStr(first.string()));const auto second=folder/"mount-r2.arkprt";saveParametricComponent(makeParametricComponent(g_doc,definition),second.string()); + g_session=AgentSession{};++g_documentEpoch;rebuildScene();state.directory=folder.string();componentLibraryAction067G(49960);verify(state.window&&get(state.catalog,"components").arr.size()==2,"Library browser catalog missing revisions");verify(!get(state.thumbnail,"lines").arr.empty(),"Selected component thumbnail missing"); + const auto before=g_session.revision;SetWindowTextW(state.search,L"absent");SendMessage(state.window,WM_COMMAND,3,0);verify(get(state.catalog,"components").arr.empty(),"Search failed to filter");SetWindowTextW(state.search,L"width");SendMessage(state.window,WM_COMMAND,3,0);verify(get(state.catalog,"components").arr.size()==2&&g_session.revision==before,"Public-parameter search mutated design"); + UpdateWindow(state.window);bomCapture(state.window,shotPath+".library.png");verify(std::filesystem::is_regular_file(shotPath+".library.png"),"Library capture missing"); + g_dialogSmoke=3;g_dialogOverrideQueue={{"mount","{\"width\":72}"}};SendMessage(state.window,WM_COMMAND,5,0);g_dialogSmoke=0;verify(state.error.empty()&&!g_error&&g_doc.parametricComponents.arr.size()==1,"Library insert: "+state.error+" / "+g_status);verify(g_doc.getParam("mount__width")==72,"Library public parameter override missing"); + SendMessage(state.list,LB_SETCURSEL,1,0);SendMessage(state.window,WM_COMMAND,MAKEWPARAM(7,LBN_SELCHANGE),0);g_dialogSmoke=3;g_dialogOverrideQueue={{"mount","{}"}};SendMessage(state.window,WM_COMMAND,6,0);g_dialogSmoke=0;verify(state.error.empty()&&!g_error&&get(get(g_doc.parametricComponents.arr.front(),"package"),"revision").num==2,"Library explicit update failed: "+state.error+" / "+g_status); + SetWindowPos(state.window,nullptr,0,0,960,640,SWP_NOMOVE|SWP_NOZORDER);UpdateWindow(state.window);bomCapture(state.window,shotPath+".library-compact.png");DestroyWindow(state.window);g_busyTestMode=previousBusyTest;return 0; + }catch(const std::exception& e){g_dialogSmoke=0;g_dialogOverrideQueue.clear();g_busyTestMode=previousBusyTest;if(state.window)DestroyWindow(state.window);fprintf(stderr,"Component library 067G: %s\n",e.what());return 1676;} +} diff --git a/src/view/design_review_067g.inl b/src/view/design_review_067g.inl new file mode 100644 index 0000000..f925b63 --- /dev/null +++ b/src/view/design_review_067g.inl @@ -0,0 +1,46 @@ +// 067G revision comparison and explicitly reviewed feature correction. +namespace design_review_067 { +using V=arkjson::Value; +struct State {std::vector before,after;u64 revision=~u64{},epoch=~u64{};bool active=false,dirty=false;HWND report=nullptr,edit=nullptr;std::string description;}; +static State state; +static const V& field(const V& v,const char* key){static V nil;const auto* p=v.find(key);return p?*p:nil;} +static void appendMesh(std::vector& out,const Mesh& mesh,const Mat4& world){ + if(out.size()+mesh.idx.size()*6>12000000)throw std::runtime_error("Revision overlay exceeds display capacity; narrow the review before displaying it"); + // Drop coplanar triangle diagonals in the display only. The exact producer + // data and the revision comparison remain unchanged. + struct Edge {u32 a=0,b=0;Vec3 normal;unsigned count=0;bool crease=false;}; + std::unordered_map edges;edges.reserve(mesh.idx.size()); + auto point=[&](u32 i){if((size_t)i*3+2>=mesh.pos.size())throw std::runtime_error("Invalid derived display mesh");return Vec3{mesh.pos[i*3],mesh.pos[i*3+1],mesh.pos[i*3+2]};}; + for(size_t t=0;t+2 lines(const Document& doc,const std::set& ids){std::vector out;std::vector placements;std::string error;if(doc.assembly.empty()){const auto consumed=consumedFeatureInputs(doc);for(const auto& b:doc.evalBodies)if(ids.count(b.id)&&!consumed.count(b.id))placements.push_back({0,b.id,"",Mat4::identity(),true});}else if(!resolveAssembly(doc,placements,error))throw std::runtime_error(error);for(const auto& p:placements)if(p.visible&&ids.count(p.feature))for(const auto& b:doc.evalBodies)if(b.id==p.feature)appendMesh(out,b.tessellate(doc.tessOpt),p.world);return out;} +static void overlay(const Document& before,const Document& after,const std::set& ids){auto a=lines(before,ids),b=lines(after,ids);state.before=std::move(a);state.after=std::move(b);state.revision=g_session.revision;state.epoch=g_documentEpoch;state.active=state.dirty=true;} +static LRESULT CALLBACK procedure(HWND w,UINT msg,WPARAM wp,LPARAM lp){ + if(msg==WM_CREATE){state.edit=CreateWindowExW(WS_EX_CLIENTEDGE,L"EDIT",L"",WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL|ES_MULTILINE|ES_READONLY|ES_AUTOVSCROLL|ES_AUTOHSCROLL,12,12,750,480,w,(HMENU)1,GetModuleHandle(nullptr),nullptr);SendMessage(state.edit,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),TRUE);return 0;} + if(msg==WM_SIZE){RECT r{};GetClientRect(w,&r);MoveWindow(state.edit,12,12,std::max(50L,r.right-24),std::max(40L,r.bottom-24),TRUE);return 0;} + if(msg==WM_CLOSE){DestroyWindow(w);return 0;}if(msg==WM_DESTROY){state.report=state.edit=nullptr;return 0;}return DefWindowProcW(w,msg,wp,lp); +} +static void report(const std::string& text){state.description=text;if(!state.report){WNDCLASSW wc{};wc.lpfnWndProc=procedure;wc.hInstance=GetModuleHandle(nullptr);wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);wc.lpszClassName=L"ARKDesignReview067G";RegisterClassW(&wc);state.report=CreateWindowExW(WS_EX_APPWINDOW,wc.lpszClassName,L"ARK / Revision review",WS_OVERLAPPEDWINDOW,100,100,850,580,g_window,nullptr,wc.hInstance,nullptr);}SetWindowTextW(state.edit,bomWide(text).c_str());ShowWindow(state.report,SW_SHOW);UpdateWindow(state.report);} +static std::string summary(const V& diff){ + std::ostringstream out; + out<<"REVISION COMPARISON\r\nBefore: "< "< "< "< "< "< "< ids;for(const auto& row:field(diff,"features").arr)if(field(row,"status").asStr()!="unchanged")ids.insert((u64)field(row,"id").num);auto source=std::make_shared(g_doc);auto work=std::async(std::launch::async,[source,id]{auto before=std::make_unique();iterationRestore(*source,id,*before);before->recompute();return before;});while(work.wait_for(std::chrono::milliseconds(10))!=std::future_status::ready){MSG message{};for(int drained=0;drained<32&&PeekMessage(&message,nullptr,0,0,PM_REMOVE);++drained){if(message.message==WM_QUIT){PostQuitMessage((int)message.wParam);break;}TranslateMessage(&message);DispatchMessage(&message);}}auto before=work.get();if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Document changed while preparing overlay; compare again");overlay(*before,g_doc,ids);report(summary(diff));g_status="Revision overlay / orange before / cyan after / Hide review overlay closes it";} +static void compareDialog(){const auto history=iterationInfo(g_doc);const auto baseline=field(history,"baseline_id").asStr();if(baseline.empty())throw std::runtime_error("Make a saved authoring edit first; this document has no retained revisions");std::vector choices;std::vector ids;for(const auto& n:field(history,"nodes").arr){ids.push_back(field(n,"id").asStr());choices.push_back(field(n,"id").asStr().substr(0,12)+" / "+field(n,"tool").asStr());}ids.push_back(baseline);choices.push_back(baseline.substr(0,12)+" / initial state");std::vector fields{{"Before revision",choices.size()>1?choices[1]:choices[0],false,choices}};if(!editFields("Compare retained revision","Compare to the current design. No restore or document edit is performed.",fields))return;auto found=std::find(choices.begin(),choices.end(),fields[0].value);if(found==choices.end())throw std::runtime_error("Choose a retained revision");compare(ids[(size_t)(found-choices.begin())]);} +static void repairDialog(){const auto revision=g_session.revision,epoch=g_documentEpoch;V request=V::makeObj();request.set("action",V::makeStr("diagnose"));request.set("expected_revision",V::makeNum((double)revision));auto response=runTool("design_review",request);if(g_error)return;V diagnostics=field(response,"structuredContent");const auto failures=field(diagnostics,"failures");if(failures.arr.empty()){g_status="No failed feature or retained single-feature edit at this revision / use Failure report for other rejected operations";return;}std::vector choices;for(const auto& row:failures.arr)choices.push_back("#"+std::to_string((u64)field(row,"id").num)+" / "+field(row,"name").asStr()+(row.find("failure_id")?" / rejected "+field(row,"failure_id").asStr().substr(0,8):""));std::vector choose{{"Failed feature",choices.front(),false,choices}};if(!editFields("Repair failed feature","Choose the failed operation to inspect its error, dimensions and dependencies.",choose))return;auto it=std::find(choices.begin(),choices.end(),choose[0].value);if(it==choices.end())throw std::runtime_error("Choose a failed feature");const auto row=failures.arr[(size_t)(it-choices.begin())];std::vector fields;fields.push_back({"Error",field(row,"error").asStr()});std::vector names;for(const auto& kv:field(row,"parameters").obj){names.push_back(kv.first);fields.push_back({"Dimension / "+kv.first,kv.second.asStr()});}const auto inputIndex=fields.size();fields.push_back({"Earlier dependency IDs (JSON)",field(row,"inputs").dump()});const auto nativeIndex=fields.size();fields.push_back({"Native reference recipe (JSON)",field(row,"native").dump()});fields.push_back({"Available earlier dependencies",field(row,"earlier_dependencies").dump()});if(!editFields("Repair / explicit correction","Correct only the intended expressions or references. Preview validates the full design; Apply follows a separate review.",fields))return;if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Document changed; inspect the failure again");V command=row.find("attempted_command")?field(row,"attempted_command"):V::makeObj(),p=field(command,"p");if(p.t!=V::Obj)p=V::makeObj();command.set("op",V::makeStr("feature.edit"));command.set("id",field(row,"id"));for(size_t i=0;i>{{inputIndex,"inputs"},{nativeIndex,"native"}})if(fields[spec.first].value!=field(row,spec.second).dump()){V value;if(!arkjson::parse(fields[spec.first].value,value))throw std::runtime_error("Correction JSON is invalid");command.set(spec.second,value);}V args=V::makeObj();args.set("action",V::makeStr("prepare_repair"));args.set("expected_revision",V::makeNum((double)revision));args.set("source_sha256",field(diagnostics,"source_sha256"));args.set("id",field(row,"id"));args.set("command",command);if(row.find("failure_id"))args.set("failure_id",field(row,"failure_id"));auto prepared=runTool("design_review",args);if(g_error)return;const auto candidate=field(prepared,"structuredContent");const auto candidateId=field(candidate,"candidate_id").asStr();if(candidateId.empty())throw std::runtime_error("Repair preview returned no reviewed candidate");auto transfer=g_session.takePreparedCandidate(candidateId);if(!transfer)throw std::runtime_error("Repair preview expired");std::set ids{(u64)field(row,"id").num};for(const auto& id:field(row,"dependents").arr)ids.insert((u64)id.num);overlay(g_doc,transfer->document(),ids);g_session.adoptPreparedCandidate(std::move(*transfer),revision);std::vector review{{"Checked correction",containerReviewText(candidate)}};if(!editFields("Review feature repair","The exact candidate has been checked. Orange is the old display, cyan is the corrected candidate.",review,true,"Apply",nullptr,true))return;if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Repair preview became stale; inspect again");V apply=V::makeObj();apply.set("candidate_id",V::makeStr(candidateId));apply.set("expected_revision",V::makeNum((double)revision));runTool("doc_apply",apply);state.active=false;if(!g_error)g_status="Reviewed repair applied / editable sources and dependents retained";} +} +static bool designReviewAction067(int id){if(id<49940||id>49942)return false;if(id==49940)design_review_067::compareDialog();else if(id==49941)design_review_067::repairDialog();else{design_review_067::state.active=false;g_status="Revision overlay hidden";}return true;} +static void drawDesignReview067(){using namespace design_review_067;if(!state.active)return;if(state.revision!=g_session.revision||state.epoch!=g_documentEpoch){state.active=false;return;}static GLuint vao[2]{},vbo[2]{};static GLsizei count[2]{};if(!vao[0]){glGenVertexArrays(2,vao);glGenBuffers(2,vbo);for(int i=0;i<2;++i){glBindVertexArray(vao[i]);glBindBuffer(GL_ARRAY_BUFFER,vbo[i]);glEnableVertexAttribArray(0);glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,12,nullptr);}}if(state.dirty){const std::vector* lines[]{&state.before,&state.after};for(int i=0;i<2;++i){glBindBuffer(GL_ARRAY_BUFFER,vbo[i]);glBufferData(GL_ARRAY_BUFFER,(GLsizeiptr)(lines[i]->size()*sizeof(float)),lines[i]->data(),GL_STATIC_DRAW);count[i]=(GLsizei)lines[i]->size()/3;}state.dirty=false;}glViewport(viewX,winH-viewY-viewH,viewW,viewH);glDisable(GL_DEPTH_TEST);glEnable(GL_BLEND);glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);glUseProgram(pSketch);const auto m=cameraProjection()*cameraView();float vp[16];for(int i=0;i<16;++i)vp[i]=(float)m.m[i];glUniformMatrix4fv(glGetUniformLocation(pSketch,"vp"),1,GL_FALSE,vp);for(int i=0;i<2;++i){glBindVertexArray(vao[i]);if(i==0)glUniform4f(glGetUniformLocation(pSketch,"tint"),1,.47f,.13f,.5f);else glUniform4f(glGetUniformLocation(pSketch,"tint"),.1f,.85f,.92f,.65f);glDrawArrays(GL_LINES,0,count[i]);}glViewport(0,0,winW,winH);} diff --git a/src/view/design_review_selftest_067g.inl b/src/view/design_review_selftest_067g.inl new file mode 100644 index 0000000..fd0e412 --- /dev/null +++ b/src/view/design_review_selftest_067g.inl @@ -0,0 +1,27 @@ +{ + using V=arkjson::Value; + struct BusyGuard {bool old=g_busyTestMode;BusyGuard(){g_busyTestMode=true;}~BusyGuard(){g_busyTestMode=old;}} busyGuard; + auto check=[](bool pass,const std::string& reason){if(!pass)throw std::runtime_error(reason);}; + auto json=[](const std::string& text){V value;if(!arkjson::parse(text,value))throw std::runtime_error("Review fixture JSON");return value;}; + auto apply=[&](const std::string& commands){V args=V::makeObj();args.set("commands",json(commands));args.set("expected_revision",V::makeNum((double)g_session.revision));runTool("doc_apply",args);check(!g_error,g_status);}; + auto capture=[&](const std::string& suffix){target=tTarget;dist=tDist;yaw=tYaw;pitch=tPitch;g_swap=false;drawFrame(hdc);glFinish();Image image;image.w=winW;image.h=winH;image.px.resize((size_t)winW*winH*3);std::vector raw(image.px.size());glPixelStorei(GL_PACK_ALIGNMENT,1);glReadBuffer(GL_BACK);glReadPixels(0,0,winW,winH,GL_RGB,GL_UNSIGNED_BYTE,raw.data());for(int y=0;y pixels((size_t)w*h*4);const bool read=GetDIBits(memory,bitmap,0,h,pixels.data(),&info,DIB_RGB_COLORS)!=0;DeleteObject(bitmap);DeleteDC(memory);ReleaseDC(window,screen);check(painted&&read,"Native comparison report capture failed");Image image;image.w=w;image.h=h;image.px.resize((size_t)w*h*3);for(size_t i=0;i<(size_t)w*h;++i){image.px[i*3]=pixels[i*4+2];image.px[i*3+1]=pixels[i*4+1];image.px[i*3+2]=pixels[i*4];}check(writePNG((shotPath+".report.png").c_str(),image),"Report PNG failed");}; + try{ + g_doc=Document{};g_path="Design review fixture.ark";g_toolModule=0;g_assistantDockOpen=false;++g_documentEpoch;g_session.revision=0;rebuildScene();layout(); + apply(R"([{"op":"param.set","name":"width","expr":"30"},{"op":"feature.add","type":"native_solid","name":"Review block","native":{"op":"box"},"p":{"width":"width","depth":25,"height":18}}])"); + const auto id=design_review_067::field(iterationInfo(g_doc),"head_id").asStr(); + apply(R"([{"op":"param.set","name":"width","expr":"45"}])");frameScene(); + const auto before=documentToJson(g_doc);const auto revision=g_session.revision; + const auto history=iterationInfo(g_doc);std::string choice; + for(const auto& n:design_review_067::field(history,"nodes").arr)if(design_review_067::field(n,"id").asStr()==id)choice=id.substr(0,12)+" / "+design_review_067::field(n,"tool").asStr(); + g_dialogSmoke=3;g_dialogOverrideQueue.push_back({choice});uiAction(49940);g_dialogSmoke=0; + check(!g_error&&design_review_067::state.active&&!design_review_067::state.before.empty()&&!design_review_067::state.after.empty(),"Compare action did not create both geometry overlays");check(IsWindow(design_review_067::state.report)!=FALSE,"Selectable comparison report did not open");check(documentToJson(g_doc)==before&&g_session.revision==revision,"UI comparison changed authoring");capture(".comparison.png");captureReport(); + uiAction(49942);check(!design_review_067::state.active,"Hide overlay action failed"); + V failed=json(R"({"commands":[{"op":"feature.edit","id":1,"p":{"width":-10,"depth":35}}]})");failed.set("expected_revision",V::makeNum((double)revision));runTool("doc_apply",failed);check(g_error&&documentToJson(g_doc)==before,"A rejected edit must retain the valid design before guided repair"); + V diagnosticRequest=V::makeObj();diagnosticRequest.set("action",V::makeStr("diagnose"));diagnosticRequest.set("expected_revision",V::makeNum((double)revision));const auto diagnosticResponse=runTool("design_review",diagnosticRequest);check(!g_error,g_status);const auto diagnostics=design_review_067::field(diagnosticResponse,"structuredContent");const auto row=design_review_067::field(diagnostics,"failures").arr.at(0);std::vector correction{design_review_067::field(row,"error").asStr()};for(const auto& kv:design_review_067::field(row,"parameters").obj)correction.push_back(kv.first=="width"?"48":kv.second.asStr());correction.push_back(design_review_067::field(row,"inputs").dump());correction.push_back(design_review_067::field(row,"native").dump());correction.push_back(design_review_067::field(row,"earlier_dependencies").dump()); + g_dialogSmoke=3;g_dialogOverrideQueue.push_back({"#1 / Review block / rejected "+design_review_067::field(row,"failure_id").asStr().substr(0,8)});g_dialogOverrideQueue.push_back(correction);uiAction(49941);g_dialogSmoke=0; + check(!g_error,g_status);check(g_session.revision==revision+1&&g_doc.find(1)->p["width"]=="48"&&g_doc.find(1)->get("depth")=="35","Repair controls failed to publish the reviewed correction once");check(!g_doc.lastResults.empty()&&g_doc.lastResults.front().ok,"Repair left failed geometry");frameScene();capture(".repaired.png"); + if(design_review_067::state.report)DestroyWindow(design_review_067::state.report); + std::fprintf(stderr,"Design review UI passed: compare selection, retained source, both overlays, report window, hide, diagnostic form and reviewed repair publication\n"); + }catch(const std::exception& error){g_dialogSmoke=0;std::fprintf(stderr,"Design review UI failed: %s\n",error.what());return 4670;} +} diff --git a/src/view/design_variants.inl b/src/view/design_variants.inl new file mode 100644 index 0000000..44383ec --- /dev/null +++ b/src/view/design_variants.inl @@ -0,0 +1,31 @@ +// 067G native configurator. Preview triangles are display-only; comparisons use +// exact B-rep metrics returned by the same tool used by agents. +namespace design_variants_view_067g { +using V=arkjson::Value; +struct State {HWND window=nullptr,program=nullptr,parameters=nullptr,variants=nullptr,name=nullptr,results=nullptr,status=nullptr;HFONT font=nullptr;std::string ns;V values,report;u64 revision=0,epoch=0;bool busy=false;std::vector parameterNames,savedNames,programNames;int selectedResult=0;}; +static State state; +static const V& field(const V& v,const char* key){static V none;const auto* p=v.find(key);return p?*p:none;} +static std::wstring wide(const std::string& s){return bomWide(s);} +static std::string windowText(HWND w){int n=GetWindowTextLengthW(w);std::wstring value(n+1,L'\0');GetWindowTextW(w,value.data(),n+1);value.resize(n);if(value.empty())return {};int bytes=WideCharToMultiByte(CP_UTF8,0,value.data(),n,nullptr,0,nullptr,nullptr);std::string out(bytes,'\0');WideCharToMultiByte(CP_UTF8,0,value.data(),n,out.data(),bytes,nullptr,nullptr);return out;} +static void message(const std::string& s){SetWindowTextW(state.status,wide(s).c_str());g_status=s;} +static void add(HWND list,const std::string& s,bool combo=false){SendMessageW(list,combo?CB_ADDSTRING:LB_ADDSTRING,0,(LPARAM)wide(s).c_str());} +static const V* program(){for(const auto& p:g_doc.parametricPrograms.arr)if(field(p,"namespace").str==state.ns)return &p;return nullptr;} +static void fillParameters(){SendMessageW(state.parameters,LB_RESETCONTENT,0,0);state.parameterNames.clear();const auto* p=program();if(!p)return;for(const auto& parameter:field(field(*p,"program"),"parameters").obj){state.parameterNames.push_back(parameter.first);const auto& spec=parameter.second;std::string label=parameter.first+" = "+field(state.values,parameter.first.c_str()).dump()+" "+field(spec,"unit").asStr();if(spec.find("min")||spec.find("max"))label+=" ["+(spec.find("min")?field(spec,"min").dump():"-")+" .. "+(spec.find("max")?field(spec,"max").dump():"-")+"]";add(state.parameters,label);}if(!state.parameterNames.empty())SendMessageW(state.parameters,LB_SETCURSEL,0,0);} +static void fillSaved(){SendMessageW(state.variants,LB_RESETCONTENT,0,0);state.savedNames.clear();for(const auto& v:g_doc.designVariants.arr)if(field(v,"namespace").str==state.ns){state.savedNames.push_back(field(v,"name").str);const auto* p=program();add(state.variants,field(v,"name").str+(p&&field(v,"program_sha256").str==field(*p,"program_sha256").str?"":" [source changed]"));}} +static void refresh(){state.revision=g_session.revision;state.epoch=g_documentEpoch;state.report={};state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);SendMessageW(state.program,CB_RESETCONTENT,0,0);state.programNames.clear();int selected=0;for(const auto& p:g_doc.parametricPrograms.arr){if(field(p,"namespace").str==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(field(p,"namespace").str);add(state.program,field(p,"namespace").str+" / "+field(p,"name").str,true);}for(const auto& v:g_doc.designVariants.arr){const auto ns=field(v,"namespace").str;if(std::find(state.programNames.begin(),state.programNames.end(),ns)==state.programNames.end()){if(ns==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(ns);add(state.program,ns+" / program removed",true);}}if(!state.programNames.empty()){SendMessageW(state.program,CB_SETCURSEL,selected,0);state.ns=state.programNames[selected];state.values=program()?field(*program(),"values"):V::makeObj();}else{state.ns.clear();state.values=V::makeObj();}fillParameters();fillSaved();message(state.ns.empty()?"Install a starter program to create an editable family.":"Edit parameters, preview, save named configurations, then compare or explore.");InvalidateRect(state.window,nullptr,TRUE);} +static V tool(V a){a.set("namespace",V::makeStr(state.ns));a.set("expected_revision",V::makeNum(double(state.revision)));auto r=runTool("design_variants",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());return field(r,"structuredContent");} +static V args(const char* action){V a=V::makeObj();a.set("action",V::makeStr(action));return a;} +static void commit(const V& preview){V a=V::makeObj();a.set("expected_revision",V::makeNum(double(state.revision)));a.set("candidate_id",field(preview,"candidate_id"));const auto r=runTool("doc_apply",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());refresh();} +static void showReport(V report){state.report=std::move(report);state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);for(const auto& row:field(state.report,"results").arr){const auto& m=field(row,"metrics");std::string label=field(row,"name").str+" | ";if(!field(row,"valid").b)label+="FAILED: "+field(row,"error").str;else{label+=field(m,"width_mm").dump()+" x "+field(m,"depth_mm").dump()+" x "+field(m,"height_mm").dump()+" mm | "+field(m,"volume_mm3").dump()+" mm3 | ";label+=field(m,"mass_available").b?field(m,"mass_kg").dump()+" kg":"mass: assign density";if(!field(row,"feasible").b)label+=" | outside constraints";}add(state.results,label);}if(!field(state.report,"ranked_indices").arr.empty())state.selectedResult=(int)field(state.report,"ranked_indices").arr[0].num;SendMessageW(state.results,LB_SETCURSEL,state.selectedResult,0);message(std::to_string((int)field(state.report,"attempted").num)+" evaluated / "+std::to_string((int)field(state.report,"failed").num)+" failed. Exact metrics; sampled thumbnails are display only.");InvalidateRect(state.window,nullptr,TRUE);} +static void editParameter(){int i=(int)SendMessageW(state.parameters,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.parameterNames.size())return;const auto name=state.parameterNames[i];std::string value=field(state.values,name.c_str()).dump();if(!editText(("Parameter: "+name).c_str(),value))return;bool ok=false;double parsed=evalExpr(trimField(value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(parsed))throw std::runtime_error("Enter a finite numeric value");state.values.set(name,V::makeNum(parsed));fillParameters();SendMessageW(state.parameters,LB_SETCURSEL,i,0);message("Value staged; Preview validates the program and exact geometry before Apply.");} +static void loadSaved(){if(!program())throw std::runtime_error("The program was removed. This saved configuration can be inspected or deleted, but cannot be applied.");int i=(int)SendMessageW(state.variants,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.savedNames.size())return;for(const auto& v:g_doc.designVariants.arr)if(field(v,"namespace").str==state.ns&&field(v,"name").str==state.savedNames[i]){if(field(v,"program_sha256").str!=field(*program(),"program_sha256").str)throw std::runtime_error("Program source changed. Review each parameter before creating a new configuration.");state.values=field(v,"values");SetWindowTextW(state.name,wide(state.savedNames[i]).c_str());fillParameters();message("Saved values staged. Preview checks geometry; Apply publishes the selected configuration.");break;}} +static void starter(){const V examples=parametricProgramExamples();std::vector fields{{"Example",field(examples.arr.front(),"id").str},{"Namespace","family"}};for(const auto& example:examples.arr)fields[0].choices.push_back(field(example,"id").str);if(!editFields("New parametric family","Installs an editable example with exact native features. Existing designs are preserved.",fields))return;const auto ns=trimField(fields[1].value);V a=V::makeObj();a.set("action",V::makeStr("prepare"));a.set("mode",V::makeStr("install"));a.set("namespace",V::makeStr(ns));a.set("expected_revision",V::makeNum(double(state.revision)));for(const auto& example:examples.arr)if(field(example,"id").str==fields[0].value)a.set("program",field(example,"program"));const auto r=runTool("parametric_program",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());commit(field(r,"structuredContent"));state.ns=ns;refresh();} +static void explore(){const auto* p=program();if(!p)throw std::runtime_error("Install a program first");std::vector fields{{"Parameter",state.parameterNames.empty()?"":state.parameterNames.front()},{"Trial values (comma separated)",""},{"Minimize","volume_mm3"},{"Maximum width mm (optional)",""},{"Maximum depth mm (optional)",""},{"Maximum height mm (optional)",""},{"Maximum mass kg (optional)",""},{"Clearance feature A (optional)",""},{"Clearance feature B (optional)",""},{"Minimum pair gap mm (optional)",""}};fields[0].choices=state.parameterNames;fields[2].choices={"volume_mm3","mass_kg","width_mm","depth_mm","height_mm"};if(!state.parameterNames.empty()){const auto& spec=field(field(*p,"program"),"parameters").obj.front().second;const auto& value=field(state.values,state.parameterNames.front().c_str());fields[1].value=(spec.find("min")?field(spec,"min").dump():value.dump())+", "+value.dump()+", "+(spec.find("max")?field(spec,"max").dump():value.dump());}if(!editFields("Explore parameter alternatives","Every explicit value is evaluated with the exact kernel. Program assertions and entered limits govern feasibility. Failed trials remain visible. No structural or manufacturing claim.",fields))return;V a=args("explore"),axes=V::makeObj(),values=V::makeArr(),constraints=V::makeObj();std::istringstream in(fields[1].value);std::string word;while(std::getline(in,word,',')){bool ok=false;const double number=evalExpr(trimField(word),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(number))throw std::runtime_error("Trial values must be finite numbers");values.arr.push_back(V::makeNum(number));}axes.set(fields[0].value,values);const char* keys[]={"width_mm","depth_mm","height_mm","mass_kg"};for(int i=0;i<4;++i)if(!trimField(fields[i+3].value).empty()){bool ok=false;const auto value=evalExpr(trimField(fields[i+3].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(value))throw std::runtime_error("Limits must be finite numbers");V range=V::makeObj();range.set("max",V::makeNum(value));constraints.set(keys[i],range);}if(!trimField(fields[7].value).empty()||!trimField(fields[8].value).empty()||!trimField(fields[9].value).empty()){bool ok=false;const double gap=evalExpr(trimField(fields[9].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(gap)||gap<0||trimField(fields[7].value).empty()||trimField(fields[8].value).empty())throw std::runtime_error("Enter both program feature names and a nonnegative minimum gap");V pairs=V::makeArr(),pair=V::makeObj();pair.set("a",V::makeStr(trimField(fields[7].value)));pair.set("b",V::makeStr(trimField(fields[8].value)));pair.set("min_mm",V::makeNum(gap));pairs.arr.push_back(pair);a.set("clearance_pairs",pairs);}a.set("values",state.values);a.set("axes",axes);a.set("constraints",constraints);a.set("objective",V::makeStr(fields[2].value));a.set("thumbnails",V::makeBool(true));showReport(tool(a));} +static void action(int id){if(state.busy)return;state.busy=true;g_error=false;try{if(id!=1&&state.epoch!=g_documentEpoch)throw std::runtime_error("Document changed. Refresh before editing.");if(id!=1&&state.revision!=g_session.revision)throw std::runtime_error("Model revision changed. Refresh and review values before continuing.");if(id==1)refresh();else if(id==2)starter();else if(id==3)editParameter();else if(id==4){V a=args("evaluate");a.set("name",V::makeStr("Staged"));a.set("values",state.values);a.set("thumbnails",V::makeBool(true));showReport(tool(a));}else if(id==5){V a=args("prepare");a.set("values",state.values);commit(tool(a));message("Configuration applied. Undo restores the previous editable source.");}else if(id==6){V a=args("save");a.set("name",V::makeStr(trimField(windowText(state.name))));a.set("values",state.values);const V staged=state.values;commit(tool(a));state.values=staged;fillParameters();message("Named configuration saved in the document; Save the .ark to retain it on disk.");}else if(id==7)loadSaved();else if(id==8){int i=(int)SendMessageW(state.variants,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.savedNames.size())throw std::runtime_error("Select a saved variant");V a=args("remove");a.set("name",V::makeStr(state.savedNames[i]));const V staged=state.values;commit(tool(a));state.values=staged;fillParameters();}else if(id==9){V a=args("evaluate");a.set("thumbnails",V::makeBool(true));showReport(tool(a));}else if(id==10)explore();else if(id==11){int i=(int)SendMessageW(state.results,LB_GETCURSEL,0,0);const auto& rows=field(state.report,"results").arr;if(i<0||i>=(int)rows.size()||!field(rows[i],"valid").b)throw std::runtime_error("Select a valid evaluated result");state.values=field(rows[i],"values");SetWindowTextW(state.name,wide(field(rows[i],"name").str).c_str());fillParameters();message("Result values staged. Save a named variant or Apply to the model.");}}catch(const std::exception& e){g_error=true;message(e.what());}state.busy=false;InvalidateRect(state.window,nullptr,TRUE);} +static void text(HDC dc,RECT r,const std::string& s,COLORREF color=RGB(225,228,232)){SetTextColor(dc,color);SetBkMode(dc,TRANSPARENT);DrawTextW(dc,wide(s).c_str(),-1,&r,DT_LEFT|DT_WORDBREAK|DT_END_ELLIPSIS);} +static void thumbnail(HDC dc,RECT r,const V& row){auto brush=CreateSolidBrush(RGB(39,43,49));FillRect(dc,&r,brush);DeleteObject(brush);RECT label{r.left+10,r.top+8,r.right-8,r.top+44};text(dc,label,field(row,"name").asStr(),RGB(255,174,94));const auto& triangles=field(row,"display_triangles").arr;if(triangles.empty()){RECT empty{r.left+10,r.top+50,r.right-10,r.bottom-10};text(dc,empty,field(row,"valid").b?"No display mesh available":field(row,"error").asStr());return;}double loX=1e300,loY=1e300,hiX=-1e300,hiY=-1e300;auto point=[](const V& t,int i){return std::pair{.866*(t.arr[i].num-t.arr[i+1].num),.5*(t.arr[i].num+t.arr[i+1].num)-t.arr[i+2].num};};for(const auto& tri:triangles)if(tri.arr.size()==9)for(int j=0;j<9;j+=3){auto p=point(tri,j);loX=std::min(loX,p.first);hiX=std::max(hiX,p.first);loY=std::min(loY,p.second);hiY=std::max(hiY,p.second);}double scale=std::min((r.right-r.left-28.)/std::max(1.,hiX-loX),(r.bottom-r.top-66.)/std::max(1.,hiY-loY));const double x=r.left+(r.right-r.left-(hiX-loX)*scale)*.5-loX*scale,y=r.top+45+(r.bottom-r.top-55-(hiY-loY)*scale)*.5-loY*scale;auto pen=CreatePen(PS_SOLID,1,RGB(140,154,170));auto fill=CreateSolidBrush(RGB(80,91,107));auto oldP=SelectObject(dc,pen),oldB=SelectObject(dc,fill);std::vector ordered;for(const auto& tri:triangles)if(tri.arr.size()==9)ordered.push_back(&tri);auto depth=[](const V* tri){double z=0;for(const auto& coordinate:tri->arr)z+=coordinate.num;return z;};std::stable_sort(ordered.begin(),ordered.end(),[&](const V* a,const V* b){return depth(a)1e-12?std::clamp((.3*nx+.5*ny+.8*nz)/length,0.,1.):0.;const int shade=(int)(65+65*light);auto faceBrush=CreateSolidBrush(RGB(shade,shade+11,shade+27));auto priorBrush=SelectObject(dc,faceBrush);Polygon(dc,pts,3);SelectObject(dc,priorBrush);DeleteObject(faceBrush);}SelectObject(dc,oldP);SelectObject(dc,oldB);DeleteObject(pen);DeleteObject(fill);} +static void layout(){RECT r{};GetClientRect(state.window,&r);const int w=r.right,h=r.bottom,left=350;MoveWindow(state.program,18,48,w-262,300,TRUE);MoveWindow(GetDlgItem(state.window,2),w-232,47,105,28,TRUE);MoveWindow(GetDlgItem(state.window,1),w-117,47,98,28,TRUE);MoveWindow(state.parameters,18,112,left-36,180,TRUE);MoveWindow(GetDlgItem(state.window,3),18,300,102,28,TRUE);MoveWindow(GetDlgItem(state.window,4),128,300,92,28,TRUE);MoveWindow(GetDlgItem(state.window,5),228,300,104,28,TRUE);MoveWindow(state.name,18,363,left-36,25,TRUE);MoveWindow(GetDlgItem(state.window,6),18,397,left-36,28,TRUE);MoveWindow(state.variants,18,465,left-36,std::max(80,h-565),TRUE);MoveWindow(GetDlgItem(state.window,7),18,h-92,147,28,TRUE);MoveWindow(GetDlgItem(state.window,8),176,h-92,156,28,TRUE);MoveWindow(state.results,left+10,112,w-left-28,134,TRUE);MoveWindow(GetDlgItem(state.window,9),left+10,256,150,28,TRUE);MoveWindow(GetDlgItem(state.window,10),left+170,256,150,28,TRUE);MoveWindow(GetDlgItem(state.window,11),left+330,256,174,28,TRUE);MoveWindow(state.status,18,h-51,w-36,42,TRUE);} +static LRESULT CALLBACK procedure(HWND w,UINT m,WPARAM wp,LPARAM lp){if(m==WM_CREATE){state.window=w;state.font=CreateFontW(-15,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");auto control=[&](const wchar_t* type,const wchar_t* title,DWORD style,int id){HWND c=CreateWindowExW(type==std::wstring(L"EDIT")||type==std::wstring(L"LISTBOX")?WS_EX_CLIENTEDGE:0,type,title,WS_CHILD|WS_VISIBLE|style,0,0,100,25,w,(HMENU)(INT_PTR)id,GetModuleHandle(nullptr),nullptr);SendMessageW(c,WM_SETFONT,(WPARAM)state.font,TRUE);return c;};state.program=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL,20);state.parameters=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL|WS_HSCROLL,21);state.name=control(L"EDIT",L"Standard",ES_AUTOHSCROLL,22);state.variants=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL,23);state.results=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL|WS_HSCROLL,24);SendMessageW(state.results,LB_SETHORIZONTALEXTENT,2000,0);state.status=control(L"STATIC",L"",0,25);const wchar_t* labels[]={L"Refresh",L"New family",L"Edit value",L"Preview",L"Apply",L"Save named variant",L"Load values",L"Delete variant",L"Compare saved",L"Explore values",L"Use selected result"};for(int i=0;i<11;++i)control(L"BUTTON",labels[i],BS_PUSHBUTTON|WS_TABSTOP,i+1);SetTimer(w,1,500,nullptr);return 0;}if(m==WM_SIZE){layout();InvalidateRect(w,nullptr,TRUE);return 0;}if(m==WM_GETMINMAXINFO){auto* info=(MINMAXINFO*)lp;info->ptMinTrackSize={960,680};return 0;}if(m==WM_COMMAND){const int id=LOWORD(wp),event=HIWORD(wp);if(id<=11&&event==BN_CLICKED){action(id);return 0;}if(id==20&&event==CBN_SELCHANGE){int i=(int)SendMessageW(state.program,CB_GETCURSEL,0,0);if(i>=0&&i<(int)state.programNames.size()){state.ns=state.programNames[i];refresh();}return 0;}if(id==21&&event==LBN_DBLCLK){action(3);return 0;}if(id==23&&event==LBN_DBLCLK){action(7);return 0;}if(id==24&&event==LBN_SELCHANGE){state.selectedResult=(int)SendMessageW(state.results,LB_GETCURSEL,0,0);InvalidateRect(w,nullptr,TRUE);return 0;}}if(m==WM_TIMER){if(!state.busy&&(state.revision!=g_session.revision||state.epoch!=g_documentEpoch))message("Model changed. Refresh and review the current parameters before applying a configuration.");return 0;}if(m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(w,&ps);RECT r{};GetClientRect(w,&r);auto brush=CreateSolidBrush(RGB(27,30,35));FillRect(dc,&r,brush);DeleteObject(brush);auto old=SelectObject(dc,state.font);text(dc,{18,14,r.right-18,40},"Design variants / configure, compare and explore",RGB(255,174,94));text(dc,{18,87,330,108},"Program parameters");text(dc,{360,87,r.right-18,108},"Exact comparison results");text(dc,{18,337,330,360},"Variant name");text(dc,{18,439,330,462},"Saved configurations");const auto& rows=field(state.report,"results").arr;const int count=std::min(3,(int)rows.size()),cardWidth=(r.right-378)/3;int start=std::max(0,std::min(state.selectedResult-1,(int)rows.size()-count));for(int i=0;i=25","message":"Width needs 25 mm for the interface"},{"emit":{"op":"feature.add","type":"native_solid","name":"Base","native":{"op":"box"},"p":{"width":"{width}","depth":24,"height":"{height}"}}}]}})"); + stage("install-program");install.set("expected_revision",V::makeNum(double(g_session.revision)));const auto prepared=runTool("parametric_program",install);check(!field(prepared,"isError").b,prepared.dump());V apply=V::makeObj();apply.set("candidate_id",field(field(prepared,"structuredContent"),"candidate_id"));apply.set("expected_revision",V::makeNum(double(g_session.revision)));runTool("doc_apply",apply);check(!g_error,g_status); + stage("open-window"); + openDesignVariantsWindow();check(state.window&&state.parameterNames.size()==2,"Configurator controls and parameters missing"); + auto press=[&](int id){SendMessageW(state.window,WM_COMMAND,MAKEWPARAM(id,BN_CLICKED),(LPARAM)GetDlgItem(state.window,id));}; + auto save=[&](const wchar_t* name,double width){state.values.set("width",V::makeNum(width));fillParameters();SetWindowTextW(state.name,name);press(6);check(!g_error,g_status);check(field(state.values,"width").num==width,"Saving metadata must preserve staged configuration values");}; + stage("save-compact");save(L"Compact",25);stage("save-standard");save(L"Standard",40);stage("save-reinforced");save(L"Reinforced",70);check(g_doc.designVariants.arr.size()==3,"Three configurations did not persist"); + stage("compare"); + const auto revision=g_session.revision;press(9);check(field(state.report,"results").arr.size()==3,"Compare did not produce three rows");check(g_session.revision==revision,"Comparison published geometry");for(const auto& row:field(state.report,"results").arr)check(field(row,"valid").b&&!field(row,"display_triangles").arr.empty(),"Missing exact alternative or thumbnail"); + auto capture=[&](const char* suffix){InvalidateRect(state.window,nullptr,TRUE);UpdateWindow(state.window);bomCapture(state.window,shotPath+suffix);check(std::filesystem::is_regular_file(shotPath+suffix),"Variants capture missing");};capture(".compare.png"); + stage("apply-undo");SendMessageW(state.results,LB_SETCURSEL,0,0);press(11);check(field(state.values,"width").num==25,"Result values not loaded");press(5);check(field(field(g_doc.parametricPrograms.arr[0],"values"),"width").num==25,"Apply did not configure exact program"); + runTool("doc_undo",V::makeObj());check(field(field(g_doc.parametricPrograms.arr[0],"values"),"width").num==40,"Undo did not restore model");const auto afterUndo=g_session.revision;press(5);check(g_session.revision==afterUndo,"Stale configurator state published");press(1); + // Exercise the real numeric dialog and staged preview button. + stage("numeric-dialog");int widthIndex=0;for(size_t i=0;i=0&&r.right<=client.right&&r.top>=0&&r.bottom<=client.bottom,"Configurator control outside window: "+std::to_string(id));} + const auto persisted=shotPath+".variants.ark";check(saveDocument(g_doc,persisted.c_str()),"Save variants document failed");Document loaded;std::string error;check(loadDocument(persisted.c_str(),loaded,&error),error);check(loaded.designVariants.arr.size()==3,"Saved variant configurations lost on reopen"); + DestroyWindow(state.window);g_busyTestMode=oldBusyTest;std::ofstream(shotPath+".variants-test.log")<<"PASS three named variants, exact preview, comparison thumbnails, apply/undo, stale rejection, numeric edit, exploration failures, compact controls, persistence\n";return 0; + }catch(const std::exception& e){g_dialogSmoke=0;g_dialogOverrideQueue.clear();if(state.window)DestroyWindow(state.window);g_busyTestMode=oldBusyTest;std::ofstream(shotPath+".variants-test.log")<<"FAIL "<128)throw std::runtime_error("This catalog exceeds one 128-command transaction; create selected sheets explicitly");drawingViewportApply(commands,revision,epoch);g_status=std::to_string(commands.arr.size())+" source-linked sheets created"+(unsupported?" / "+std::to_string(unsupported)+" unsupported sources require review":""); } static void drawingViewportTemplateForm(){ - using V=arkjson::Value;auto& state=g_drawingViewport;sheetAssertCurrent(state.sheet);V drawing=sheetAuthored(state.sheet),t=drawing.find("template")?*drawing.find("template"):V::makeObj();std::vector fields{{"Sheet name",state.sheet.name},{"Original template",t.find("id")?sheetText(t,"id"):"ark_precision",false,{"ark_precision","ark_blueprint"}},{"Title",t.find("title")?sheetText(t,"title"):state.sheet.name},{"Drawing number",sheetText(t,"drawing_number")},{"Declared revision label",sheetText(t,"revision_label")},{"Notes",sheetText(t,"notes")},{"Layout",drawing.find("layout")?sheetText(drawing,"layout"):"manual",false,{"auto","manual"}},{"Maximum model scale",sheetNumber(drawing.find("scale")->num)},{"Dimension units",sheetText(drawing,"units"),false,{"mm","in"}},{"Paper width / mm",sheetNumber(drawing.find("paper_mm")->arr[0].num)},{"Paper height / mm",sheetNumber(drawing.find("paper_mm")->arr[1].num)}};const auto revision=state.sheet.revision,epoch=state.sheet.epoch;if(!sheetFields(state.sheet,"Manufacturing sheet template","Editable original vector templates. Model dimensions stay exact; this form does not declare tolerances.",fields))return;for(const auto& existing:g_doc.drawings)if(sheetText(existing,"name")==trimField(fields[0].value)&&sheetText(existing,"name")!=state.sheet.name)throw std::runtime_error("A sheet with that name already exists");drawing.set("name",V::makeStr(trimField(fields[0].value)));t.set("id",V::makeStr(fields[1].value));const char* keys[]={"title","drawing_number","revision_label","notes"};for(int i=0;i<4;++i)t.set(keys[i],V::makeStr(fields[2+i].value));drawing.set("template",t);drawing.set("layout",V::makeStr(fields[6].value));drawing.set("scale",V::makeNum(sheetInput(fields[7].value)));if(sheetText(drawing,"units")!=fields[8].value){auto dims=*drawing.find("dimensions");const double factor=sheetText(drawing,"units")=="mm"?1/25.4:25.4;for(auto& dim:dims.arr)if(auto oldTolerance=dim.find("tolerance")){auto changed=*oldTolerance;changed.set("lower",V::makeNum(oldTolerance->find("lower")->num*factor));changed.set("upper",V::makeNum(oldTolerance->find("upper")->num*factor));changed.set("units",V::makeStr(fields[8].value));dim.set("tolerance",changed);}drawing.set("dimensions",dims);}drawing.set("units",V::makeStr(fields[8].value));drawing.set("paper_mm",sheetPair(sheetInput(fields[9].value),sheetInput(fields[10].value)));sheetApply(state.sheet,drawing,revision,epoch,state.sheet.name);drawingViewportRead(); + using V=arkjson::Value;auto& state=g_drawingViewport;sheetAssertCurrent(state.sheet);V drawing=sheetAuthored(state.sheet),t=drawing.find("template")?*drawing.find("template"):V::makeObj();std::vector fields{{"Sheet name",state.sheet.name},{"Original template",t.find("id")?sheetText(t,"id"):"ark_precision",false,{"ark_precision","ark_blueprint"}},{"Title",t.find("title")?sheetText(t,"title"):state.sheet.name},{"Drawing number",sheetText(t,"drawing_number")},{"Declared revision label",sheetText(t,"revision_label")},{"Notes",sheetText(t,"notes")},{"Layout",drawing.find("layout")?sheetText(drawing,"layout"):"manual",false,{"auto","manual"}},{"Maximum model scale",sheetNumber(drawing.find("scale")->num)},{"Dimension units",sheetText(drawing,"units"),false,{"mm","in"}},{"Paper width / mm",sheetNumber(drawing.find("paper_mm")->arr[0].num)},{"Paper height / mm",sheetNumber(drawing.find("paper_mm")->arr[1].num)}};const auto revision=state.sheet.revision,epoch=state.sheet.epoch;if(!sheetFields(state.sheet,"Manufacturing sheet template","Editable original vector templates. Model dimensions stay exact; this form does not declare tolerances.",fields))return;for(const auto& existing:g_doc.drawings)if(sheetText(existing,"name")==trimField(fields[0].value)&&sheetText(existing,"name")!=state.sheet.name)throw std::runtime_error("A sheet with that name already exists");drawing.set("name",V::makeStr(trimField(fields[0].value)));t.set("id",V::makeStr(fields[1].value));const char* keys[]={"title","drawing_number","revision_label","notes"};for(int i=0;i<4;++i)t.set(keys[i],V::makeStr(fields[2+i].value));drawing.set("template",t);drawing.set("layout",V::makeStr(fields[6].value));drawing.set("scale",V::makeNum(sheetInput(fields[7].value)));if(sheetText(drawing,"units")!=fields[8].value){auto dims=*drawing.find("dimensions");const double factor=sheetText(drawing,"units")=="mm"?1/25.4:25.4;for(auto& dim:dims.arr)if(auto oldTolerance=dim.find("tolerance")){auto changed=*oldTolerance;changed.set("lower",V::makeNum(oldTolerance->find("lower")->num*factor));changed.set("upper",V::makeNum(oldTolerance->find("upper")->num*factor));changed.set("units",V::makeStr(fields[8].value));dim.set("tolerance",changed);}drawing.set("dimensions",dims);if(drawing.find("geometric_tolerances")){V frames=*drawing.find("geometric_tolerances");for(auto& f:frames.arr){f.set("value",V::makeNum(f.find("value")->num*factor));f.set("units",V::makeStr(fields[8].value));}drawing.set("geometric_tolerances",frames);}}drawing.set("units",V::makeStr(fields[8].value));drawing.set("paper_mm",sheetPair(sheetInput(fields[9].value),sheetInput(fields[10].value)));sheetApply(state.sheet,drawing,revision,epoch,state.sheet.name);drawingViewportRead(); } static void drawingViewportSelect(bool dimension){auto& state=g_drawingViewport;sheetAssertCurrent(state.sheet);const auto selectedDrawing=sheetAuthored(state.sheet);const auto& rows=selectedDrawing.find(dimension?"dimensions":"views")->arr;std::vector labels;for(const auto& row:rows)labels.push_back(sheetText(row,"name"));if(labels.empty())throw std::runtime_error(dimension?"Add a dimension first":"Add a view first");std::vector fields{{dimension?"Dimension":"View",labels.front(),false,labels}};if(!sheetFields(state.sheet,dimension?"Select dimension":"Select view","Choose the current source-linked item to edit.",fields))return;for(size_t i=0;istatic void renderDrawingViewport(Re paperLine(8,8,pw-8,8,dr,dg,db);paperLine(8,8,8,ph-8,dr,dg,db);paperLine(pw-8,8,pw-8,ph-8,dr,dg,db);paperLine(8,ph-8,pw-8,ph-8,dr,dg,db);label(blueprint?"ARK / BLUEPRINT ATELIER":"ARK / PRECISION STUDIO",12,11,.63f);for(double xx=48;xxarr){const auto& offset=view.find("authored")->find("offset_mm")->arr;auto rows=[&](const arkjson::Value& edges,bool convention){for(const auto& edge:edges.arr){const bool hidden=sheetText(edge,"visibility")=="hidden",selected=state.selectedSource.t==arkjson::Value::Obj&&edge.find("source")&&drawingViewportSameOccurrence(state.selectedSource,*edge.find("source"));const auto& points=edge.find("display_polyline_mm")->arr;for(size_t i=1;iarr;label(sheetText(view,"name"),offset[0].num+bounds[0].num*scale,offset[1].num-bounds[1].num*scale+16,.46f);} bool declared=false;for(const auto& dimension:state.sheet.report.find("dimensions")->arr){const arkjson::Value* view=nullptr;for(const auto& v:authored.find("views")->arr)if(sheetText(v,"name")==sheetText(dimension,"view"))view=&v;const auto& offset=view->find("offset_mm")->arr,&a=dimension.find("a_mm")->arr,&b=dimension.find("b_mm")->arr,&p=dimension.find("position_mm")->arr;const double ax=offset[0].num+a[0].num*scale,ay=offset[1].num-a[1].num*scale,bx=offset[0].num+b[0].num*scale,by=offset[1].num-b[1].num*scale;auto kind=sheetText(dimension,"kind");if(kind=="extent_horizontal")kind="horizontal";if(kind=="extent_vertical")kind="vertical";auto dimLine=[&](double x1,double y1,double x2,double y2,bool arrow=false){paperLine(x1,y1,x2,y2,dr,dg,db,.8f);if(arrow){const double dx=x2-x1,dy=y2-y1,len=std::hypot(dx,dy);if(len>1e-9)for(int sign:{1,-1}){const double xx=sign==1?x1:x2,yy=sign==1?y1:y2;paperLine(xx+sign*dx/len*2-dy/len*.8,yy+sign*dy/len*2+dx/len*.8,xx,yy,dr,dg,db,.8f);paperLine(xx+sign*dx/len*2+dy/len*.8,yy+sign*dy/len*2-dx/len*.8,xx,yy,dr,dg,db,.8f);}}};if(kind=="horizontal"){dimLine(ax,ay,ax,p[1].num);dimLine(bx,by,bx,p[1].num);dimLine(ax,p[1].num,bx,p[1].num,true);}else if(kind=="vertical"){dimLine(ax,ay,p[0].num,ay);dimLine(bx,by,p[0].num,by);dimLine(p[0].num,ay,p[0].num,by,true);}else dimLine(ax,ay,bx,by,true);std::string value=(kind=="radius"?"R ":kind=="diameter"?"DIA ":"")+sheetNumber(dimension.find("value")->num)+" "+sheetText(dimension,"units");if(auto tolerance=dimension.find("tolerance")){value+=" ["+sheetNumber(tolerance->find("lower")->num)+", +"+sheetNumber(tolerance->find("upper")->num)+"]";declared=true;}label(value,kind=="vertical"?p[0].num+1:(ax+bx)/2-3,kind=="vertical"?(ay+by)/2:p[1].num-5,.49f);} - const double ty=ph-40;paperLine(8,ty,pw-8,ty,dr,dg,db);paperLine(pw*.64,ty,pw*.64,ph-8,dr,dg,db);paperLine(pw*.64,ty+16,pw-8,ty+16,dr,dg,db);label(t&&t->find("title")?sheetText(*t,"title"):state.sheet.name,12,ty+4,.70f,pw*.64-20);label(declared?"Tolerances: declared per dimension":"Tolerances: not declared",12,ty+14,.49f,pw*.64-20);if(t&&t->find("notes"))label(sheetText(*t,"notes"),12,ty+23,.43f,pw*.64-20);label("Scale "+sheetNumber(scale)+" / "+sheetText(authored,"units")+" / r"+std::to_string(state.sheet.revision),pw*.64+4,ty+4,.47f);label(t&&t->find("drawing_number")?sheetText(*t,"drawing_number"):"SOURCE-LINKED SHEET",pw*.64+4,ty+11,.43f);label("REV "+(t&&t->find("revision_label")?sheetText(*t,"revision_label"):"UNDECLARED"),pw*.64+4,ty+19,.47f);label("Select a drawing line to inspect its 3D origin",pw*.64+4,ty+27,.38f);glDisable(GL_SCISSOR_TEST); + if(const auto* frames=authored.find("geometric_tolerances"))for(const auto& f:frames->arr){declared=true;const auto& p=f.find("position_mm")->arr;const auto& tip=f.find("leader_mm")->arr;std::string value=sheetText(f,"characteristic")+" | "+sheetNumber(f.find("value")->num)+" "+sheetText(f,"units");for(const auto& datum:f.find("datums")->arr)value+=" | "+datum.str;const double width=std::max(20.,textWidth(value,.49f*(float)state.zoom)/fit+3),xx=p[0].num,yy=p[1].num;paperLine(xx,yy,xx+width,yy,dr,dg,db);paperLine(xx,yy+7,xx+width,yy+7,dr,dg,db);paperLine(xx,yy,xx,yy+7,dr,dg,db);paperLine(xx+width,yy,xx+width,yy+7,dr,dg,db);const double cx=xx+width/2,cy=yy+3.5,dx=tip[0].num-cx,dy=tip[1].num-cy,attach=std::min(std::abs(dx)>1e-9?width/2/std::abs(dx):1e30,std::abs(dy)>1e-9?3.5/std::abs(dy):1e30);if(attach<1)paperLine(cx+dx*attach,cy+dy*attach,tip[0].num,tip[1].num,dr,dg,db);label(value,xx+1,yy+1,.49f);} + const double ty=ph-40;paperLine(8,ty,pw-8,ty,dr,dg,db);paperLine(pw*.64,ty,pw*.64,ph-8,dr,dg,db);paperLine(pw*.64,ty+16,pw-8,ty+16,dr,dg,db);label(t&&t->find("title")?sheetText(*t,"title"):state.sheet.name,12,ty+4,.70f,pw*.64-20);label(declared?"Tolerances: caller-declared":"Tolerances: not declared",12,ty+14,.49f,pw*.64-20);if(t&&t->find("notes"))label(sheetText(*t,"notes"),12,ty+23,.43f,pw*.64-20);label("Scale "+sheetNumber(scale)+" / "+sheetText(authored,"units")+" / r"+std::to_string(state.sheet.revision),pw*.64+4,ty+4,.47f);label(t&&t->find("drawing_number")?sheetText(*t,"drawing_number"):"SOURCE-LINKED SHEET",pw*.64+4,ty+11,.43f);label("REV "+(t&&t->find("revision_label")?sheetText(*t,"revision_label"):"UNDECLARED"),pw*.64+4,ty+19,.47f);label("Select a drawing line to inspect its 3D origin",pw*.64+4,ty+27,.38f);glDisable(GL_SCISSOR_TEST); } button("<",x+12,y+h-39,44,850);button(">",x+64,y+h-39,44,851);const auto count=state.names.size();auto current=std::find(state.names.begin(),state.names.end(),state.sheet.name)-state.names.begin();std::string footer=state.sheet.name.empty()?"No sheet selected":std::to_string(current+1)+" / "+std::to_string(count)+" "+state.sheet.name+" / "+status;footer+=" / "+sheetNumber(state.zoom*100)+"%";textOut(fitText(footer,.62f,w-254),x+123,y+h-30,.62f,status=="current"?.68f:.94f,status=="current"?.84f:.70f,status=="current"?.91f:.37f);button("Delete",x+w-105,y+h-39,88,859); } diff --git a/src/view/drawing_workspace.inl b/src/view/drawing_workspace.inl index 5aa7802..665c0f2 100644 --- a/src/view/drawing_workspace.inl +++ b/src/view/drawing_workspace.inl @@ -42,6 +42,7 @@ static void sheetDefinitionDialog(DrawingWorkspace& state,bool create){ using V=arkjson::Value;if(!create)sheetAssertCurrent(state);const u64 revision=g_session.revision,epoch=g_documentEpoch;V drawing=create?V::makeObj():sheetAuthored(state);if(!create&&!drawing.find("feature"))throw std::runtime_error("Source recipes and original templates use the integrated viewport Sheet controls");const auto sources=sheetSources();if(sources.empty())throw std::runtime_error("DRAWING_SOURCE_UNSUPPORTED: create one exact solid before starting a drawing");std::vector labels;std::string source=labels.empty()?sources.front().first:"";for(const auto& item:sources){labels.push_back(item.first);if(!create&&drawing.find("feature")->num==(double)item.second)source=item.first;} std::vector fields{{"Drawing name",create?"Drawing "+std::to_string(g_doc.drawings.size()+1):state.name},{"Exact source solid",source,false,labels},{"Dimension units",create?"mm":sheetText(drawing,"units"),false,{"mm","in"}},{"Sheet scale",create?"1":sheetNumber(drawing.find("scale")->num)},{"Paper width / mm",create?"297":sheetNumber(drawing.find("paper_mm")->arr[0].num)},{"Paper height / mm",create?"210":sheetNumber(drawing.find("paper_mm")->arr[1].num)}}; if(!sheetFields(state,create?"New technical drawing":"Edit drawing sheet","Select the exact source. Sheet scale changes presentation; dimensions keep physical units.",fields))return;const auto name=trimField(fields[0].value);for(const auto& existing:g_doc.drawings)if(sheetText(existing,"name")==name&&(create||name!=state.name))throw std::runtime_error("A drawing with that name already exists");u64 sourceId=0;for(const auto& candidate:sources)if(candidate.first==fields[1].value)sourceId=candidate.second;if(!sourceId)throw std::runtime_error("Exact source selection is no longer available");const auto oldUnits=create?fields[2].value:sheetText(drawing,"units");drawing.set("name",V::makeStr(name));drawing.set("feature",V::makeNum((double)sourceId));drawing.set("units",V::makeStr(fields[2].value));drawing.set("scale",V::makeNum(sheetInput(fields[3].value)));drawing.set("paper_mm",sheetPair(sheetInput(fields[4].value),sheetInput(fields[5].value))); + if(!create&&oldUnits!=fields[2].value&&drawing.find("geometric_tolerances")){V frames=*drawing.find("geometric_tolerances");const double factor=oldUnits=="in"?25.4:1./25.4;for(auto& f:frames.arr){f.set("value",V::makeNum(f.find("value")->num*factor));f.set("units",V::makeStr(fields[2].value));}drawing.set("geometric_tolerances",frames);} if(create){V views=V::makeArr(),view=V::makeObj();view.set("name",V::makeStr("Top"));view.set("type",V::makeStr("orthographic"));view.set("direction",V::makeStr("top"));view.set("offset_mm",sheetPair(45,75));views.arr.push_back(view);drawing.set("views",views);drawing.set("dimensions",V::makeArr());} else if(oldUnits!=fields[2].value){V dimensions=*drawing.find("dimensions");for(auto& dimension:dimensions.arr)if(auto tolerance=dimension.find("tolerance")){V changed=*tolerance;const double factor=oldUnits=="mm"?1/25.4:25.4;changed.set("lower",V::makeNum(tolerance->find("lower")->num*factor));changed.set("upper",V::makeNum(tolerance->find("upper")->num*factor));changed.set("units",V::makeStr(fields[2].value));dimension.set("tolerance",changed);}drawing.set("dimensions",dimensions);} sheetApply(state,drawing,revision,epoch,create?"":state.name); @@ -50,7 +51,7 @@ static void sheetViewDialog(DrawingWorkspace& state,bool create){ using V=arkjson::Value;sheetAssertCurrent(state);const u64 revision=state.revision,epoch=state.epoch;V drawing=sheetAuthored(state);if(drawing.find("layout")&&sheetText(drawing,"layout")=="auto"&&state.report.find("presentation")){drawing.set("views",*state.report.find("presentation")->find("views"));drawing.set("dimensions",*state.report.find("presentation")->find("dimensions"));}V views=*drawing.find("views"),view=V::makeObj();const int selected=state.views?sheetChoice(state.views):state.selectedView;if(!create){if(selected<0||(size_t)selected>=views.arr.size())throw std::runtime_error("Select a view first");view=views.arr[(size_t)selected];}const auto oldName=create?"":sheetText(view,"name");std::vector fields{{"View name",create?"View "+std::to_string(views.arr.size()+1):oldName},{"View type",create?state.newViewType:sheetText(view,"type"),false,{"orthographic","section"}},{"Direction",create?"front":sheetText(view,"direction"),false,{"front","back","top","bottom","right","left","isometric"}},{"Paper X / mm",create?"45":sheetNumber(view.find("offset_mm")->arr[0].num)},{"Paper Y / mm",create?"135":sheetNumber(view.find("offset_mm")->arr[1].num)}}; if(drawing.find("layout"))fields.push_back({"Sheet layout",sheetText(drawing,"layout"),false,{"auto","manual"}});if(!sheetFields(state,create?"Add drawing view":"Edit drawing view","Automatic layout derives paper positions; Manual uses X/Y. A section uses explicit source-local or assembly-world coordinates.",fields))return;view.set("name",V::makeStr(trimField(fields[0].value)));view.set("type",V::makeStr(fields[1].value));view.set("direction",V::makeStr(fields[2].value));view.set("offset_mm",sheetPair(sheetInput(fields[3].value),sheetInput(fields[4].value))); view.obj.erase(std::remove_if(view.obj.begin(),view.obj.end(),[](const auto& item){return item.first=="origin_mm";}),view.obj.end());if(fields[1].value=="section"){const auto* prior=!create?views.arr[(size_t)selected].find("origin_mm"):nullptr;std::vector cut{{"Cut origin X / mm",prior?sheetNumber(prior->arr[0].num):"0"},{"Cut origin Y / mm",prior?sheetNumber(prior->arr[1].num):"0"},{"Cut origin Z / mm",prior?sheetNumber(prior->arr[2].num):"0"}};if(!sheetFields(state,"Section plane","The origin is explicit source-local geometry. A plane that misses the solid rejects.",cut))return;V origin=sheetPair(sheetInput(cut[0].value),sheetInput(cut[1].value));origin.arr.push_back(V::makeNum(sheetInput(cut[2].value)));view.set("origin_mm",origin);} - if(create)views.arr.push_back(view);else views.arr[(size_t)selected]=view;drawing.set("views",views);if(drawing.find("layout")){drawing.set("layout",V::makeStr(fields[5].value));if(fields[5].value=="manual"&&state.report.find("presentation"))drawing.set("scale",*state.report.find("presentation")->find("scale"));}if(!create&&oldName!=sheetText(view,"name")){V dims=*drawing.find("dimensions");for(auto& dimension:dims.arr)if(sheetText(dimension,"view")==oldName)dimension.set("view",*view.find("name"));drawing.set("dimensions",dims);}sheetApply(state,drawing,revision,epoch); + if(create)views.arr.push_back(view);else views.arr[(size_t)selected]=view;drawing.set("views",views);if(!create&&drawing.find("geometric_tolerances")){V frames=*drawing.find("geometric_tolerances");for(auto& f:frames.arr)if(sheetText(f,"view")==oldName)f.set("view",*view.find("name"));drawing.set("geometric_tolerances",frames);}if(drawing.find("layout")){drawing.set("layout",V::makeStr(fields[5].value));if(fields[5].value=="manual"&&state.report.find("presentation"))drawing.set("scale",*state.report.find("presentation")->find("scale"));}if(!create&&oldName!=sheetText(view,"name")){V dims=*drawing.find("dimensions");for(auto& dimension:dims.arr)if(sheetText(dimension,"view")==oldName)dimension.set("view",*view.find("name"));drawing.set("dimensions",dims);}sheetApply(state,drawing,revision,epoch); } static void sheetDimensionDialog(DrawingWorkspace& state,bool create){ using V=arkjson::Value;sheetAssertCurrent(state);const u64 revision=state.revision,epoch=state.epoch;V drawing=sheetAuthored(state);if(drawing.find("layout")&&sheetText(drawing,"layout")=="auto"&&state.report.find("presentation")){drawing.set("views",*state.report.find("presentation")->find("views"));drawing.set("dimensions",*state.report.find("presentation")->find("dimensions"));}V dims=*drawing.find("dimensions"),dimension=V::makeObj();const int selected=state.dimensions?(int)SendMessage(state.dimensions,LB_GETCURSEL,0,0):state.selectedDimension;if(!create){if(selected<0||(size_t)selected>=dims.arr.size())throw std::runtime_error("Select a dimension first");dimension=dims.arr[(size_t)selected];} @@ -63,8 +64,20 @@ static void sheetDimensionDialog(DrawingWorkspace& state,bool create){ } static void sheetRemoveElement(DrawingWorkspace& state,bool view){using V=arkjson::Value;sheetAssertCurrent(state);V drawing=sheetAuthored(state),rows=*drawing.find(view?"views":"dimensions");const int selected=view?(state.views?sheetChoice(state.views):state.selectedView):(state.dimensions?(int)SendMessage(state.dimensions,LB_GETCURSEL,0,0):state.selectedDimension);if(selected<0||(size_t)selected>=rows.arr.size())throw std::runtime_error("Select an item first");if(view){if(rows.arr.size()==1)throw std::runtime_error("Keep at least one drawing view");for(const auto& dimension:drawing.find("dimensions")->arr)if(sheetText(dimension,"view")==sheetText(rows.arr[(size_t)selected],"name"))throw std::runtime_error("Remove dimensions attached to this view before removing it");}rows.arr.erase(rows.arr.begin()+selected);drawing.set(view?"views":"dimensions",rows);sheetApply(state,drawing,state.revision,state.epoch);} static void sheetRefreshSource(DrawingWorkspace& state){using V=arkjson::Value;if(state.epoch!=g_documentEpoch)throw std::runtime_error("Project changed; reopen Drawings");V command=V::makeObj(),commands=V::makeArr(),args=V::makeObj();command.set("op",V::makeStr("drawing.refresh"));command.set("name",V::makeStr(state.name));commands.arr.push_back(command);args.set("commands",commands);args.set("expected_revision",V::makeNum((double)state.revision));runTool("doc_apply",args);if(g_error)throw std::runtime_error(g_status);sheetRefreshRead(state);} -static void sheetExport(DrawingWorkspace& state){using V=arkjson::Value;sheetAssertCurrent(state);const auto revision=state.revision,epoch=state.epoch;std::vector fields{{"Drawing format","svg",false,{"svg","json"}}};if(!sheetFields(state,"Export technical drawing","SVG is a sheet presentation preview. JSON retains exact derived curves and dimensions.",fields))return;std::string path=g_drawingExportTestPath;if(path.empty()){wchar_t file[32768]=L"Drawing.svg";OPENFILENAMEW choose{};choose.lStructSize=sizeof choose;choose.hwndOwner=state.window?state.window:g_window;choose.lpstrFilter=fields[0].value=="svg"?L"Drawing SVG\0*.svg\0\0":L"Drawing JSON\0*.json\0\0";choose.lpstrFile=file;choose.nMaxFile=32768;choose.lpstrDefExt=fields[0].value=="svg"?L"svg":L"json";choose.Flags=OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(!GetSaveFileNameW(&choose))return;auto bytes=std::filesystem::path(file).u8string();path.assign(bytes.begin(),bytes.end());}if(epoch!=g_documentEpoch)throw std::runtime_error("Project changed during export setup");V args=V::makeObj();args.set("name",V::makeStr(state.name));args.set("expected_revision",V::makeNum((double)revision));args.set("format",V::makeStr(fields[0].value));args.set("path",V::makeStr(path));runTool("drawing_export",args);if(g_error)throw std::runtime_error(g_status);state.error="Exported "+fields[0].value+" to "+path;if(state.window)InvalidateRect(state.window,nullptr,FALSE);} -static void sheetLayout(DrawingWorkspace& state){RECT r{};GetClientRect(state.window,&r);int x=18;const int widths[]={114,98,91,91,128,128,124,83,72};for(int i=0;i<9;++i){MoveWindow(GetDlgItem(state.window,801+i),x,66,widths[i],32,TRUE);x+=widths[i]+7;}MoveWindow(state.drawings,22,157,230,250,TRUE);MoveWindow(state.views,22,280,230,250,TRUE);MoveWindow(state.dimensions,22,383,230,std::max(90,(int)r.bottom-595),TRUE);MoveWindow(GetDlgItem(state.window,810),22,318,105,28,TRUE);MoveWindow(GetDlgItem(state.window,811),133,318,119,28,TRUE);MoveWindow(GetDlgItem(state.window,812),22,r.bottom-55,230,30,TRUE);for(int i=0;i<3;++i)MoveWindow(GetDlgItem(state.window,813+i),22+i*79,r.bottom-149,72,30,TRUE);state.canvas={274,122,r.right-18,r.bottom-44};if(state.window)InvalidateRect(state.window,nullptr,FALSE);} +static void sheetToleranceDialog(DrawingWorkspace& state){using V=arkjson::Value;sheetAssertCurrent(state);const auto revision=state.revision,epoch=state.epoch;V drawing=sheetAuthored(state);std::vector views;for(const auto& view:drawing.find("views")->arr)views.push_back(sheetText(view,"name")); + std::vector fields{{"Frame name","Tolerance 1"},{"View",views.front(),false,views},{"Characteristic","position",false,{"position","flatness","straightness","circularity","cylindricity","parallelism","perpendicularity","angularity","profile_line","profile_surface","runout","total_runout"}},{"Tolerance (sheet units)","0.1"},{"Datums (comma separated)","A,B"},{"Frame X (paper mm)","100"},{"Frame Y (paper mm)","100"},{"Leader X (paper mm)","80"},{"Leader Y (paper mm)","80"},{"Action","Save",false,{"Save","Remove"}}}; + if(!sheetFields(state,"Geometric tolerance frame","Authored requirement only. Named characteristics are not a certified ISO/ASME symbol layout; datum labels do not measure compliance.",fields))return; + V frames=drawing.find("geometric_tolerances")?*drawing.find("geometric_tolerances"):V::makeArr();const auto name=trimField(fields[0].value);frames.arr.erase(std::remove_if(frames.arr.begin(),frames.arr.end(),[&](const V& f){return sheetText(f,"name")==name;}),frames.arr.end()); + if(fields[9].value=="Save"){V f=V::makeObj(),datums=V::makeArr();std::istringstream input(fields[4].value);std::string datum;while(std::getline(input,datum,','))if(!trimField(datum).empty())datums.arr.push_back(V::makeStr(trimField(datum)));f.set("name",V::makeStr(name));f.set("view",V::makeStr(fields[1].value));f.set("characteristic",V::makeStr(fields[2].value));f.set("value",V::makeNum(sheetInput(fields[3].value)));f.set("units",*drawing.find("units"));f.set("datums",datums);f.set("position_mm",sheetPair(sheetInput(fields[5].value),sheetInput(fields[6].value)));f.set("leader_mm",sheetPair(sheetInput(fields[7].value),sheetInput(fields[8].value)));frames.arr.push_back(f);}drawing.set("geometric_tolerances",frames);sheetApply(state,drawing,revision,epoch); +} +static void sheetExport(DrawingWorkspace& state){using V=arkjson::Value;sheetAssertCurrent(state);const auto revision=state.revision,epoch=state.epoch; + std::vector fields{{"Drawing format","pdf",false,{"pdf","svg","json","dxf"}},{"Sheets","Current sheet",false,{"Current sheet","All sheets (PDF)"}}}; + if(!sheetFields(state,"Export / print technical drawings","PDF keeps paper size and vector presentation. Print at Actual size (100%). All sheets are checked before publication; stale sheets reject the entire export.",fields))return; + const auto format=fields[0].value;std::string path=g_drawingExportTestPath; + if(path.empty()){const auto ext=bomWide(format);std::wstring initial=L"Drawing."+ext;wchar_t file[32768]{};wcsncpy_s(file,initial.c_str(),_TRUNCATE);std::wstring filter=L"Technical drawing";filter.push_back(0);filter+=L"*."+ext;filter.push_back(0);filter.push_back(0);OPENFILENAMEW choose{};choose.lStructSize=sizeof choose;choose.hwndOwner=state.window?state.window:g_window;choose.lpstrFilter=filter.c_str();choose.lpstrFile=file;choose.nMaxFile=32768;choose.lpstrDefExt=ext.c_str();choose.Flags=OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(!GetSaveFileNameW(&choose))return;auto bytes=std::filesystem::path(file).u8string();path.assign(bytes.begin(),bytes.end());} + if(epoch!=g_documentEpoch)throw std::runtime_error("Project changed during export setup");V args=V::makeObj();if(fields[1].value=="All sheets (PDF)"){if(format!="pdf")throw std::runtime_error("All sheets requires PDF");V names=V::makeArr();for(const auto& sheet:g_doc.drawings)names.arr.push_back(*sheet.find("name"));args.set("names",names);}else args.set("name",V::makeStr(state.name));args.set("expected_revision",V::makeNum((double)revision));args.set("format",V::makeStr(format));args.set("path",V::makeStr(path));runTool("drawing_export",args);if(g_error)throw std::runtime_error(g_status);state.error="Exported "+format+" to "+path;if(state.window)InvalidateRect(state.window,nullptr,FALSE); +} +static void sheetLayout(DrawingWorkspace& state){RECT r{};GetClientRect(state.window,&r);int x=18;const int widths[]={114,98,91,91,128,128,124,83,72};for(int i=0;i<9;++i){MoveWindow(GetDlgItem(state.window,801+i),x,66,widths[i],32,TRUE);x+=widths[i]+7;}MoveWindow(state.drawings,22,157,230,250,TRUE);MoveWindow(state.views,22,280,230,250,TRUE);MoveWindow(state.dimensions,22,383,230,std::max(90,(int)r.bottom-595),TRUE);MoveWindow(GetDlgItem(state.window,810),22,318,105,28,TRUE);MoveWindow(GetDlgItem(state.window,811),133,318,119,28,TRUE);MoveWindow(GetDlgItem(state.window,812),22,r.bottom-55,230,30,TRUE);for(int i=0;i<3;++i)MoveWindow(GetDlgItem(state.window,813+i),22+i*79,r.bottom-149,72,30,TRUE);MoveWindow(GetDlgItem(state.window,816),22,r.bottom-111,230,30,TRUE);state.canvas={274,122,r.right-18,r.bottom-44};if(state.window)InvalidateRect(state.window,nullptr,FALSE);} static void sheetPaint(DrawingWorkspace& state,HDC dc){ state.viewRects.clear();state.labelRects.clear(); RECT client{};GetClientRect(state.window,&client);bomFill(dc,client,bomBg);bomLabel(dc,L"Technical drawings",{22,14,400,47},state.title,bomWhite);const auto status=sheetText(state.report,"status");std::string subtitle=state.name.empty()?"Create a sheet from one exact source solid":status=="current"?"CURRENT / source association checked / document r"+std::to_string(state.revision):status=="stale"?"STALE / source changed / Refresh source to rebuild":"INVALID / source or semantic reference unavailable";bomLabel(dc,bomWide(subtitle),{410,17,client.right-18,49},state.font,status=="current"?bomCyan:bomAmber);bomFill(dc,{18,117,258,client.bottom-68},bomPanelBg,8);bomLabel(dc,L"DRAWING SHEET",{22,123,252,148},state.smallFont,bomMuted);bomLabel(dc,L"SOURCE SOLID",{22,197,252,219},state.smallFont,bomMuted);const auto* authored=state.report.find("presentation")?state.report.find("presentation"):state.report.find("authored");bomLabel(dc,bomWide(state.sourceLabel),{22,220,252,246},state.font,bomWhite);bomLabel(dc,L"VIEWS",{22,253,252,278},state.smallFont,bomMuted);bomLabel(dc,L"DIMENSIONS",{22,351,252,378},state.smallFont,bomMuted);bomLabel(dc,bomWide("Display zoom / "+sheetNumber(state.zoom*100)+"% / drag to pan"),{22,client.bottom-189,252,client.bottom-165},state.smallFont,bomMuted); @@ -73,6 +86,7 @@ static void sheetPaint(DrawingWorkspace& state,HDC dc){ const double width=authored->find("paper_mm")->arr[0].num,height=authored->find("paper_mm")->arr[1].num;const double fit=state.zoom*std::min((state.canvas.right-state.canvas.left-40)/width,(state.canvas.bottom-state.canvas.top-40)/height);const int px=state.panX+state.canvas.left+(int)((state.canvas.right-state.canvas.left-width*fit)/2),py=state.panY+state.canvas.top+(int)((state.canvas.bottom-state.canvas.top-height*fit)/2);RECT paper{px,py,px+(int)(width*fit),py+(int)(height*fit)};int saved=SaveDC(dc);IntersectClipRect(dc,state.canvas.left+8,state.canvas.top+8,state.canvas.right-8,state.canvas.bottom-8);bomFill(dc,{paper.left+5,paper.top+6,paper.right+5,paper.bottom+6},RGB(16,17,19));bomFill(dc,paper,RGB(255,255,255));auto font=CreateFontW(-std::max(11,(int)(3*fit)),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");IntersectClipRect(dc,paper.left,paper.top,paper.right,paper.bottom);const double scale=authored->find("scale")->num;auto point=[&](double x,double y){return POINT{px+(LONG)std::lround(x*fit),py+(LONG)std::lround(y*fit)};};auto line=[&](double ax,double ay,double bx,double by,COLORREF color,bool arrow=false){auto a=point(ax,ay),b=point(bx,by);auto pen=CreatePen(PS_SOLID,1,color);auto old=SelectObject(dc,pen);MoveToEx(dc,a.x,a.y,nullptr);LineTo(dc,b.x,b.y);if(arrow){double dx=b.x-a.x,dy=b.y-a.y,len=std::hypot(dx,dy);if(len>1){dx/=len;dy/=len;for(auto tip:{a,b}){double sign=tip.x==a.x&&tip.y==a.y?1:-1;MoveToEx(dc,tip.x+(int)(sign*dx*6-dy*3),tip.y+(int)(sign*dy*6+dx*3),nullptr);LineTo(dc,tip.x,tip.y);LineTo(dc,tip.x+(int)(sign*dx*6+dy*3),tip.y+(int)(sign*dy*6-dx*3));}}}SelectObject(dc,old);DeleteObject(pen);};auto label=[&](const std::string& value,double x,double y,COLORREF color,bool record=false){auto p=point(x,y);if(record){auto text=bomWide(value);SIZE size{};auto old=SelectObject(dc,font);GetTextExtentPoint32W(dc,text.c_str(),(int)wcslen(text.c_str()),&size);SelectObject(dc,old);state.labelRects.push_back({p.x,p.y,p.x+size.cx,p.y+size.cy});}bomLabel(dc,bomWide(value),{p.x,p.y,paper.right-8,p.y+std::max(16,(int)(5*fit))},font,color);}; for(const auto& view:state.report.find("views")->arr){const auto* layout=view.find("authored");const auto& offset=layout->find("offset_mm")->arr;RECT visibleBounds{LONG_MAX,LONG_MAX,LONG_MIN,LONG_MIN};for(bool hidden:{true,false})for(const auto& edge:view.find("edges")->arr){if((sheetText(edge,"visibility")=="hidden")!=hidden)continue;auto pen=CreatePen(hidden?PS_DASH:PS_SOLID,1,hidden?RGB(139,150,160):RGB(44,46,50));auto old=SelectObject(dc,pen);bool first=true;for(const auto& sample:edge.find("display_polyline_mm")->arr){auto p=point(offset[0].num+sample.arr[0].num*scale,offset[1].num-sample.arr[1].num*scale);visibleBounds.left=std::min(visibleBounds.left,p.x);visibleBounds.top=std::min(visibleBounds.top,p.y);visibleBounds.right=std::max(visibleBounds.right,p.x+1);visibleBounds.bottom=std::max(visibleBounds.bottom,p.y+1);if(first)MoveToEx(dc,p.x,p.y,nullptr);else LineTo(dc,p.x,p.y);first=false;}SelectObject(dc,old);DeleteObject(pen);}state.viewRects.push_back(visibleBounds);label(sheetText(view,"name"),offset[0].num,offset[1].num+6,RGB(50,53,57),true);} for(const auto& dimension:state.report.find("dimensions")->arr){const auto name=sheetText(dimension,"view");const arkjson::Value* view=nullptr;for(const auto& item:authored->find("views")->arr)if(sheetText(item,"name")==name)view=&item;const auto& offset=view->find("offset_mm")->arr;const auto& a=dimension.find("a_mm")->arr;const auto& b=dimension.find("b_mm")->arr;const auto& p=dimension.find("position_mm")->arr;double ax=offset[0].num+a[0].num*scale,ay=offset[1].num-a[1].num*scale,bx=offset[0].num+b[0].num*scale,by=offset[1].num-b[1].num*scale;const auto kind=sheetText(dimension,"kind");const auto blue=RGB(87,90,98);if(kind=="horizontal"){line(ax,ay,ax,p[1].num,blue);line(bx,by,bx,p[1].num,blue);line(ax,p[1].num,bx,p[1].num,blue,true);}else if(kind=="vertical"){line(ax,ay,p[0].num,ay,blue);line(bx,by,p[0].num,by,blue);line(p[0].num,ay,p[0].num,by,blue,true);}else if(kind=="linear"){double dx=bx-ax,dy=by-ay,len=std::hypot(dx,dy),nx=-dy/len,ny=dx/len,shift=(p[0].num-ax)*nx+(p[1].num-ay)*ny;line(ax,ay,ax+nx*shift,ay+ny*shift,blue);line(bx,by,bx+nx*shift,by+ny*shift,blue);line(ax+nx*shift,ay+ny*shift,bx+nx*shift,by+ny*shift,blue,true);}else line(p[0].num,p[1].num,bx,by,blue,true);std::string value=(kind=="radius"?"R ":kind=="diameter"?"DIA ":"")+sheetNumber(dimension.find("value")->num)+" "+sheetText(dimension,"units");if(const auto* tolerance=dimension.find("tolerance"))value+=" ["+sheetNumber(tolerance->find("lower")->num)+", +"+sheetNumber(tolerance->find("upper")->num)+"]";label(value,p[0].num+(kind=="vertical"?2:0),kind=="vertical"?(ay+by)/2-2:p[1].num-7,blue);} + if(const auto* frames=authored->find("geometric_tolerances"))for(const auto& f:frames->arr){const auto& p=f.find("position_mm")->arr;const auto& tip=f.find("leader_mm")->arr;std::string text=sheetText(f,"characteristic")+" | "+sheetNumber(f.find("value")->num)+" "+sheetText(f,"units");for(const auto& datum:f.find("datums")->arr)text+=" | "+datum.str;SIZE frameSize{};const auto wide=bomWide(text);auto previousFont=SelectObject(dc,font);GetTextExtentPoint32W(dc,wide.c_str(),(int)wide.size(),&frameSize);SelectObject(dc,previousFont);const double width=std::max(20.,frameSize.cx/fit+3),height=std::max(7.,(frameSize.cy+4.)/fit),x=p[0].num,y=p[1].num;const auto ink=RGB(45,59,73);line(x,y,x+width,y,ink);line(x,y+height,x+width,y+height,ink);line(x,y,x,y+height,ink);line(x+width,y,x+width,y+height,ink);const double cx=x+width/2,cy=y+height/2,dx=tip[0].num-cx,dy=tip[1].num-cy,attach=std::min(std::abs(dx)>1e-9?width/2/std::abs(dx):1e30,std::abs(dy)>1e-9?height/2/std::abs(dy):1e30);if(attach<1)line(cx+dx*attach,cy+dy*attach,tip[0].num,tip[1].num,ink,true);label(text,x+1,y+1,ink);} label(state.name+" | Scale "+sheetNumber(scale)+" | Units "+sheetText(*authored,"units")+" | Source r"+std::to_string((u64)authored->find("binding")->find("observed_revision")->num),8,height-11,RGB(75,79,85));RestoreDC(dc,saved);DeleteObject(font); } const auto footer=state.error.empty()?"Views and dimensions remain linked to the source solid. Tolerances are declared; manufacturing qualification is separate.":state.error;bomLabel(dc,bomWide(footer),{274,client.bottom-35,client.right-18,client.bottom-8},state.smallFont,state.error.empty()?bomMuted:bomAmber); @@ -83,7 +97,7 @@ static LRESULT CALLBACK drawingWorkspaceProc(HWND window,UINT message,WPARAM w,L if(message==WM_CTLCOLORSTATIC||message==WM_CTLCOLOREDIT||message==WM_CTLCOLORLISTBOX){SetTextColor((HDC)w,bomWhite);SetBkColor((HDC)w,bomPanelBg);SetDCBrushColor((HDC)w,bomPanelBg);return (LRESULT)GetStockObject(DC_BRUSH);} if(message==WM_DRAWITEM){auto& item=*(DRAWITEMSTRUCT*)l;const bool enabled=IsWindowEnabled(item.hwndItem)!=0;const bool primary=item.CtlID==801||item.CtlID==807;bomFill(item.hDC,item.rcItem,enabled?(primary?RGB(80,84,91):RGB(44,46,50)):RGB(32,34,36),6);wchar_t text[100]{};GetWindowTextW(item.hwndItem,text,100);bomLabel(item.hDC,text,item.rcItem,state->font,enabled?bomWhite:bomMuted,DT_CENTER|DT_VCENTER|DT_SINGLELINE);if(item.itemState&ODS_FOCUS){RECT r=item.rcItem;InflateRect(&r,-3,-3);DrawFocusRect(item.hDC,&r);}return TRUE;} if(message==WM_TIMER){if(g_busy)return 0;try{if(state->revision!=g_session.revision||state->epoch!=g_documentEpoch)sheetRefreshRead(*state);}catch(const std::exception& error){state->error=error.what();InvalidateRect(window,nullptr,FALSE);}return 0;} - if(message==WM_COMMAND){try{const int action=LOWORD(w);if(g_busy&&action!=809&&action!=813&&action!=814&&action!=815)throw std::runtime_error("Wait for the current model operation before editing this sheet");if(action==820&&HIWORD(w)==CBN_SELCHANGE&&!state->updating){const int selected=sheetChoice(state->drawings);if(selected>=0&&(size_t)selectedname=sheetText(g_doc.drawings[(size_t)selected],"name");sheetRefreshRead(*state);return 0;}switch(action){case 801:sheetDefinitionDialog(*state,true);break;case 802:sheetDefinitionDialog(*state,false);break;case 803:sheetViewDialog(*state,true);break;case 804:sheetViewDialog(*state,false);break;case 805:sheetDimensionDialog(*state,true);break;case 806:sheetDimensionDialog(*state,false);break;case 807:sheetRefreshSource(*state);break;case 808:sheetExport(*state);break;case 809:state->done=true;break;case 813:state->zoom=1;state->panX=state->panY=0;InvalidateRect(window,nullptr,FALSE);break;case 814:state->zoom=std::min(4.,state->zoom*1.25);InvalidateRect(window,nullptr,FALSE);break;case 815:state->zoom=std::max(.5,state->zoom/1.25);InvalidateRect(window,nullptr,FALSE);break;case 810:sheetRemoveElement(*state,true);break;case 811:sheetRemoveElement(*state,false);break;case 812:{if(state->revision!=g_session.revision||state->epoch!=g_documentEpoch)throw std::runtime_error("Document changed; inspect the sheet again");using V=arkjson::Value;V command=V::makeObj(),commands=V::makeArr(),args=V::makeObj();command.set("op",V::makeStr("drawing.remove"));command.set("name",V::makeStr(state->name));commands.arr.push_back(command);args.set("commands",commands);args.set("expected_revision",V::makeNum((double)state->revision));runTool("doc_apply",args);if(g_error)throw std::runtime_error(g_status);sheetRefreshRead(*state);break;}}}catch(const std::exception& error){g_error=true;g_status=error.what();state->error=error.what();InvalidateRect(window,nullptr,FALSE);}return 0;} + if(message==WM_COMMAND){if(LOWORD(w)==816){try{if(g_busy)throw std::runtime_error("Wait for the current model operation");sheetToleranceDialog(*state);}catch(const std::exception& e){g_error=true;g_status=e.what();state->error=e.what();InvalidateRect(window,nullptr,FALSE);}return 0;}try{const int action=LOWORD(w);if(g_busy&&action!=809&&action!=813&&action!=814&&action!=815)throw std::runtime_error("Wait for the current model operation before editing this sheet");if(action==820&&HIWORD(w)==CBN_SELCHANGE&&!state->updating){const int selected=sheetChoice(state->drawings);if(selected>=0&&(size_t)selectedname=sheetText(g_doc.drawings[(size_t)selected],"name");sheetRefreshRead(*state);return 0;}switch(action){case 801:sheetDefinitionDialog(*state,true);break;case 802:sheetDefinitionDialog(*state,false);break;case 803:sheetViewDialog(*state,true);break;case 804:sheetViewDialog(*state,false);break;case 805:sheetDimensionDialog(*state,true);break;case 806:sheetDimensionDialog(*state,false);break;case 807:sheetRefreshSource(*state);break;case 808:sheetExport(*state);break;case 809:state->done=true;break;case 813:state->zoom=1;state->panX=state->panY=0;InvalidateRect(window,nullptr,FALSE);break;case 814:state->zoom=std::min(4.,state->zoom*1.25);InvalidateRect(window,nullptr,FALSE);break;case 815:state->zoom=std::max(.5,state->zoom/1.25);InvalidateRect(window,nullptr,FALSE);break;case 810:sheetRemoveElement(*state,true);break;case 811:sheetRemoveElement(*state,false);break;case 812:{if(state->revision!=g_session.revision||state->epoch!=g_documentEpoch)throw std::runtime_error("Document changed; inspect the sheet again");using V=arkjson::Value;V command=V::makeObj(),commands=V::makeArr(),args=V::makeObj();command.set("op",V::makeStr("drawing.remove"));command.set("name",V::makeStr(state->name));commands.arr.push_back(command);args.set("commands",commands);args.set("expected_revision",V::makeNum((double)state->revision));runTool("doc_apply",args);if(g_error)throw std::runtime_error(g_status);sheetRefreshRead(*state);break;}}}catch(const std::exception& error){g_error=true;g_status=error.what();state->error=error.what();InvalidateRect(window,nullptr,FALSE);}return 0;} if(message==WM_LBUTTONDOWN&&sheetCurrent(*state)){POINT point{GET_X_LPARAM(l),GET_Y_LPARAM(l)};if(PtInRect(&state->canvas,point)){state->dragging=true;state->dragPoint=point;SetCapture(window);return 0;}} if(message==WM_MOUSEMOVE&&state->dragging){POINT point{GET_X_LPARAM(l),GET_Y_LPARAM(l)};state->panX+=point.x-state->dragPoint.x;state->panY+=point.y-state->dragPoint.y;state->dragPoint=point;InvalidateRect(window,&state->canvas,FALSE);return 0;} if(message==WM_LBUTTONUP&&state->dragging){state->dragging=false;ReleaseCapture();return 0;} @@ -91,7 +105,7 @@ static LRESULT CALLBACK drawingWorkspaceProc(HWND window,UINT message,WPARAM w,L return DefWindowProc(window,message,w,l); } static void showDrawingWorkspace(){ - if(g_busy)throw std::runtime_error("Wait for the current model operation before opening Drawings");WNDCLASSW wc{};wc.lpfnWndProc=drawingWorkspaceProc;wc.hInstance=GetModuleHandle(nullptr);wc.lpszClassName=L"ARK_DRAWING_WORKSPACE";wc.hCursor=LoadCursor(nullptr,IDC_ARROW);RegisterClassW(&wc);DrawingWorkspace state;state.font=CreateFontW(-15,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");state.smallFont=CreateFontW(-13,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");state.title=CreateFontW(-26,0,0,0,FW_SEMIBOLD,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");RECT parent{};GetWindowRect(g_window,&parent);const int width=std::max(1100,winW),height=std::max(700,winH);auto window=CreateWindowExW(WS_EX_DLGMODALFRAME,wc.lpszClassName,L"ARK / Technical drawings",WS_OVERLAPPEDWINDOW,parent.left,parent.top,width,height,g_window,nullptr,wc.hInstance,&state);BOOL dark=TRUE;DwmSetWindowAttribute(window,20,&dark,sizeof dark);auto control=[&](const wchar_t* cls,const wchar_t* title,DWORD style,int id){auto h=CreateWindowExW(0,cls,title,WS_CHILD|WS_VISIBLE|style,0,0,100,30,window,(HMENU)(INT_PTR)id,wc.hInstance,nullptr);SendMessage(h,WM_SETFONT,(WPARAM)state.font,TRUE);return h;};state.drawings=control(L"COMBOBOX",L"",WS_TABSTOP|CBS_DROPDOWNLIST|WS_VSCROLL,820);state.views=control(L"COMBOBOX",L"",WS_TABSTOP|CBS_DROPDOWNLIST|WS_VSCROLL,821);state.dimensions=control(L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,822);const wchar_t* labels[]={L"New drawing",L"Edit sheet",L"Add view",L"Edit view",L"Add dimension",L"Edit dimension",L"Refresh source",L"Export",L"Close",L"Remove view",L"Remove dim",L"Delete sheet",L"Fit",L"Zoom +",L"Zoom -"};for(int i=0;i<15;++i)control(L"BUTTON",labels[i],WS_TABSTOP|BS_OWNERDRAW,801+i);sheetRefreshRead(state);sheetLayout(state);EnableWindow(g_window,FALSE);ShowWindow(window,SW_SHOW);UpdateWindow(window);SetTimer(window,903,400,nullptr); + if(g_busy)throw std::runtime_error("Wait for the current model operation before opening Drawings");WNDCLASSW wc{};wc.lpfnWndProc=drawingWorkspaceProc;wc.hInstance=GetModuleHandle(nullptr);wc.lpszClassName=L"ARK_DRAWING_WORKSPACE";wc.hCursor=LoadCursor(nullptr,IDC_ARROW);RegisterClassW(&wc);DrawingWorkspace state;state.font=CreateFontW(-15,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");state.smallFont=CreateFontW(-13,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");state.title=CreateFontW(-26,0,0,0,FW_SEMIBOLD,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");RECT parent{};GetWindowRect(g_window,&parent);const int width=std::max(1100,winW),height=std::max(700,winH);auto window=CreateWindowExW(WS_EX_DLGMODALFRAME,wc.lpszClassName,L"ARK / Technical drawings",WS_OVERLAPPEDWINDOW,parent.left,parent.top,width,height,g_window,nullptr,wc.hInstance,&state);BOOL dark=TRUE;DwmSetWindowAttribute(window,20,&dark,sizeof dark);auto control=[&](const wchar_t* cls,const wchar_t* title,DWORD style,int id){auto h=CreateWindowExW(0,cls,title,WS_CHILD|WS_VISIBLE|style,0,0,100,30,window,(HMENU)(INT_PTR)id,wc.hInstance,nullptr);SendMessage(h,WM_SETFONT,(WPARAM)state.font,TRUE);return h;};state.drawings=control(L"COMBOBOX",L"",WS_TABSTOP|CBS_DROPDOWNLIST|WS_VSCROLL,820);state.views=control(L"COMBOBOX",L"",WS_TABSTOP|CBS_DROPDOWNLIST|WS_VSCROLL,821);state.dimensions=control(L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,822);const wchar_t* labels[]={L"New drawing",L"Edit sheet",L"Add view",L"Edit view",L"Add dimension",L"Edit dimension",L"Refresh source",L"Export",L"Close",L"Remove view",L"Remove dim",L"Delete sheet",L"Fit",L"Zoom +",L"Zoom -",L"Geometric tolerance"};for(int i=0;i<16;++i)control(L"BUTTON",labels[i],WS_TABSTOP|BS_OWNERDRAW,801+i);sheetRefreshRead(state);sheetLayout(state);EnableWindow(g_window,FALSE);ShowWindow(window,SW_SHOW);UpdateWindow(window);SetTimer(window,903,400,nullptr); if(g_drawingWorkspaceTest){auto test=std::move(g_drawingWorkspaceTest);g_drawingWorkspaceTest={};try{test(state);}catch(...){KillTimer(window,903);EnableWindow(g_window,TRUE);DestroyWindow(window);for(auto font:{state.font,state.smallFont,state.title})DeleteObject(font);throw;}} MSG message{};while(!state.done&&GetMessage(&message,nullptr,0,0)>0){if(message.message==WM_KEYDOWN&&message.wParam==VK_ESCAPE){state.done=true;break;}if(!IsDialogMessage(window,&message)){TranslateMessage(&message);DispatchMessage(&message);}if(!g_busy){drainUiTools();pollTeam(false);}}KillTimer(window,903);EnableWindow(g_window,TRUE);DestroyWindow(window);for(auto font:{state.font,state.smallFont,state.title})DeleteObject(font);SetActiveWindow(g_window); } diff --git a/src/view/drawing_workspace_selftest.inl b/src/view/drawing_workspace_selftest.inl index f5ecdd6..b1ff07a 100644 --- a/src/view/drawing_workspace_selftest.inl +++ b/src/view/drawing_workspace_selftest.inl @@ -11,8 +11,9 @@ press(803,{{"Front","orthographic","front","45","135"}});press(803,{{"Section A-A","section","top","175","75"},{"0","0","6"}});assertUi(state.report.find("views")->arr.size()==3,"Native view forms did not author orthographic and exact section views"); g_dialogShot=shotPath+".dimension-form.png";press(805,{{"Overall width","Top","horizontal","x_min","x_max","55","96","-0.1","0.2"}});assertUi(state.report.find("dimensions")->arr[0].find("value")->num==50,"Native dimension form did not resolve exact width"); press(805,{{"Height","Front","vertical","z_min","z_max","105","129","",""}});SendMessage(state.dimensions,LB_SETCURSEL,0,0);press(806,{{"Overall width","Top","horizontal","x_min","x_max","55","96","-0.2","0.3"}});assertUi(state.report.find("dimensions")->arr[0].find("tolerance")->find("upper")->num==.3,"Native tolerance editor did not retain its declared units and deviations"); + press(816,{{"Mount position","Top","position","0.15","A,B","165","135","155","120","Save"}});assertUi(sheetAuthored(state).find("geometric_tolerances")->arr.size()==1,"Geometric tolerance native editor did not author a frame"); assertUi(g_doc.evalBodies[0].nativeData.find("brep_base64")->str==sourceBrep,"Drawing UI edited the source B-rep");capture(".drawing-workspace.png"); - g_drawingExportTestPath=shotPath+".drawing.svg";std::error_code ignored;std::filesystem::remove(g_drawingExportTestPath,ignored);press(808,{{"svg"}});assertUi(std::filesystem::is_regular_file(g_drawingExportTestPath),"Native SVG export failed");g_drawingExportTestPath=shotPath+".drawing.json";std::filesystem::remove(g_drawingExportTestPath,ignored);press(808,{{"json"}});assertUi(std::filesystem::is_regular_file(g_drawingExportTestPath),"Native JSON export failed");g_drawingExportTestPath.clear(); + g_drawingExportTestPath=shotPath+".drawing.svg";std::error_code ignored;std::filesystem::remove(g_drawingExportTestPath,ignored);press(808,{{"svg","Current sheet"}});assertUi(std::filesystem::is_regular_file(g_drawingExportTestPath),"Native SVG export failed");g_drawingExportTestPath=shotPath+".drawing.json";std::filesystem::remove(g_drawingExportTestPath,ignored);press(808,{{"json","Current sheet"}});assertUi(std::filesystem::is_regular_file(g_drawingExportTestPath),"Native JSON export failed");g_drawingExportTestPath=shotPath+".drawing.pdf";std::filesystem::remove(g_drawingExportTestPath,ignored);press(808,{{"pdf","All sheets (PDF)"}});assertUi(std::filesystem::is_regular_file(g_drawingExportTestPath),"Native PDF export failed");g_drawingExportTestPath.clear(); applyCommand(fixture(R"({"op":"feature.edit","id":1,"p":{"width":65}})"));assertUi(!g_error,"Source edit fixture failed");SendMessage(state.window,WM_TIMER,903,0);assertUi(sheetText(state.report,"status")=="stale"&&!IsWindowEnabled(GetDlgItem(state.window,805)),"Source edit did not expose stale state and disable dimension authoring");capture(".drawing-stale.png");press(807);assertUi(sheetCurrent(state)&&state.report.find("dimensions")->arr[0].find("value")->num==65,"Native explicit refresh did not update associative measurements"); const auto before=documentToJson(g_doc,false,false);const auto revision=g_session.revision;g_dialogSmoke=2;SendMessage(GetDlgItem(state.window,802),BM_CLICK,0,0);g_dialogSmoke=0;assertUi(g_session.revision==revision&&documentToJson(g_doc,false,false)==before,"Cancelled drawing form changed the document"); g_drawingMutationAfterForm=[&]{applyCommand(fixture(R"({"op":"param.set","name":"intervening_ui_edit","expr":1})"));};g_dialogOverrideQueue={{"Bracket manufacturing sheet","1 / Fixture bracket","mm","0.5","297","210"}};g_dialogSmoke=3;SendMessage(GetDlgItem(state.window,802),BM_CLICK,0,0);g_dialogSmoke=0;assertUi(g_error&&g_session.revision==revision+1&&g_doc.drawings[0].find("scale")->num==1,"Drawing form silently rebased across an intervening revision");g_error=false;SendMessage(state.window,WM_TIMER,903,0); diff --git a/src/view/viewer.cpp b/src/view/viewer.cpp index 2f396fa..3ac66f7 100644 --- a/src/view/viewer.cpp +++ b/src/view/viewer.cpp @@ -75,6 +75,9 @@ typedef ptrdiff_t GLsizeiptr; #include "ark/holes_orchestrator.hpp" #include "ark/design_containers.hpp" #include "ark/parametric_components.hpp" +#include "ark/parametric_programs.hpp" +#include "ark/design_review.hpp" +#include "ark/design_variants.hpp" #include "ark/design_disciplines.hpp" #include "ark/motion_cables.hpp" #include "ark/datum_authoring.hpp" @@ -1560,7 +1563,7 @@ static arkjson::Value runTool(const std::string& tool,const arkjson::Value& args g_progressTiming030={}; flushPendingUsage(); auto effectiveArgs=args;static const std::set mutations{"doc_apply","doc_new","doc_load","doc_undo","doc_redo","iteration_restore","history_migrate_derived","history_compact","import_step","import_sheet_step","import_mesh","import_cad","design_containers","image_asset","plane_authoring","library_insert"};const bool documentWrite=mutations.count(tool)&&(tool!="design_containers"||containerWrite)&&(tool!="image_asset"||!args.find("action")||args.find("action")->asStr()!="inspect");if(documentWrite&&!effectiveArgs.find("actor")){using V=arkjson::Value;V actor=V::makeObj();actor.set("kind",V::makeStr("human"));actor.set("id",V::makeStr("studio"));effectiveArgs.set("actor",actor);} - bool potentiallySlow=(tool=="image_asset"&&args.find("action")&&(args.find("action")->asStr()=="generate"||args.find("action")->asStr()=="compose"))||tool=="parametric_components"||tool=="parametric_program"||tool=="wood_inspect"||tool=="hud_flex_check"||tool=="sketch_repair"||tool=="plane_authoring"||tool=="import_cad"||tool=="cad_inspect"||tool=="design_containers"||tool.rfind("library_",0)==0||tool=="failure_replay"||tool=="failure_export"||tool=="manufacturing_inspect"||tool=="doc_load"||tool=="iteration_restore"||tool=="history_migrate_derived"||tool=="history_compact"||tool=="doc_apply"||tool=="doc_preview"||tool=="design_solve"||tool=="placement_plan"||tool=="pattern_plan"||tool=="query_batch"||tool=="geometry_query"||tool=="physics_inspect"||tool=="native_inspect"||tool=="step_inspect"||tool=="reference_inspect"||tool=="assembly_info"||tool=="kernel_info"||tool=="doc_undo"||tool=="doc_redo"||tool=="import_step"||tool=="import_sheet_step"||tool=="import_mesh"||tool=="export_step"||tool=="export_iges"||tool=="export_mesh"||tool=="export_flat_dxf"||tool=="bom_export_parts"||tool=="reference_navigate"||tool=="selection_set"; + bool potentiallySlow=(tool=="image_asset"&&args.find("action")&&(args.find("action")->asStr()=="generate"||args.find("action")->asStr()=="compose"))||tool=="parametric_components"||tool=="parametric_program"||tool=="design_variants"||tool=="design_review"||tool=="drawing_export"||tool=="wood_inspect"||tool=="hud_flex_check"||tool=="sketch_repair"||tool=="plane_authoring"||tool=="import_cad"||tool=="cad_inspect"||tool=="design_containers"||tool.rfind("library_",0)==0||tool=="failure_replay"||tool=="failure_export"||tool=="manufacturing_inspect"||tool=="doc_load"||tool=="iteration_restore"||tool=="history_migrate_derived"||tool=="history_compact"||tool=="doc_apply"||tool=="doc_preview"||tool=="design_solve"||tool=="placement_plan"||tool=="pattern_plan"||tool=="query_batch"||tool=="geometry_query"||tool=="physics_inspect"||tool=="native_inspect"||tool=="step_inspect"||tool=="reference_inspect"||tool=="assembly_info"||tool=="kernel_info"||tool=="doc_undo"||tool=="doc_redo"||tool=="import_step"||tool=="import_sheet_step"||tool=="import_mesh"||tool=="export_step"||tool=="export_iges"||tool=="export_mesh"||tool=="export_flat_dxf"||tool=="bom_export_parts"||tool=="reference_navigate"||tool=="selection_set"; if(tool=="doc_apply"&&!effectiveArgs.find("checks")&&metadataOnlyApply(g_doc,effectiveArgs))potentiallySlow=false; bool viewportSnapshot=tool=="snapshot"&&!effectiveArgs.find("candidate_id")&&effectiveArgs.find("view")&&effectiveArgs.find("view")->asStr()=="viewport"; const bool backgroundAuthoring=tool=="doc_apply"&&!effectiveArgs.find("candidate_id")&&(!metadataOnlyApply(g_doc,effectiveArgs)||effectiveArgs.find("checks"))&&g_uiReady&&(!g_headless||g_authoringUiTestMode);if(backgroundAuthoring&&!effectiveArgs.find("expected_revision"))effectiveArgs.set("expected_revision",arkjson::Value::makeNum((double)g_session.revision)); @@ -3558,6 +3561,8 @@ static std::string readableJson(const arkjson::Value& value){std::string source= #include "holes_orchestrator_authoring.inl" #include "design_container_workspace.inl" #include "parametric_graph_053b.inl" +#include "component_library_067g.inl" +#include "design_variants.inl" #include "design_disciplines_054b.inl" static void failureOperationDialog(int mode=0){ using V=arkjson::Value;V arguments=V::makeObj();if(g_lastFailureId.empty()){arguments.set("limit",V::makeNum(1));auto latest=runTool("failure_info",arguments);if(g_error)return;auto* rows=latest.find("structuredContent")->find("records");if(!rows||rows->arr.empty())throw std::runtime_error("No failed operation was retained in this local session");g_lastFailureId=rows->arr.front().find("id")->asStr();} @@ -3878,6 +3883,7 @@ struct StudioCommandGroup {const char* title;std::vector& studioCommandGroups(){ static const auto groups=[](){std::vector result; auto group=[&](const char* title,std::initializer_list> items){result.push_back({title,items});}; + group("Design alternatives and review",{{49920,"Parametric configurator / saved variants"},{49921,"Compare editable alternatives"},{49922,"Explore parameter combinations"},{49940,"Compare design revisions"},{49941,"Repair failed feature"},{49942,"Hide revision overlay"},{49960,"Visual component library"}}); group("Plastics",{{308,"Plastics workspace"},{999,"Hollow / wall thickness"},{106,"Release angle"},{990,"Reinforce / mounting / lid fit"},{992,"Separate at plane"},{991,"Inspect exact polymer part"},{993,"Plastics scope and agent workflow"}}); group("Electronics & cabling",{{309,"Electronics workspace"},{211,"Board and pads"},{212,"Rounded cable route"},{996,"Smooth 3D cable"},{997,"Flat ribbon route"},{998,"Guide cable / ribbon path in viewport"},{995,"Inspect board / cable"},{994,"Approved Vendors"}}); group("Wood",{{982,"Wood panel"},{983,"Timber beam"},{986,"Wood groove / pocket / rabbet"},{987,"Wood stock cutlist"}}); @@ -3989,7 +3995,10 @@ static void selectTangentFaces(); static void collisionCheckDialog(); static bool viewportDockAction(int);static bool parametricHudAction(int); static bool surfaceEditAction059(int);static bool surfaceEditActive059(); +static bool designReviewAction067(int); static void uiAction(int id){ + if(id==49920||id==49921||id==49922){openDesignVariantsWindow();return;} + if(designReviewAction067(id)||componentLibraryAction067G(id))return; if(id==0||id==969)return; // Visible neutral panels consume input without changing state. if(id==49800){if(measurementActive())endMeasurement();else beginMeasurement(4);return;} if(id==49801){resetSmart062();return;} @@ -5046,6 +5055,7 @@ static void drawCanvases(const GLfloat* vpT){ #include "print_job_062b.inl" #include "transmission_panel_061c.inl" #include "surface_edit_059c.inl" +#include "design_review_067g.inl" #include "drag_chain.inl" #include "assistant_chat.inl" // Shared CAD display pass: no window operations, layout, chat synchronization, @@ -5125,7 +5135,7 @@ static Mat4 drawViewportScene059(bool interactive){ if(g_showDatumPlanes){glUniform4f(glGetUniformLocation(pSketch,"tint"),.55,.77,.68,.48);glDrawArrays(GL_LINES,(GLint)(g_sketchLines.size()+g_sketchPoints.size()+g_constraintHighlightLines.size())/3,(GLsizei)g_datumLines.size()/3);} if(!g_selectionLines.empty()){glLineWidth(2.5f);glUniform4f(glGetUniformLocation(pSketch,"tint"),.97,.62,.28,1.);glDrawArrays(GL_LINES,(GLint)(g_sketchLines.size()+g_sketchPoints.size()+g_constraintHighlightLines.size()+g_datumLines.size())/3,(GLsizei)g_selectionLines.size()/3);glLineWidth(1.f);} } - if(!sectionActive062()){if(interactive){if(g_measure.mode==4)smartHover062(g_pointerX,g_pointerY);else updateSelectionHover(g_pointerX,g_pointerY);}drawMeshPointerEdges();drawSelectedFaceGlow();drawSelectedReferenceEdges();drawSelectionHover();}drawDraftSketches();drawProjectionPreview();drawManualSketchPreview();drawSketchEditPreview();drawDirectAuthoringPreview();drawCableGuide035();drawSurfaceEdit059(); + if(!sectionActive062()){if(interactive){if(g_measure.mode==4)smartHover062(g_pointerX,g_pointerY);else updateSelectionHover(g_pointerX,g_pointerY);}drawMeshPointerEdges();drawSelectedFaceGlow();drawSelectedReferenceEdges();drawSelectionHover();}drawDraftSketches();drawProjectionPreview();drawManualSketchPreview();drawSketchEditPreview();drawDirectAuthoringPreview();drawCableGuide035();drawSurfaceEdit059();drawDesignReview067(); return vp; } static double g_frameProfile064[3]{}; @@ -5257,7 +5267,7 @@ static void drawFrame(HDC hdc){ else if(g_toolModule==4)groups={{"Analysis",{{"Physics",188},{"Loads",216}}},{"Generate",{{"Mesh net",981},{"Vent",984},{"Light up",980}}},{"Systems",{{"Electronics",211},{"Routing",212}}},{"Library",{{"Library",484},{"Model tools",456}}},{"Agents",{{"Assistant",400},{"Presence",988},{"Tools",457},{"Connect",58},{"Providers",357}}}}; else if(g_toolModule==6&&surfaceEditActive059())groups={{"Control net",{{"Pole / delta",49501},{"Glue hitpoint",49503},{"Reset",49505}}},{"View",{{"Normal view",71},{"Fit",20},{"Graphics",56}}},{"Finish",{{"Apply",49502},{"Cancel",49504}}}}; else if(g_toolModule==6)groups={{"Create",{{"Extrude",151},{"Revolve",152},{"Sweep",150},{"Loft",49403},{"Ruled",49402}}},{"Freeform",{{"NURBS",78},{"Patch fill",49404},{"Controls",49500}}},{"Trim",{{"Trim tool",49401},{"Trim plane",492},{"Mid mirror",49400}}},{"Finish",{{"Offset",153},{"Sew",154},{"Thicken",79},{"Repair",830}}}}; - else groups={{"Document",{{"New",55},{"Open",17},{"Save",16},{"Import",81},{"Export",213}}},{"History",{{"Undo",18},{"Redo",19},{"Features",756},{"Iterations",493},{"Last failure",580}}},{"Design",{{"Parameters",67},{"HUD",48000},{"Configurations",44080},{"Skeleton IDE",710}}},{"Outputs",{{"Drawings",860},{"BOM",590}}},{"Account",{{"Connect",58},{"Account",57},{"More",459}}}}; + else groups={{"Document",{{"New",55},{"Open",17},{"Save",16},{"Import",81},{"Export",213}}},{"History",{{"Undo",18},{"Redo",19},{"Features",756},{"Iterations",493},{"Last failure",580}}},{"Design",{{"Parameters",67},{"HUD",48000},{"Variants",49920},{"Library",49960},{"Skeleton IDE",710}}},{"Outputs",{{"Drawings",860},{"BOM",590}}},{"Account",{{"Connect",58},{"Account",57},{"More",459}}}}; groups.push_back({"Discover",{{"All tools",480}}}); // Ribbon labels keep one readable size: long titles wrap at the most balanced space. auto ribbonLabel=[&](const std::string& title,float x,float w,th::Tone t){ @@ -6153,12 +6163,18 @@ static void captureBusySnapshot030(){ } glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,winW,winH); } +static void invalidateStudioWindowsAfterWork(){ + EnumThreadWindows(GetCurrentThreadId(),[](HWND window,LPARAM)->BOOL{ + if(IsWindowVisible(window))RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN); + return TRUE; + },0); +} static arkjson::Value callSessionWithProgress(const std::string& tool,const arkjson::Value& args,std::function operation){ const auto captureStarted030=RealtimeClock030::now(); HDC hdc=GetDC(g_window);if(!hdc)throw std::runtime_error("Could not acquire ARK viewport for kernel operation"); struct BusyCleanup{ HDC hdc;bool previousSwap; - ~BusyCleanup(){g_busy=false;g_swap=previousSwap;ReleaseDC(g_window,hdc); + ~BusyCleanup(){g_busy=false;g_swap=previousSwap;ReleaseDC(g_window,hdc);invalidateStudioWindowsAfterWork(); if(g_busyClosePending){g_busyClosePending=false;PostMessage(g_window,WM_CLOSE,0,0);}} } cleanup{hdc,g_swap}; {std::lock_guard lock(g_busyProgressMutex);g_busyFeatureProgress={};} @@ -6182,7 +6198,9 @@ static arkjson::Value callSessionWithProgress(const std::string& tool,const arkj unsigned frameBefore=g_busyFrameCount; while(response.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready){ MSG message{}; - while(PeekMessageA(&message,nullptr,0,0,PM_REMOVE)){ + // Modeless native controls may continuously regenerate paint messages. + // Always return to the worker future, even while the UI queue stays busy. + for(unsigned pumped=0;pumped<256&&PeekMessageA(&message,nullptr,0,0,PM_REMOVE);++pumped){ if(mediaCancel&&message.message==WM_KEYDOWN&&message.wParam==VK_ESCAPE){*mediaCancel=true;g_status="Media cancellation requested";continue;} if(dispatchTeamDiagnostics030(message)){++g_busyPumpCount;continue;} if(message.message==WM_QUIT||message.message==WM_CLOSE){g_busyClosePending=true;continue;} @@ -6190,7 +6208,7 @@ static arkjson::Value callSessionWithProgress(const std::string& tool,const arkj // worker owns CAD. Other authoring input remains excluded. if(message.hwnd==g_window&&(message.message==WM_ARK_TOOL||message.message==WM_ARK_CHAT||message.message==WM_ARK_AUTH||message.message==WM_ARK_PRICE||message.message==WM_ARK_TEAM||message.message==WM_SIZE||message.message==WM_SYSCOMMAND||message.message==WM_NCLBUTTONDOWN||message.message==WM_NCLBUTTONUP||message.message==WM_NCLBUTTONDBLCLK||message.message==WM_NCRBUTTONUP||message.message==WM_DPICHANGED)){ DispatchMessageA(&message);++g_busyPumpCount; - }else if(message.message==WM_PAINT&&message.hwnd)ValidateRect(message.hwnd,nullptr); + }else if(message.message==WM_PAINT&&message.hwnd)RedrawWindow(message.hwnd,nullptr,nullptr,RDW_VALIDATE|RDW_NOINTERNALPAINT|RDW_NOERASE); } if(g_busyPumpTest)g_busyPumpTest(); drawBusyFrame(hdc);response.wait_for(std::chrono::milliseconds(16)); @@ -6529,6 +6547,7 @@ static void seedDocument(){g_doc=makeDemoDocument();rebuildScene();frameScene(); #include "assistant_chat_selftest.inl" #include "chat_dock_selftest.inl" #include "parametric_role_selftest.inl" +#include "design_variants_selftest.inl" #include "studio_render_selftest.inl" #include "interaction_performance.inl" #include "viewport_quality_selftest_056c.inl" @@ -6550,13 +6569,13 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ auto setDpiContext=reinterpret_cast(GetProcAddress(GetModuleHandleW(L"user32.dll"),"SetProcessDpiAwarenessContext")); if(!setDpiContext||!setDpiContext(reinterpret_cast(-4)))SetProcessDPIAware(); - bool assistantChatUiTest=false,chatDockUiTest=false,parametricRoleUiTest=false; + bool assistantChatUiTest=false,chatDockUiTest=false,parametricRoleUiTest=false,designVariantsUiTest=false; bool plasticsUiTest=false,electronicsWorkspaceUiTest=false,cableGuideUiTest=false; bool nativeProductPerformanceUiTest=false,sceneCacheUiTest=false,authoringAssistanceUiTest=false,featureEditorPickingUiTest=false; bool asyncAuthoringUiTest=false;bool historyCompactionUiTest=false;bool featureHistoryUiTest=false,recoveryUiTest=false,editorScrollUiTest=false,configurationWorkspaceUiTest=false,interactionPerformanceUiTest=false;bool startupUiTest=false;bool stampsUiTest=false;bool media044bUiTest=false;bool planesSectionsUiTest=false; bool specializedPatternUiTest=false;bool advancedSheetmetalUiTest=false;bool nativeVertexPullUiTest=false;bool cadImportUiTest=false;bool holesOrchestratorUiTest=false;bool designContainerUiTest=false;bool parametricGraphUiTest=false;bool designDisciplinesUiTest=false; bool directAuthoringUiTest=false,parametricAuthoringUiTest=false,skeletonEditorUiTest=false,imageAttachmentUiTest=false,assistantSteeringUiTest=false; - bool inspectionUiTest062=false;bool localModelsUiTest=false;bool viewportDockUiTest=false;bool bakedMotionsUiTest=false;bool parametricHudUiTest=false;bool explodedViewsUiTest=false;bool dragChainUiTest=false;bool bomUiTest=false;bool drawingWorkspaceUiTest=false;bool drawingViewportUiTest=false;bool measurementUiTest=false;bool authoringUiTest=false; + bool inspectionUiTest062=false;bool localModelsUiTest=false;bool viewportDockUiTest=false;bool bakedMotionsUiTest=false;bool parametricHudUiTest=false;bool designReviewUiTest=false;bool componentLibraryUiTest067G=false;bool explodedViewsUiTest=false;bool dragChainUiTest=false;bool bomUiTest=false;bool drawingWorkspaceUiTest=false;bool drawingViewportUiTest=false;bool measurementUiTest=false;bool authoringUiTest=false; bool selectionPickingUiTest=false;bool interactionUiTest=false,connectorsUiTest=false,actionIconsUiTest=false,treeUiTest=false,arcUiTest=false,completionUiTest=false,sketchDrawingUiTest=false,sketchEditUiTest=false,selectionGlowUiTest=false,datumAuthoringUiTest=false,typedSketchUiTest=false; bool assistantRevisionUiTest=false;bool teamBlockersUiTest=false;bool realtimeUiTest=false;bool asyncExactUiTest=false;bool productToolsUiTest=false;bool selfTest=false,assemblyTest=false,dialogTest=false,bendTest=false,bendExportTest=false,sourceTest=false,sketchTest=false,assistantTest=false,nativeUiTest=false,renderUiTest=false,engineeringUiTest=false,sheetShowcaseTest=false,contextUiTest=false,suspensionUiTest=false,connectChatGpt=false,motionUiTest=false,motionPlay=false,navigationUiTest=false,projectionUiTest=false,frameToolsUiTest=false;unsigned exitAfterMs=0;std::string endpointFile,requestedSketch;int requestedOpening=-1;double requestedFold=-1,showcaseProgress=-1;std::string shotPath="ark_studio.png",loadPath,scriptPath,importPath,showcaseView,spotlightName,suspensionFeatureName,motionDriverName,motionSpeed;double requestedMotionTime=0;std::vector suspensionValues; int requestedPathSamples=1;bool studioRenderTest=false,requestedPathTracing=false,viewportQualityTest=false,viewportCaptureTest=false,inertialUiTest=false,inertialEngineUiTest=false,rubberUiTest=false,rubberEngineUiTest=false,surfaceEditUiTest=false,surfaceWorkflowUiTest=false; @@ -6607,6 +6626,7 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ else if(a=="--self-test-planes-sections-ui"){planesSectionsUiTest=true;g_headless=true;} else if(a=="--self-test-assistant-chat-ui"){assistantChatUiTest=true;g_headless=true;} else if(a=="--self-test-chat-dock-ui"){chatDockUiTest=true;g_headless=true;} + else if(a=="--self-test-design-variants-ui"){designVariantsUiTest=true;g_headless=true;} else if(a=="--self-test-parametric-role-ui"){parametricRoleUiTest=true;g_headless=true;} else if(a=="--self-test-assistant-steering-ui"){assistantSteeringUiTest=true;g_headless=true;} else if(a=="--self-test-selection-picking-ui"){selectionPickingUiTest=true;g_headless=true;} @@ -6635,6 +6655,8 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ else if(a=="--self-test-local-models-ui"){localModelsUiTest=true;g_headless=true;} else if(a=="--self-test-viewport-dock-ui"){viewportDockUiTest=true;g_headless=true;} else if(a=="--self-test-baked-motions-ui"){bakedMotionsUiTest=true;g_headless=true;} + else if(a=="--self-test-component-library-ui"){componentLibraryUiTest067G=true;g_headless=true;} + else if(a=="--self-test-design-review-ui"){designReviewUiTest=true;g_headless=true;} else if(a=="--self-test-parametric-hud-ui"){parametricHudUiTest=true;g_headless=true;} else if(a=="--self-test-exploded-views-ui"){explodedViewsUiTest=true;g_headless=true;} else if(a=="--self-test-drag-chain-ui"){dragChainUiTest=true;g_headless=true;} @@ -7107,6 +7129,11 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ if(bakedMotionsUiTest){ #include "baked_motions_selftest.inl" } + if(componentLibraryUiTest067G){int result=testComponentLibrary067G(shotPath);DestroyWindow(hwnd);return result;} + if(designReviewUiTest){ +#include "design_review_selftest_067g.inl" + DestroyWindow(hwnd);return 0; + } if(parametricHudUiTest){ #include "parametric_hud_selftest.inl" } @@ -7610,6 +7637,7 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ } if(assistantChatUiTest){int result=testAssistantChat(shotPath);DestroyWindow(hwnd);return result;} if(chatDockUiTest){int result=testChatDock(shotPath);DestroyWindow(hwnd);return result;} + if(designVariantsUiTest){int result=testDesignVariantsUi(shotPath);DestroyWindow(hwnd);return result;} if(parametricRoleUiTest){int result=1;try{result=testParametricRole(shotPath);}catch(const std::exception& error){std::fprintf(stderr,"Parametric role exception: %s\n",error.what());std::ofstream(shotPath+".parametric-role-test.log")<<"FAIL exception: "<b)throw std::runtime_error(r.find("structu V call(AgentSession& s,const char* name,const char* json){return accepted(s.call(name,parse(json)));} void close(double a,double b,double tol,const char* reason){check(std::abs(a-b)<=tol,reason);} void testMath(){AgentSession s; - auto tools=AgentSession::tools(),full=AgentSession::tools(true);check(tools.arr.size()==122,"tool discovery");check(tools.dump().size()num,50.8,1e-12,"inch conversion"); close(call(s,"math_eval",R"({"op":"angle","a":[1,0,0],"b":[0,1,0]})").find("value")->num,90,1e-12,"vector angle"); diff --git a/tests/agent_team_design_workflows_067g_tests.inl b/tests/agent_team_design_workflows_067g_tests.inl new file mode 100644 index 0000000..31d5057 --- /dev/null +++ b/tests/agent_team_design_workflows_067g_tests.inl @@ -0,0 +1,53 @@ +// Candidate custody contracts independent of the native producers exercised by +// design_variants/design_review tests. The executor supplies a real cached preview. +static void designWorkflowCandidateCustody067g(){ + for(const auto& request:std::vector>{ + {"design_variants","prepare"},{"design_variants","save"}, + {"design_variants","remove"},{"design_review","prepare_repair"}}){ + ark::AgentSession session;ark::AgentTeam team;ark::AgentTeamConfig config; + config.roles={role("engineer",true)};int rounds=0;std::string candidate; + config.roles[0].transport=[&](const auto&,const V& input,const auto*){ + switch(++rounds){ + case 1:return call("inspect","doc_info",R"({"detail":"revision"})"); + case 2:return call("prepare",request.first,"{\"action\":\""+request.second+"\",\"expected_revision\":0}"); + case 3:{auto receipt=lastTeamReceipt(input);candidate=receipt.find("candidate_id")?receipt.find("candidate_id")->asStr():""; + return call("apply","team_apply_step","{\"candidate_id\":\""+candidate+"\",\"expected_revision\":0}");} + default:return done("Reviewed candidate applied"); + } + }; + team.start(config,"Review and apply a design candidate",ark::AgentSession::tools(),[&](const auto& name,const V& args){ + if(name==request.first)return session.call("doc_preview",json(R"({"expected_revision":0,"commands":[{"op":"param.set","name":"reviewed_width","expr":"24"}]})")); + return session.call(name,args); + });complete(team); + check(!candidate.empty()&&session.revision==1&&session.document.getParam("reviewed_width")==24,"host-generated design preview retains role ownership through team_apply_step"); + } + for(const auto& producer:std::vector>{{"design_variants","prepare"},{"design_review","prepare_repair"}}){ + ark::AgentSession session;ark::AgentTeam team;ark::AgentTeamConfig config; + config.roles={role("programmer",true)};config.roles[0].discipline=ark::AgentTeamDiscipline::ParametricDesigner; + int rounds=0;std::string preparedReceipt,publishReceipt,hostCandidate; + config.roles[0].transport=[&](const auto&,const V& input,const auto*){ + switch(++rounds){ + case 1:return call("inspect","doc_info",R"({"detail":"revision"})"); + case 2:return call("prepare",producer.first,"{\"action\":\""+producer.second+"\",\"expected_revision\":0}"); + case 3:preparedReceipt=lastTeamReceipt(input).dump();return call("publish","team_apply_step","{\"candidate_id\":\""+hostCandidate+"\",\"expected_revision\":0}"); + default:publishReceipt=lastTeamReceipt(input).dump();return done("Rejected unrelated recipe"); + } + }; + team.start(config,"Only compile the assigned parametric program",ark::AgentSession::tools(),[&](const auto& name,const V& args){ + if(name==producer.first){auto response=session.call("doc_preview",json(R"({"expected_revision":0,"commands":[{"op":"feature.add","type":"box","name":"Unrelated ordinary feature","p":{"dx":5,"dy":6,"dz":7}}]})"));const auto* data=response.find("structuredContent");if(data&&data->find("candidate_id"))hostCandidate=data->find("candidate_id")->asStr();return response;} + return session.call(name,args); + });complete(team); + check(!hostCandidate.empty()&&preparedReceipt.find("outside this role")!=std::string::npos,"Generated candidate must satisfy the recipient role discipline before custody"); + check(session.revision==0&&session.document.features.empty()&&publishReceipt.find("no successful preview receipt")!=std::string::npos,"Even a guessed retained candidate id cannot bypass rejected role custody"); + } + const auto tools=ark::AgentSession::tools(); + check(ark::assistantToolReadOnly(tools,"design_variants",json(R"({"action":"explore"})")),"exploration is a read-only isolated evaluation"); + check(!ark::assistantToolReadOnly(tools,"design_variants",json(R"({"action":"prepare"})")),"variant preview respects steering and reservation gates"); + check(ark::assistantToolReadOnly(tools,"design_review",json(R"({"action":"compare"})")),"revision comparison is read-only"); + check(!ark::assistantToolReadOnly(tools,"design_review",json(R"({"action":"prepare_repair"})")),"repair preview respects steering and reservation gates"); + ark::AgentSession session; + for(const char* topic:{"variants","design_review"}){ + auto receipt=session.call("agent_onboard",json(std::string("{\"topic\":\"")+topic+"\",\"detail\":\"guide\"}")); + check(!receipt.find("isError")->b,"new design workflow guidance is discoverable"); + } +} diff --git a/tests/agent_team_tests.cpp b/tests/agent_team_tests.cpp index a9c3c92..ca1b4e0 100644 --- a/tests/agent_team_tests.cpp +++ b/tests/agent_team_tests.cpp @@ -545,4 +545,5 @@ static void explicitInputWithRetainedToolFailure(){ #include "agent_team_read_recovery_038d_tests.inl" #include "agent_team_read_progress_041d_tests.inl" #include "agent_team_report_feedback_042d_tests.inl" -int main(){try{parametricDesignerRole();reportRatingsReplaceFeedbackRound042d();rejectedReportRatingsRecordNothing042d();progressReportCarriesRatings042d();handoffNoticeCarriesReport042d();teamRequestSizes();readFailureDoesNotBlockCompletion();removedSubjectSupersedesRejectedRead047d();reviewerCheckpointReminder();singleAssistantPreviewSchema();inspectionProgressProjection041d();inspectionActionPriorities041d();nativeReadThenGeometry041d();observedReadProgress041d();unsupportedCandidateRecovery040d();projectedBatchReadRecovery038d();exactReferenceReadRecovery038d();staleReadRevisionRecovery038d();correctedPreviewRecovery038d();batchReceiptAssociationRecovery038d();initialCheckpointNeedsSketchGeometry037d();initialLeadAuthoringCheckpoint037d();initialCheckpointLifecycle037d();coherentConstructionBounds037d();semanticProgress036a();semanticHandoff036a();sharedGraph034d();workflow033d();cooperativeReceiptContracts032d();expiredReceiptOwnership032d();independentTeamCandidateRefresh031b();teamCandidateDependencyConflict031b();teamCandidateProjectBoundary031b();teamCandidateRefreshReceipt031b();explicitInputWithRetainedToolFailure();staleLeadCannotAssignDownstream();inFlightImageTeamSteering();snapshotsDuringPeerWriteWindow();userImageTeamChecks();cooperativeWriteWindows();cooperativeWriteWindowLifecycle();cooperativeWriteWindowPermissionsAndAudit();oversizedHistoryResume();sharedAuthoringSchemas();drawingTeamScope();explicitGoalCompletion();ownedPreparedCandidates();restoredDocumentAndCanvasTools();coherentBatchBenchmark();focusedSequentialAssignments();leadEngineerAuthorsPartsAndAssembly();parallelProgressStillReportsCompletion();sharedFailureEvidence();parallelAutomaticCompletionBoundaries();unlimitedEightRoleAssignments();configChecks();concurrencyAndRevision();steeringAndPause();collaboration();cancellationAndFailures();interruptedBatchHistory();limitsAndMutationSchemas();conversationMemoryBound();incrementalStepsAndScopes();frameDisciplineScope();proposalsAndPhysicsRole();concurrentQueuedDrafts();yieldedAndInterruptedContinuation();std::cout<<"Agent team checks passed: "<find("error")->str.find("Density must be a positive finite number of grams per cubic centimetre")!=std::string::npos); } - CHECK(AgentSession::tools().arr.size()==122); + CHECK(AgentSession::tools().arr.size()==124); for(const char* name:{"manufacturing_plan","manufacturing_simulate","manufacturing_export","manufacturing_slice"}){auto tools=AgentSession::tools();CHECK(std::count_if(tools.arr.begin(),tools.arr.end(),[&](const V& tool){return tool.find("name")->str==name;})==1);} std::cout<str==name)return item;throw std::runtime_error("Missing tool "+name);} int main(){try{ AgentSession session;const auto baseline=documentToJson(session.document);const auto tools=AgentSession::tools(true); - check(tools.arr.size()==122,"Unexpected discovered tool count");for(const char* name:{"holes_catalog","cad_inspect","import_cad","design_containers"})check(tool(tools,name).find("inputSchema"),"Undiscoverable authoring tool"); + check(tools.arr.size()==124,"Unexpected discovered tool count");for(const char* name:{"holes_catalog","cad_inspect","import_cad","design_containers"})check(tool(tools,name).find("inputSchema"),"Undiscoverable authoring tool"); const auto& apply=*tool(tools,"doc_apply").find("inputSchema")->find("properties")->find("commands")->find("items");const auto& preview=*tool(tools,"doc_preview").find("inputSchema")->find("properties")->find("commands")->find("items");check(apply.dump()==preview.dump(),"Preview/apply recipes diverged");check(apply.find("properties")->find("p_remove"),"Inactive feature override removal absent"); for(const char* topic:{"overview","sketch","holes","cad_import","containers"}){V args=V::makeObj();args.set("topic",V::makeStr(topic));auto guide=agentOnboard(session,args);check(guide.find("functional_holes")&&guide.find("functional_holes")->str.find("Holes Orchestrator")!=std::string::npos,"Functional-hole policy absent");check(guide.find("drawing_authorization")&&guide.find("drawing_authorization")->str.find("explicitly requests")!=std::string::npos,"Drawing opt-in policy lost");} auto bad=session.call("import_cad",json(R"({"path":"missing.step","expected_revision":1})"));check(bad.find("isError")->b,"Stale CAD import accepted"); diff --git a/tests/authoring_024b_contract_tests.cpp b/tests/authoring_024b_contract_tests.cpp index 6838322..37c636a 100644 --- a/tests/authoring_024b_contract_tests.cpp +++ b/tests/authoring_024b_contract_tests.cpp @@ -9,7 +9,7 @@ static void check(bool value,const char* message){if(!value)throw std::runtime_e static V json(const char* text){V v;if(!arkjson::parse(text,v))throw std::runtime_error("Fixture JSON");return v;} static V call(AgentSession& s,const char* tool,V args){auto result=s.call(tool,args);if(result.find("isError")->b)throw std::runtime_error(result.find("structuredContent")->dump());return *result.find("structuredContent");} int main(){try{ - AgentSession session;const auto tools=AgentSession::tools();check(tools.arr.size()==122,"Expected 122 discoverable tools"); + AgentSession session;const auto tools=AgentSession::tools();check(tools.arr.size()==124,"Expected 124 discoverable tools"); for(const char* topic:{"stamps","planes"})check(!call(session,"agent_onboard",json((std::string("{\"topic\":\"")+topic+"\"}").c_str())).find("rules")->arr.empty(),"Missing specialized onboarding"); const auto baseline=documentToJson(session.document);auto preview=call(session,"plane_authoring",json(R"({"action":"create_plane","name":"Elevated","parent":"XY","p":{"oz":"12"},"expected_revision":0,"preview":true})"));check(preview.find("commands")&&!preview.find("applied")->b&&session.revision==0&&documentToJson(session.document)==baseline,"Plane preview must be concrete and immutable"); call(session,"plane_authoring",json(R"({"action":"create_plane","name":"Elevated","parent":"XY","p":{"oz":"12"},"expected_revision":0})"));check(session.revision==1,"Plane command must atomically commit once"); diff --git a/tests/authoring_029b_integration_tests.cpp b/tests/authoring_029b_integration_tests.cpp index abbec47..2c5afb7 100644 --- a/tests/authoring_029b_integration_tests.cpp +++ b/tests/authoring_029b_integration_tests.cpp @@ -53,7 +53,7 @@ void unloadedNamedHistory(){ apply(session,json(R"([{"op":"assembly.load","roots":null}])"));check(session.document.evalBodies.size()==4,"Loading all definitions remains valid after the rejected reorder");for(const auto& result:session.document.lastResults)check(result.ok,"Named loft and curve sources recompute after rejection"); } void discoveryAndHistory(){ - const auto tools=AgentSession::tools();check(tools.arr.size()==122,"029 tools plus the read-only Wood cutlist and parametric programs remain discoverable"); + const auto tools=AgentSession::tools();check(tools.arr.size()==124,"029 tools plus the read-only Wood cutlist and parametric programs remain discoverable"); const auto schema=tools.dump();check(schema.find("configuration.apply")!=std::string::npos&&schema.find("configuration.activate")==std::string::npos,"Discovery exposes executable configuration operations"); AgentSession session;for(const char* topic:{"history","configurations","drawings","stamps","planes","cad_import","containers"}){V args=V::makeObj();args.set("topic",V::makeStr(topic));accepted(session.call("agent_onboard",args));} apply(session,json(R"([{"op":"feature.add","type":"box","p":{"dx":10,"dy":8,"dz":5}},{"op":"feature.add","type":"box","p":{"dx":3,"dy":2,"dz":1}},{"op":"feature.rollback","id":1}])")); diff --git a/tests/datum_authoring_tests.cpp b/tests/datum_authoring_tests.cpp index 7263d3d..c774556 100644 --- a/tests/datum_authoring_tests.cpp +++ b/tests/datum_authoring_tests.cpp @@ -147,7 +147,7 @@ void originBisectorAndSelection(){ Document loaded;std::string error;check(documentFromJson(saved.dump(),loaded,&error),error.c_str());close(origin(loaded,"Mid"),{0,0,10},"reloaded bisector geometry");close(z(loaded,"Flip"),{0,0,-1},"reloaded difference normal"); setVersion(saved,45);check(!documentFromJson(saved.dump(),loaded,&error),"bisector below version 46 rejected");check(error.find("Bisector planes require document version 46")!=std::string::npos,error.c_str()); Document offset;put(offset,datum("Raised","plane",R"({"kind":"offset_plane","plane":"XY","offset":20})"));V older;check(arkjson::parse(documentToJson(offset),older),"offset json");check(older.find("version")->num==34,"offset plane stays version 34"); - setVersion(older,45);Document promoted;check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,46);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,47);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,48);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,49);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,56);check(!documentFromJson(older.dump(),promoted,&error),"version 56 rejected");check(error.find("unsupported document version")!=std::string::npos,error.c_str()); + setVersion(older,45);Document promoted;check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,46);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,47);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,48);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,49);check(documentFromJson(older.dump(),promoted,&error),error.c_str());setVersion(older,57);check(!documentFromJson(older.dump(),promoted,&error),"version 57 rejected");check(error.find("unsupported document version")!=std::string::npos,error.c_str()); AgentSession session;auto denied=session.call("doc_apply",parse(R"({"expected_revision":0,"commands":[{"op":"plane.set","name":"Origin","kind":"point","support":{"kind":"point","point":[0,0,0]}}]})")); check(denied.find("isError")->b&&denied.find("structuredContent")->dump().find("Built-in datums are immutable")!=std::string::npos,"session cannot author Origin"); auto selected=session.call("selection_set",parse(R"({"plane":"Origin","expected_revision":0})"));check(!selected.find("isError")->b,"Origin selection"); diff --git a/tests/design_review_tests.cpp b/tests/design_review_tests.cpp new file mode 100644 index 0000000..18124bc --- /dev/null +++ b/tests/design_review_tests.cpp @@ -0,0 +1,44 @@ +#include "ark/design_review.hpp" +#include "ark/iteration_history.hpp" +#include +#include +#include +using namespace ark;using V=arkjson::Value; +static void check(bool b,const char* m){if(!b)throw std::runtime_error(m);} +static V json(const std::string& s){V v;check(arkjson::parse(s,v),"fixture JSON");return v;} +static const V& field(const V& v,const char* k){static V n;const auto* p=v.find(k);return p?*p:n;} +static V invoke(AgentSession& s,const std::string& tool,V args){args.set("expected_revision",V::makeNum((double)s.revision));auto r=s.call(tool,args);if(field(r,"isError").b)throw std::runtime_error(r.dump());return field(r,"structuredContent");} +static void apply(AgentSession& s,const std::string& commands){V args=V::makeObj();args.set("commands",json(commands));invoke(s,"doc_apply",args);} +static V review(AgentSession& s,const char* action){V a=V::makeObj();a.set("action",V::makeStr(action));return invoke(s,"design_review",a);} +int main(){try{ + AgentSession s; + apply(s,R"([{"op":"param.set","name":"width","expr":"10"},{"op":"feature.add","type":"native_solid","name":"Block","native":{"op":"box"},"p":{"width":"width","depth":8,"height":6},"part":{"description":"Review fixture","part_number":"R-001"}},{"op":"assembly.add","feature":1,"name":"Block occurrence"}])"); + const auto id=field(iterationInfo(s.document),"head_id").asStr(); + {Document reordered=s.document;std::reverse(reordered.find(1)->part.obj.begin(),reordered.find(1)->part.obj.end());const auto same=compareDesignRevisions(reordered,s.revision,id);check(field(same,"changed").num==0,"JSON object key order must not create a false revision change");check(field(same,"bom_changes").arr.empty(),"JSON object key order must not create false BOM differences");} + apply(s,R"([{"op":"param.set","name":"width","expr":"14"},{"op":"assembly.add","feature":1,"name":"Second occurrence","p":{"tx":30}}])"); + const auto saved=documentToJson(s.document);const auto revision=s.revision;V args=V::makeObj();args.set("action",V::makeStr("compare"));args.set("before_id",V::makeStr(id));auto diff=invoke(s,"design_review",args); + check(field(diff,"changed").num==1,"Driven dimension change must change geometry even when the feature recipe is identical");check(field(diff,"parameter_changes").arr.size()==1,"Named parameter difference is explicit");check(documentToJson(s.document)==saved&&s.revision==revision,"Compare must not publish or change journal"); + check(field(field(field(diff,"features").arr[0],"after_geometry"),"geometry_authority").asStr()=="native_brep","Exact comparison uses native digest"); + const auto beforeItems=field(field(diff,"bom_before"),"items"),afterItems=field(field(diff,"bom_after"),"items");check(field(beforeItems.arr[0],"quantity").num==1&&field(afterItems.arr[0],"quantity").num==2,"BOM counts preserve revision-specific occurrences"); + args.set("before_id",V::makeStr("missing-history-id"));args.set("expected_revision",V::makeNum((double)s.revision));check(field(s.call("design_review",args),"isError").b,"Unknown history cannot silently fall back"); + args.set("before_id",V::makeStr(id));args.set("expected_revision",V::makeNum((double)s.revision-1));check(field(s.call("design_review",args),"isError").b,"Stale review must reject"); + check(field(review(s,"diagnose"),"failures").arr.empty(),"Valid model has no artificial repair findings"); + // External/native loading can expose a failed editable source. The repair + // path must recover it through the same whole-document preview transaction. + s.document.find(1)->p["width"]="unbound_width";s.document.iterationHistory=V();s.document.recompute();const auto broken=documentToJson(s.document);auto diagnostics=review(s,"diagnose");check(field(diagnostics,"failures").arr.size()==1,"Failed source is diagnosed"); + V repair=json(R"({"action":"prepare_repair","id":1,"command":{"op":"feature.edit","id":1,"p":{"width":"width"}}})");repair.set("source_sha256",field(diagnostics,"source_sha256"));auto candidate=invoke(s,"design_review",repair);check(!field(candidate,"candidate_id").asStr().empty(),"Repair returns a retained reviewed candidate");check(documentToJson(s.document)==broken&&s.revision==revision,"Preparing repair must leave broken authoring untouched"); + V forbidden=repair;forbidden.set("command",json(R"({"op":"feature.edit","id":1,"suppressed":true})"));forbidden.set("expected_revision",V::makeNum((double)s.revision));check(field(s.call("design_review",forbidden),"isError").b,"Suppression must not masquerade as repair"); + V stale=repair;stale.set("source_sha256",V::makeStr(std::string(64,'0')));stale.set("expected_revision",V::makeNum((double)s.revision));check(field(s.call("design_review",stale),"isError").b,"Source fingerprint protects repair"); + V loosen=repair;loosen.set("command",json(R"({"op":"feature.edit","id":1,"p":{"width":"width","tolerance":10}})"));loosen.set("expected_revision",V::makeNum((double)s.revision));check(field(s.call("design_review",loosen),"isError").b,"Repair cannot bypass failure with a relaxed tolerance"); + stale=repair;stale.set("expected_revision",V::makeNum((double)s.revision-1));check(field(s.call("design_review",stale),"isError").b,"Repair rejects stale revision independently of fingerprint"); + V publish=V::makeObj();publish.set("candidate_id",field(candidate,"candidate_id"));invoke(s,"doc_apply",publish);check(s.revision==revision+1&&s.document.features.size()==1,"Reviewed repair publishes exactly once without dropping solids");check(field(review(s,"diagnose"),"failures").arr.empty(),"Repair resolves current failure");check(s.document.assembly.size()==2,"Repair preserves assembly occurrences"); + AgentSession rejected; + apply(rejected,R"([{"op":"feature.add","type":"native_solid","name":"Everyday block","native":{"op":"box"},"p":{"width":10,"depth":8,"height":6}}])"); + const auto validSource=documentToJson(rejected.document);const auto validRevision=rejected.revision; + V bad=json(R"({"commands":[{"op":"feature.edit","id":1,"p":{"width":-10}}]})");bad.set("expected_revision",V::makeNum((double)validRevision));const auto failure=rejected.call("doc_apply",bad);check(field(failure,"isError").b,"Everyday negative dimension edit rejects");check(documentToJson(rejected.document)==validSource&&rejected.revision==validRevision,"Rejected edit retains the current valid source"); + auto retained=review(rejected,"diagnose");check(!field(retained,"failures").arr.empty(),"Guided repair must expose a rejected edit even while current model remains valid");const auto failedRow=field(retained,"failures").arr.front();check(!field(failedRow,"failure_id").asStr().empty(),"Rejected edit diagnosis retains failure custody"); + V correct=json(R"({"action":"prepare_repair","id":1,"command":{"op":"feature.edit","id":1,"p":{"width":18}}})");correct.set("failure_id",field(failedRow,"failure_id"));correct.set("source_sha256",field(retained,"source_sha256"));const auto reviewed=invoke(rejected,"design_review",correct);check(documentToJson(rejected.document)==validSource,"Corrected rejected edit is still only a preview");V accept=V::makeObj();accept.set("candidate_id",field(reviewed,"candidate_id"));invoke(rejected,"doc_apply",accept);check(rejected.document.find(1)->get("width")=="18"&&rejected.revision==validRevision+1,"Reviewed correction of ordinary rejected edit publishes once"); + correct.set("source_sha256",field(review(rejected,"diagnose"),"source_sha256"));correct.set("expected_revision",V::makeNum((double)rejected.revision));check(field(rejected.call("design_review",correct),"isError").b,"Retained failure from old revision cannot authorize a later correction"); + V tools=V::makeArr();appendDesignReviewTools(tools);check(tools.arr.size()==1&&!field(field(tools.arr[0],"annotations"),"readOnlyHint").b,"Prepare tool uses non-readonly steering despite no direct publication"); + std::cout<<"Design review: retained revision geometry, dimensions/BOM, atomic repair and rejection checks passed\n";return 0; +}catch(const std::exception& e){std::cerr< +#include +#include +using namespace ark;using V=arkjson::Value; +static int checks=0; +static void check(bool value,const std::string& why){++checks;if(!value)throw std::runtime_error(why);} +static V json(const std::string& s){V v;if(!arkjson::parse(s,v))throw std::runtime_error(s);return v;} +static const V& get(const V& v,const char* key){static V none;const auto* p=v.find(key);return p?*p:none;} +static V call(AgentSession& s,const char* tool,V a){a.set("expected_revision",V::makeNum(double(s.revision)));auto r=s.call(tool,a);check(!get(r,"isError").b,r.dump());return get(r,"structuredContent");} +static V variants(AgentSession& s,const std::string& args){return call(s,"design_variants",json(args));} +static void commit(AgentSession& s,const V& preview){V a=V::makeObj();a.set("candidate_id",get(preview,"candidate_id"));call(s,"doc_apply",a);} +static void reject(AgentSession& s,V a,const std::string& reason){const auto before=documentToJson(s.document,false,false);a.set("expected_revision",V::makeNum(double(s.revision)));const auto r=s.call("design_variants",a);check(get(r,"isError").b&&r.dump().find(reason)!=std::string::npos,"Expected "+reason+": "+r.dump());check(before==documentToJson(s.document,false,false),"Rejection altered document");} +int main(){try{AgentSession s;const auto program=json(R"({"format":"ark.parametric-program.v1","name":"Test family","parameters":{"width":{"default":10,"min":4,"max":20,"unit":"mm"}},"body":[{"assert":"width>=6","message":"Need six mm minimum clearance"},{"emit":{"op":"feature.add","type":"native_solid","name":"Block","native":{"op":"box"},"p":{"width":"{width}","depth":10,"height":10}}}]})");V install=json(R"({"action":"prepare","mode":"install","namespace":"family"})");install.set("program",program);commit(s,call(s,"parametric_program",install)); + const auto before=documentToJson(s.document,false,false);const auto rev=s.revision; + V staleInspect=json(R"({"action":"inspect"})");staleInspect.set("expected_revision",V::makeNum(double(s.revision+1)));check(get(s.call("design_variants",staleInspect),"isError").b,"Optional inspection revision rejects when stale");check(!get(s.call("design_variants",json(R"({"action":"inspect"})")),"isError").b,"Inspection without revision remains supported");reject(s,json(R"({"action":"prepare","namespace":"family","name":"Ambiguous","values":{"width":10}})"),"either a saved name or explicit values"); + auto evaluated=variants(s,R"({"action":"evaluate","namespace":"family","variants":[{"name":"Compact","values":{"width":6}},{"name":"Standard","values":{"width":10}},{"name":"Reinforced","values":{"width":20}},{"name":"Rejected","values":{"width":4}}],"constraints":{"volume_mm3":{"max":1200}},"thumbnails":true})");const auto& rows=get(evaluated,"results").arr; + check(rows.size()==4&&get(evaluated,"failed").num==1,"Every attempted alternative retained");check(get(rows[0],"valid").b&&std::abs(get(get(rows[0],"metrics"),"volume_mm3").num-600)<1e-7,"Independent exact compact volume");check(std::abs(get(get(rows[2],"metrics"),"width_mm").num-20)<1e-7,"Independent exact reinforced width");check(!get(rows[2],"feasible").b&&!get(rows[3],"valid").b,"Constraint rejection separate from kernel/program failure");check(get(evaluated,"ranked_indices").arr.size()==2&&get(evaluated,"ranked_indices").arr[0].num==0,"Only feasible trials ranked");check(!get(get(rows[0],"metrics"),"mass_available").b&&!get(rows[0],"display_triangles").arr.empty(),"Unknown density and display thumbnail reported honestly");check(s.revision==rev&&documentToJson(s.document,false,false)==before,"Comparison does not publish or alter history"); + auto exploration=variants(s,R"({"action":"explore","namespace":"family","axes":{"width":[4,6,10,20,21]},"objective":"width_mm","direction":"max"})");check(get(exploration,"attempted").num==5&&get(exploration,"failed").num==2,"Exploration retains assertion and range failures");check(get(exploration,"ranked_indices").arr[0].num==3,"Maximum width ranking uses exact valid geometry"); + auto unknown=variants(s,R"({"action":"evaluate","namespace":"family","values":{"width":10},"objective":"mass_kg"})");check(get(unknown,"ranked_indices").arr.empty(),"Missing density cannot win a mass objective"); + commit(s,variants(s,R"({"action":"save","namespace":"family","name":"Compact","values":{"width":6}})"));commit(s,variants(s,R"({"action":"save","namespace":"family","name":"Standard"})"));check(s.document.designVariants.arr.size()==2,"Save authored variants");check(get(s.document.designVariants.arr[0],"values").find("width"),"Saved numeric values"); + commit(s,variants(s,R"({"action":"save","namespace":"family","name":"family / Block","values":{"width":8}})"));commit(s,variants(s,R"({"action":"prepare","namespace":"family","name":"family / Block"})"));check(get(get(s.document.parametricPrograms.arr[0],"values"),"width").num==8,"Variant label equal to feature name is not a geometry dependency");commit(s,variants(s,R"({"action":"prepare","namespace":"family","name":"Standard"})"));commit(s,variants(s,R"({"action":"remove","namespace":"family","name":"family / Block"})")); + const auto persisted=documentToJson(s.document,false,false);check(get(json(persisted),"version").num==56,"New saved data requires semantic version56");Document loaded;std::string error;check(documentFromJson(persisted,loaded,&error),error);check(loaded.designVariants.dump()==s.document.designVariants.dump(),"Saved configurations reopen exactly");check(loaded.authoringCopy().designVariants.dump()==loaded.designVariants.dump(),"Isolated authoring copy preserves variants");auto downgraded=json(persisted);downgraded.set("version",V::makeNum(55));check(!documentFromJson(downgraded.dump(),loaded,&error)&&error.find("version 56")!=std::string::npos,"Reject semantic downgrade"); + auto selected=variants(s,R"({"action":"prepare","namespace":"family","name":"Compact"})");commit(s,selected);check(get(get(s.document.parametricPrograms.arr[0],"values"),"width").num==6,"Prepared saved values change editable program");call(s,"doc_undo",V::makeObj());check(get(get(s.document.parametricPrograms.arr[0],"values"),"width").num==10,"Undo restores program values");call(s,"doc_redo",V::makeObj());check(get(get(s.document.parametricPrograms.arr[0],"values"),"width").num==6,"Redo restores selected variant"); + reject(s,json(R"({"action":"save","namespace":"family","name":"Invalid","values":{"width":4}})"),"minimum clearance");reject(s,json(R"({"action":"explore","namespace":"family","axes":{"unknown":[1]}})"),"Unknown parameter axis");reject(s,json(R"({"action":"evaluate","namespace":"family","values":{"width":10},"constraints":{"stiffness":{"min":5}}})"),"Unsupported constraint metric"); + auto stale=variants(s,R"({"action":"prepare","namespace":"family","name":"Standard"})");commit(s,variants(s,R"({"action":"save","namespace":"family","name":"New","values":{"width":7}})"));V staleApply=V::makeObj();staleApply.set("candidate_id",get(stale,"candidate_id"));staleApply.set("expected_revision",V::makeNum(double(s.revision)));check(get(s.call("doc_apply",staleApply),"isError").b,"Stale prepared geometry cannot publish"); + V changed=program;changed.set("name",V::makeStr("Family revised"));V update=json(R"({"action":"prepare","mode":"update","namespace":"family"})");update.set("program",changed);commit(s,call(s,"parametric_program",update));reject(s,json(R"({"action":"prepare","namespace":"family","name":"Compact"})"),"different program revision");auto inspection=variants(s,R"({"action":"inspect","namespace":"family"})");check(!get(get(inspection,"variants").arr[0],"program_current").b,"Stale saved variant explicitly identified"); + commit(s,variants(s,R"({"action":"remove","namespace":"family","name":"Compact"})"));check(s.document.designVariants.arr.size()==2,"Remove selected metadata only"); + V removeProgram=json(R"({"action":"prepare","mode":"remove","namespace":"family"})");commit(s,call(s,"parametric_program",removeProgram));commit(s,variants(s,R"({"action":"remove","namespace":"family","name":"New"})"));check(s.document.designVariants.arr.size()==1,"Orphaned saved configurations can be explicitly removed"); + V denseProgram=program;V denseBody=get(denseProgram,"body"),denseStatement=denseBody.arr.back(),denseEmit=get(denseStatement,"emit"),denseParams=get(denseEmit,"p");denseParams.set("density",V::makeNum(7.85));denseEmit.set("p",denseParams);denseStatement.set("emit",denseEmit);denseBody.arr.back()=denseStatement;denseProgram.set("body",denseBody);V denseInstall=json(R"({"action":"prepare","mode":"install","namespace":"dense"})");denseInstall.set("program",denseProgram);commit(s,call(s,"parametric_program",denseInstall));const auto dense=variants(s,R"({"action":"evaluate","namespace":"dense","values":{"width":6},"objective":"mass_kg"})");const auto& denseMetrics=get(get(dense,"results").arr[0],"metrics");check(get(denseMetrics,"mass_available").b&&std::abs(get(denseMetrics,"mass_kg").num-0.00471)<1e-10,"Exact mass uses declared density and independent volume");check(get(dense,"ranked_indices").arr.size()==1,"Measured mass may be ranked"); + // Physical gaps use independent exact distance/common-volume checks. + V pairInstall=json(R"({"action":"prepare","mode":"install","namespace":"pair","program":{"format":"ark.parametric-program.v1","name":"Gap pair","parameters":{"gap":{"default":5,"min":-5,"max":20,"unit":"mm"}},"body":[{"emit":{"op":"feature.add","type":"native_solid","name":"Left","native":{"op":"box"},"p":{"width":10,"depth":10,"height":10}}},{"emit":{"op":"feature.add","type":"native_solid","name":"Seed","native":{"op":"box"},"p":{"width":10,"depth":10,"height":10}}},{"emit":{"op":"feature.add","type":"native_solid","name":"Right","inputs":["Seed"],"native":{"op":"transform"},"p":{"tx":"{10+gap}"}}}]}})");commit(s,call(s,"parametric_program",pairInstall)); + const auto gaps=variants(s,R"({"action":"explore","namespace":"pair","axes":{"gap":[-2,0,2,5]},"clearance_pairs":[{"a":"Left","b":"Right","min_mm":3}]})");const auto& gapRows=get(gaps,"results").arr;check(gapRows.size()==4&&get(gaps,"failed").num==0,"All gap geometries valid");check(get(gaps,"ranked_indices").arr.size()==1&&get(gaps,"ranked_indices").arr[0].num==3,"Only measured five mm gap passes three mm requirement");check(std::abs(get(get(gapRows[3],"clearance_checks").arr[0],"distance_mm").num-5)<1e-7,"Independent exact gap measurement");check(get(get(gapRows[0],"clearance_checks").arr[0],"overlap_volume_mm3").num>199.99,"Overlap measured instead of assumed separation"); + const auto missingGap=variants(s,R"({"action":"evaluate","namespace":"pair","values":{"gap":5},"clearance_pairs":[{"a":"Left","b":"Missing","min_mm":3}]})");check(get(missingGap,"ranked_indices").arr.empty()&&get(missingGap,"failed").num==1,"Missing physical gap evidence cannot rank feasible"); + bool discovery=false;for(const auto& t:AgentSession::tools().arr)discovery|=get(t,"name").str=="design_variants";check(discovery,"Tool is discoverable");std::cout<str;}++successes;}catch(const std::exception&){++failures;}};std::thread first([&]{run(a);}),second([&]{run(b);});first.join();second.join();check(successes==1&&failures==1&&iterationSha256(native_test::readFile(path.parent_path()/"publication-race.dxf"))==winner,"Concurrent DXF publication has one complete winner and preserves its measured bytes");} V entry=V::makeObj(),sanitized=V::makeObj();for(const auto& item:receipt.obj)if(item.first!="path")sanitized.set(item.first,item.second);entry.set("drawing",*query.find("name"));entry.set("fixture_recipe_sha256",V::makeStr(iterationSha256(report.find("authored")->dump())));entry.set("source_occurrences",*report.find("source_occurrences"));entry.set("receipt",sanitized);entry.set("atomic_publication_race_checked",V::makeBool(race));dxfEvidence.arr.push_back(entry);writeDxfEvidence(false); } +void delivery067G(const char* previewPath){ + native_test::TempDirectory folder("ark-drawing-delivery-067g-");AgentSession s;s.suppressFailureCapture();apply(s,R"([{"op":"feature.add","type":"native_solid","name":"Plate","native":{"op":"box"},"p":{"width":80,"depth":50,"height":8}}])"); + auto sheet=makeDrawingTemplate(s.document,json(R"({"kind":"part","feature":1})"),"Plate requirements");sheet.set("geometric_tolerances",json(R"([{"name":"Mount position","view":"top","characteristic":"position","value":0.15,"units":"mm","datums":["A","B"],"position_mm":[25,150],"leader_mm":[70,133]}])"));data(s.call("doc_apply",applyArgs(s,setCommand(sheet)))); + auto other=makeDrawingTemplate(s.document,json(R"({"kind":"part","feature":1})"),"Plate inspection");data(s.call("doc_apply",applyArgs(s,setCommand(other)))); + V args=json(R"({"names":["Plate inspection","Plate requirements"],"format":"pdf"})");args.set("path",V::makeStr(native_test::pathUtf8(folder.path()/"set.pdf")));args.set("expected_revision",V::makeNum((double)s.revision));const auto before=documentToJson(s.document);auto receipt=data(s.call("drawing_export",args));const auto bytes=native_test::readFile(folder.path()/"set.pdf");check(receipt.find("pages")->num==2&&bytes.find("/Count 2")!=std::string::npos&&bytes.find("position")!=std::string::npos&&bytes.find("0.15 mm")!=std::string::npos&&bytes.find("Tolerances: caller-declared")!=std::string::npos,"Multipage PDF retains authored tolerance frame and caller-selected order");check(before==documentToJson(s.document),"PDF does not mutate the drawing");if(previewPath)std::filesystem::copy_file(folder.path()/"set.pdf",std::filesystem::u8path(std::string(previewPath)+".set.pdf")); + Document reopened;std::string error;check(documentFromJson(before,reopened,&error),error);check(reopened.drawings[0].find("geometric_tolerances")->arr.size()==1,"Geometric tolerance persists");auto old=json(before);old.set("version",V::makeNum(55));check(!documentFromJson(old.dump(),reopened,&error),"Geometric tolerance rejects semantic downgrade"); + auto bad=sheet;auto frames=*bad.find("geometric_tolerances");frames.arr[0].set("characteristic",V::makeStr("flatness"));bad.set("geometric_tolerances",frames);check(s.call("doc_apply",applyArgs(s,setCommand(bad))).find("isError")->b,"Form tolerance rejects datum references"); + apply(s,R"([{"op":"feature.edit","id":1,"p":{"width":90}}])");args.set("expected_revision",V::makeNum((double)s.revision));args.set("path",V::makeStr(native_test::pathUtf8(folder.path()/"stale.pdf")));check(s.call("drawing_export",args).find("isError")->b&&!std::filesystem::exists(folder.path()/"stale.pdf"),"One stale sheet rejects all PDF pages before publication"); +} void inactiveSources(){ native_test::TempDirectory workspace("ark-029b-inactive-drawings-");AgentSession s;s.suppressFailureCapture();::apply(s,R"([{"op":"feature.add","type":"native_solid","name":"First","native":{"op":"box"},"p":{"width":20,"depth":10,"height":8}},{"op":"feature.add","type":"native_solid","name":"Later","native":{"op":"box"},"p":{"width":10,"depth":6,"height":4}},{"op":"assembly.add","name":"Loaded first","feature":1},{"op":"assembly.add","name":"Other definition","feature":2},{"op":"assembly.add","name":"Unloaded shared definition","feature":1,"p":{"tx":50}}])"); const auto first=s.document.assembly[0].id,shared=s.document.assembly[2].id;for(const auto& item:std::vector>{{"Later sheet",json(R"({"kind":"part","feature":2})")},{"Whole sheet",json(R"({"kind":"assembly","assembly":0})")},{"Shared sheet",json("{\"kind\":\"occurrence\",\"node\":"+std::to_string(shared)+",\"copy\":0}")}})data(s.call("doc_apply",applyArgs(s,setCommand(makeDrawingTemplate(s.document,item.second,item.first))))); @@ -63,6 +72,9 @@ void native(const char* previewPath){ auto preserved=s.document.evalBodies[0].baked?std::make_unique(*s.document.evalBodies[0].baked):nullptr;s.document.evalBodies[0].baked=std::make_unique();auto meshIndependent=inspect(s);check(meshIndependent.find("current_brep_base64_sha256")->str==digest&&meshIndependent.find("dimensions")->dump()==report.find("dimensions")->dump(),"Empty display mesh cannot choose drawing geometry or measurements");s.document.evalBodies[0].baked=std::move(preserved); const auto current=s.revision;V output=json(R"({"name":"Bracket drawing","format":"svg"})");output.set("expected_revision",V::makeNum((double)current));output.set("path",V::makeStr(native_test::pathUtf8(workspace.path()/"drawing.svg")));auto receipt=data(s.call("drawing_export",output));auto svg=native_test::readFile(workspace.path()/"drawing.svg");check(svg.find("40 mm")!=std::string::npos&&svg.find("-0.1, +0.2")!=std::string::npos&&s.revision==current,"SVG contains measured dimensions and declared tolerance without changing revision");check(s.call("drawing_export",output).find("isError")->b&&native_test::readFile(workspace.path()/"drawing.svg")==svg,"Existing drawing exports are never replaced"); dxfCheck(s,json(R"({"name":"Bracket drawing"})"),workspace.path()/"drawing.dxf",true); + V pdfArgs=output;pdfArgs.set("format",V::makeStr("pdf"));pdfArgs.set("path",V::makeStr(native_test::pathUtf8(workspace.path()/"drawing.pdf")));const auto pdfReceipt=data(s.call("drawing_export",pdfArgs));const auto pdf=native_test::readFile(workspace.path()/"drawing.pdf");check(pdf.rfind("%PDF-1.4",0)==0&&pdf.find("/PrintScaling /None")!=std::string::npos&&pdf.find("/Count 1")!=std::string::npos&&pdf.find("40 mm")!=std::string::npos&&pdfReceipt.find("vector_presentation")->b,"PDF preserves vector drawing text, page size and actual-size print preference");check(s.call("drawing_export",pdfArgs).find("isError")->b&&native_test::readFile(workspace.path()/"drawing.pdf")==pdf,"PDF no-replace publication preserves existing files"); + if(previewPath)std::filesystem::copy_file(workspace.path()/"drawing.pdf",std::filesystem::u8path(std::string(previewPath)+".pdf")); + if(previewPath)std::filesystem::copy_file(workspace.path()/"drawing.svg",std::filesystem::u8path(previewPath)); output.set("format",V::makeStr("json"));output.set("path",V::makeStr(native_test::pathUtf8(workspace.path()/"drawing.json")));data(s.call("drawing_export",output));check(json(native_test::readFile(workspace.path()/"drawing.json")).find("views")->arr[0].find("edges")->arr[0].find("exact_brep_base64"),"JSON export retains derived exact curve custody"); const auto document=native_test::pathUtf8(workspace.path()/"drawing.ark");check(saveDocument(s.document,document.c_str()),"Drawing SQLite save succeeds");Document loaded;std::string error;check(loadDocument(document.c_str(),loaded,&error),error);loaded.recompute();V query=json(R"({"name":"Bracket drawing"})");check(inspectDrawing(loaded,query,100).find("status")->str=="current","Save/reopen uses geometry binding rather than a fabricated session revision match");check(loaded.iterationHistory.t==V::Obj,"Drawing edits retain immutable document history"); @@ -111,6 +123,7 @@ try{core(); #ifdef ARK_DRAWING_NATIVE_TESTS native(argc==3&&std::string(argv[1])=="--preview"?argv[2]:nullptr); assemblyDrawings(); +delivery067G(argc==3&&std::string(argv[1])=="--preview"?argv[2]:nullptr); inactiveSources(); writeDxfEvidence(true); #endif diff --git a/tests/parametric_components_053b_tests.cpp b/tests/parametric_components_053b_tests.cpp index b1e0e12..84de5fd 100644 --- a/tests/parametric_components_053b_tests.cpp +++ b/tests/parametric_components_053b_tests.cpp @@ -22,7 +22,11 @@ int main(){try{ const auto dir=std::filesystem::temp_directory_path()/("ark-components-053b-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));std::filesystem::create_directory(dir); AgentSession source;apply(source,R"([{"op":"param.set","name":"width","expr":12},{"op":"param.set","name":"wider","expr":"width*2"},{"op":"plane.set","name":"Mount","p":{"oz":"width"}},{"op":"feature.add","type":"native_solid","name":"Base","native":{"op":"box"},"p":{"width":"wider","depth":10,"height":4}},{"op":"assembly.add","name":"Assembly","feature":0},{"op":"assembly.add","name":"Base occurrence","parent":1,"feature":1}])"); V exportArgs=json(R"({"kind":"part","feature":1,"name":"Parametric base","parameters":["width"],"interfaces":["Mount"]})");const auto package=makeParametricComponent(source.document,exportArgs);const auto path=(dir/"base-r1.arkprt").string();saveParametricComponent(package,path);check(documentContainerFile(path.c_str()),"Component must use binary owned container");check(parametricComponentHash(loadParametricComponent(path))==parametricComponentHash(package),"Package round trip"); + V libraryArgs=json(R"({"query":"width","kind":"part"})");libraryArgs.set("directory",V::makeStr(dir.string()));const auto catalog=parametricComponentLibrary(libraryArgs);check(at(catalog,"components").arr.size()==1&&at(at(catalog,"components").arr[0],"sha256").str==parametricComponentHash(package),"Library searches public parameters and retains package identity"); + const auto thumb=parametricComponentThumbnail(path);check(!at(thumb,"lines").arr.empty()&&at(thumb,"package_sha256").str==parametricComponentHash(package),"Library thumbnail comes from the selected evaluated package"); + libraryArgs.set("query",V::makeStr("does-not-exist"));check(at(parametricComponentLibrary(libraryArgs),"components").arr.empty(),"Library query filters unmatched packages without importing"); AgentSession target;apply(target,R"([{"op":"param.set","name":"width","expr":999},{"op":"feature.add","type":"box","name":"Unrelated","p":{"dx":2,"dy":3,"dz":4}}])");const auto before=documentToJson(target.document,false,false);const auto revision=target.revision; + V changedFile=json(R"({"action":"prepare","mode":"insert","namespace":"rejected","expected_source_sha256":"0000000000000000000000000000000000000000000000000000000000000000"})");changedFile.set("path",V::makeStr(path));rejects(target,"parametric_components",changedFile,"STALE_SOURCE"); const auto preview=prepare(target,path,"left","insert",json(R"({"width":20})"));check(target.revision==revision&&documentToJson(target.document,false,false)==before,"Preview must not mutate source");commit(target,preview); check(target.document.getParam("width")==999&&target.document.getParam("left__width")==20&&target.document.getParam("left__wider")==40,"Parameter isolation and expression token remap");check(target.document.find(2)->p.at("width")=="left__wider","Feature retains editable expression");check(target.document.planes[0].p.at("oz")=="left__width","Datum expressions remap");check(target.document.lastResults.back().ok,"Exact result valid"); const auto native=call(target,"native_inspect",json(R"({"id":2,"detail":"properties"})"));check(at(at(native,"report"),"brep_valid").b&&std::abs(at(at(native,"report"),"volume_mm3").num-1600)<1e-6,"Independent exact volume after public override"); diff --git a/tests/profile_regions_046b_tests.cpp b/tests/profile_regions_046b_tests.cpp index a1e688d..021cfd5 100644 --- a/tests/profile_regions_046b_tests.cpp +++ b/tests/profile_regions_046b_tests.cpp @@ -228,7 +228,7 @@ void persistence(){ double v=0;std::vector names;for(const auto& f:restored.features)if(f.name=="Selected")for(const auto& b:restored.evalBodies)if(b.id==f.id){v=b.nativeData.find("report")->find("volume_mm3")->num;names=semanticNames(b);} close(v,volume(s,"Selected"),1e-9,"cold rebuild parity");check(names==semanticNames(body(s,"Selected")),"references reproduce after reload"); Value older;check(arkjson::parse(saved,older),"older");older.set("version",Value::makeNum(47));ark::Document stale;check(!ark::documentFromJson(older.dump(),stale,&error)&&error.find("version 48")!=std::string::npos,"format 47 cannot carry native.regions: "+error); - Value future;check(arkjson::parse(saved,future),"future");future.set("version",Value::makeNum(56));check(!ark::documentFromJson(future.dump(),stale,&error)&&error.find("unsupported document version")!=std::string::npos,"format 56 is a future format"); + Value future;check(arkjson::parse(saved,future),"future");future.set("version",Value::makeNum(57));check(!ark::documentFromJson(future.dump(),stale,&error)&&error.find("unsupported document version")!=std::string::npos,"format 57 is a future format"); } applyOk(s,R"([{"op":"feature.remove","id":"Selected"}])");check(savedVersion(s.document)==implicit,"removing the selection returns to the earlier format"); std::cout<<"persistence: implicit multi-loop extrude keeps format "< Date: Sat, 7 Nov 2026 14:09:50 +0000 Subject: [PATCH 02/22] feat: deliver 068B exact surface modeling and native inspection --- CMakeLists.txt | 14 +++- docs/README.md | 4 + docs/ROADMAP.md | 7 ++ docs/SURFACE_EDITING_068B.md | 35 +++++++++ docs/SURFACE_NETWORK_068B.md | 35 +++++++++ docs/SURFACE_OFFSET_068B.md | 49 ++++++++++++ docs/SURFACE_QUALITY_068B.md | 27 +++++++ docs/SURFACING.md | 6 +- docs/iterations/068B.md | 74 +++++++++++++++++++ include/ark/native_features.hpp | 2 + include/ark/surface_edit_059c.hpp | 6 ++ include/ark/surface_network_068b.hpp | 6 ++ include/ark/surface_offset_068b.hpp | 6 ++ include/ark/surface_operations_068b.hpp | 6 ++ include/ark/surface_quality_068b.hpp | 6 ++ release.json | 19 ++--- src/agent_features.cpp | 13 +++- src/agent_team.cpp | 2 +- src/assistant.cpp | 1 + src/assistant_steering.inl | 1 + src/exact_jobs_046b.cpp | 5 +- src/iteration_history.cpp | 2 +- src/model.cpp | 1 + src/native_features.cpp | 26 +++++-- src/occt/common.cpp | 1 + src/occt/restore_result_031b.inl | 1 + src/occt/surface_match_068b.inl | 54 ++++++++++++++ src/occt/surface_network_068b.inl | 70 ++++++++++++++++++ src/occt/surface_offset_068b.inl | 40 ++++++++++ src/occt/surface_operations_068b.inl | 37 ++++++++++ src/occt/surfacing.cpp | 37 +++++++--- src/onboarding.cpp | 11 +++ src/serialize.cpp | 5 +- src/surface_edit_059c.cpp | 33 ++++++++- src/surface_network_068b.cpp | 43 +++++++++++ src/surface_offset_068b.cpp | 38 ++++++++++ src/surface_operations_068b.cpp | 34 +++++++++ src/surface_quality_068b.cpp | 30 ++++++++ src/view/action_icons_selftest.inl | 2 +- src/view/action_icons_set_c.inl | 16 ++++ src/view/geometry_authoring.inl | 14 +++- src/view/surface_edit_059c.inl | 21 ++++-- src/view/surface_edit_059c_selftest.inl | 1 + src/view/surface_network_068b.inl | 31 ++++++++ src/view/surface_network_selftest_068b.inl | 23 ++++++ src/view/surface_offset_068b.inl | 29 ++++++++ src/view/surface_offset_selftest_068b.inl | 12 +++ src/view/surface_operations_068b.inl | 19 +++++ src/view/surface_operations_selftest_068b.inl | 6 ++ src/view/surface_quality_068b.inl | 65 ++++++++++++++++ src/view/surface_quality_selftest_068b.inl | 19 +++++ src/view/surface_workflow_059c.inl | 2 +- src/view/viewer.cpp | 57 +++++++++++--- ...agent_team_design_workflows_067g_tests.inl | 3 +- tests/agent_tests.cpp | 2 +- tests/datum_authoring_tests.cpp | 2 +- tests/exact_jobs_046b_tests.cpp | 6 ++ tests/occt_surface_tests.cpp | 2 +- tests/profile_regions_046b_tests.cpp | 2 +- tests/surface_network_068b_tests.cpp | 36 +++++++++ tests/surface_network_host_068b_tests.cpp | 18 +++++ tests/surface_offset_068b_tests.cpp | 20 +++++ tests/surface_operations_068b_tests.cpp | 23 ++++++ tests/surface_quality_068b_tests.cpp | 29 ++++++++ 64 files changed, 1181 insertions(+), 66 deletions(-) create mode 100644 docs/SURFACE_EDITING_068B.md create mode 100644 docs/SURFACE_NETWORK_068B.md create mode 100644 docs/SURFACE_OFFSET_068B.md create mode 100644 docs/SURFACE_QUALITY_068B.md create mode 100644 docs/iterations/068B.md create mode 100644 include/ark/surface_network_068b.hpp create mode 100644 include/ark/surface_offset_068b.hpp create mode 100644 include/ark/surface_operations_068b.hpp create mode 100644 include/ark/surface_quality_068b.hpp create mode 100644 src/occt/surface_match_068b.inl create mode 100644 src/occt/surface_network_068b.inl create mode 100644 src/occt/surface_offset_068b.inl create mode 100644 src/occt/surface_operations_068b.inl create mode 100644 src/surface_network_068b.cpp create mode 100644 src/surface_offset_068b.cpp create mode 100644 src/surface_operations_068b.cpp create mode 100644 src/surface_quality_068b.cpp create mode 100644 src/view/surface_network_068b.inl create mode 100644 src/view/surface_network_selftest_068b.inl create mode 100644 src/view/surface_offset_068b.inl create mode 100644 src/view/surface_offset_selftest_068b.inl create mode 100644 src/view/surface_operations_068b.inl create mode 100644 src/view/surface_operations_selftest_068b.inl create mode 100644 src/view/surface_quality_068b.inl create mode 100644 src/view/surface_quality_selftest_068b.inl create mode 100644 tests/surface_network_068b_tests.cpp create mode 100644 tests/surface_network_host_068b_tests.cpp create mode 100644 tests/surface_offset_068b_tests.cpp create mode 100644 tests/surface_operations_068b_tests.cpp create mode 100644 tests/surface_quality_068b_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 55ad965..3fcdb7c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,6 +59,7 @@ add_library(ark STATIC src/authoring_023b.cpp src/cad_import.cpp src/holes_orchestrator.cpp src/design_containers.cpp src/parametric_components.cpp src/parametric_programs.cpp src/design_variants.cpp src/design_review.cpp + src/surface_quality_068b.cpp src/surface_network_068b.cpp src/surface_operations_068b.cpp src/surface_offset_068b.cpp src/design_disciplines.cpp src/motion_cables.cpp src/assembly_patterns.cpp src/transmission_math_061c.cpp src/transmission_tools_061c.cpp src/transmission_design_061c.cpp @@ -183,6 +184,17 @@ if(ARK_WITH_OCCT) add_test(NAME parametric-components-053b COMMAND ark-parametric-components-053b-tests) set_tests_properties(parametric-components-053b PROPERTIES TIMEOUT 180) add_dependencies(ark-parametric-components-053b-tests ark-occt-worker) + foreach(feature surface_quality_068b surface_network_host_068b surface_operations_068b surface_offset_068b) + add_executable(ark-${feature}-tests tests/${feature}_tests.cpp) + target_link_libraries(ark-${feature}-tests PRIVATE ark) + add_test(NAME ${feature} COMMAND ark-${feature}-tests) + set_tests_properties(${feature} PROPERTIES TIMEOUT 240) + add_dependencies(ark-${feature}-tests ark-occt-worker) + endforeach() + add_executable(ark-surface-network-native-068b-tests tests/surface_network_068b_tests.cpp) + target_link_libraries(ark-surface-network-native-068b-tests PRIVATE ark-occt ark) + add_test(NAME surface-network-native-068b COMMAND ark-surface-network-native-068b-tests) + set_tests_properties(surface-network-native-068b PROPERTIES TIMEOUT 240) foreach(feature design_variants design_review) add_executable(ark-${feature}-tests tests/${feature}_tests.cpp) target_link_libraries(ark-${feature}-tests PRIVATE ark) @@ -690,7 +702,7 @@ if(WIN32) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1280 800) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 300 RUN_SERIAL TRUE) endforeach() - foreach(check design-variants-ui component-library-ui design-review-ui inertial-ui viewport-quality-ui connectors-ui local-models-ui viewport-dock-ui context-ui suspension-ui assistant-steering-ui assistant-chat-ui chat-dock-ui parametric-role-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui parametric-graph-ui design-disciplines-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) + foreach(check surface-quality-ui surface-network-ui surface-operations-ui surface-offset-ui design-variants-ui component-library-ui design-review-ui inertial-ui viewport-quality-ui connectors-ui local-models-ui viewport-dock-ui context-ui suspension-ui assistant-steering-ui assistant-chat-ui chat-dock-ui parametric-role-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui parametric-graph-ui design-disciplines-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1440 900) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) endforeach() diff --git a/docs/README.md b/docs/README.md index 1d51858..c6de54c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,6 +29,10 @@ current release claim. [release.json](../release.json) owns application identity | [029B assembly scaling](ASSEMBLY_SCALING_029B.md) | You need selective memory/I/O and configuration/pin ownership in isolated workspaces | | [023B test guide](AUTHORING_023B_TESTING.md) | You are testing STEP/IGES import, Arkitfy, functional holes or isolated design containers | | [Parametric programs](PARAMETRIC_PROGRAMS.md) | You want a configurable family written as code: counts, conditions, generated sketches and design assertions | +| [068B surface quality and matching](SURFACE_QUALITY_068B.md) | You need native curvature/seam evidence or an explicitly reviewed boundary match | +| [068B curve networks and loft correspondence](SURFACE_NETWORK_068B.md) | You need exact compatible curve networks or typed section/seam controls | +| [068B grouped poles and surface operations](SURFACE_EDITING_068B.md) | You need locked/symmetric pole groups, explicit multi-face trims or hole-preserving extension | +| [068B offset and thickness checks](SURFACE_OFFSET_068B.md) | You need a checked native trial, curvature risk locations and explicit candidate publication | | [067G design variants](DESIGN_VARIANTS_067G.md) | You want saved configurations, visual comparison or bounded exploration of exact parametric alternatives | | [067G revision review and repair](DESIGN_REVIEW_067G.md) | You want to compare retained design revisions or preview an explicit failed-feature correction | | [067G drawing output and component library](DRAWING_LIBRARY_067G.md) | You want multipage PDF drawings, declared geometric tolerances or a visual reusable-component browser | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 15ad629..1418858 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,5 +1,12 @@ # ARK roadmap A–G +068B (**A.02/B.01/B.03/D.02 — Verificado no escopo local**): exact surface boundary +matching, loft correspondence, native curvature/seam analysis, grouped poles, +multi-face trim, trim-preserving extension/sewing diagnosis, curve networks and +checked offset/thickness workflows. Native 187/187 and affected Studio 14/14 passed; +32 boundary-orientation cases and a 32-check composed native/STEP workflow passed. +Broader milestones remain **Parcial**; see [068B evidence and limits](iterations/068B.md). + 067G (**B.02/B.03/B.04/B.05/D.02/D.05/F.03/G.02/G.03 — Verificado no escopo local**): persistent program variants and measured grid exploration, retained-revision comparison, reviewed repair of rejected edits, multipage vector PDF with declared diff --git a/docs/SURFACE_EDITING_068B.md b/docs/SURFACE_EDITING_068B.md new file mode 100644 index 0000000..1e1d9c9 --- /dev/null +++ b/docs/SURFACE_EDITING_068B.md @@ -0,0 +1,35 @@ +# Surface group editing and exact face sets — 068B + +**A.02 / B.01 / B.03 / D.02 — Verificado no escopo local.** See [068B verification](iterations/068B.md); broader milestones remain **Parcial**. + +## Groups of exact control poles + +`surface_control{action:group_plan}` extends the existing source-hash/revision-bound control-net contract. `selection` chooses explicit `poles:[[u,v],...]`, one `row` (`u`), one `column` (`v`) or a `rectangle` (`u_min/u_max/v_min/v_max`). `delta_mm` and `max_displacement_mm` are explicit. `influence_radius` is 0–32 **grid-index steps**, using smoothstep decay to zero; it is not a physical distance. `lock_boundaries` preserves named U/V boundary poles. A resulting edit must contain 1–128 nonzero displacements; oversized selections reject without truncation. + +Optional `symmetry:{direction:u|v,axis:x|y|z,origin_mm}` mirrors each selected pole to the reversed U or V index. The whole original control net must already be spatially mirrored within 1e-6 mm, paired rational weights must be equal, and knot multiplicities/reflected normalized knot positions must match (roundoff allowance 3e-14). Conflicting or locked partners reject. This maintains an explicitly declared existing symmetry; it does not guess a symmetry plane or remesh the surface. + +Plans expand to the existing `deform_poles` recipe and preserve degrees, knots, multiplicities and weights. Native validity, interference, sampled Jacobian and displacement guards remain in force. No new document semantic data is needed for group selection because the retained output is ordinary explicit pole edits. + +Studio **Group edit** (49506) exposes selection, displacement, influence, locks and mirror fields. Ctrl-click toggles poles; dragging a selected group moves all selected poles through the existing coalesced exact preview. Group-dialog previews replace the staged cage explicitly. Apply, Reset, Cancel, source revision/epoch invalidation and one Undo keep their existing behavior. + +## Trim selected faces as one operation + +`multi_trim_plan` accepts 1–16 source definitions (`sources:[id|{id,face}]`), one `tool_id`, and a definition-local `keep_points` XYZ for every source. A face in a multi-face or solid definition needs an exact semantic reference. To select several faces of the same producer, explicitly extract those faces first. At least one face must actually split; untouched selected faces remain. Every split region is measured and listed, and the keep point must select one interior region unambiguously. The result contains exactly one retained face per explicit source and is not silently sewn. + +The persisted SurfaceEdit operation is `multi_trim`; inputs hold sources followed by the cutter, which stays a separate output. Neither cutter extension nor tolerance enlargement is automatic. New operation semantics require version 57. + +## Extend a rectangular support while keeping holes + +`operations_inspect` returns exact source references and, for one open face, native UV bounds and hole count. `extend_trimmed_plan` accepts either explicit expanded `bounds` or existing bounded-support `extension:{direction,length_mm,continuity}`. The outer wire must be an exact rectangular UV boundary. Original inner wires and their native pcurves are retained, with native validity, positive added area, hole count and sampled original-support checks. + +Arbitrary outer trimmed contours, solids and multiple faces reject. This improves the supported rectangular-with-holes domain; it does not claim general trim-preserving NURBS extrapolation or global continuity certification. UV coordinates are native support parameters, not generally millimetres. Human-entered keep-point, UV-bound and extension-length expressions remain authored expressions after validation. The persisted operation is `extend_trimmed` and requires semantics 57. + +## Diagnose and sew explicit surface sets + +`sew_inspect` evaluates 2–16 exact face/shell definitions privately at the unchanged native sewing tolerance. It reports connected components, free boundaries, exact lengths/endpoints, source semantic-edge matches when topologically traceable, and nearest separated-boundary distances. A nearest edge is a diagnostic, not an authorized repair pairing. No face is dropped and no gap is healed by increasing tolerance. + +`sew_plan` prepares the existing Sew feature, with explicit `solid` and `require_connected`. Failure to close a solid rejects the candidate. Studio provides separate diagnostic and candidate-review actions; the actual evaluated candidate image is shown before Apply. Cancelling leaves the source design intact. + +## Verification scope + +`surface_operations_068b_tests.cpp` independently checks group falloff/locks/mirroring, basis preservation, native preview/persistence, analytic multi-face area conservation, ambiguous keep-point rejection, exact open-edge diagnostics, invalid solid sewing and analytic extended hole area. The existing surface-control UI test gains real group fields, four-pole preview, Apply and Undo; `surface_operations_selftest_068b.inl` exercises actual trim/sew controls and captures. No private drawing is a fixture. diff --git a/docs/SURFACE_NETWORK_068B.md b/docs/SURFACE_NETWORK_068B.md new file mode 100644 index 0000000..7f67cad --- /dev/null +++ b/docs/SURFACE_NETWORK_068B.md @@ -0,0 +1,35 @@ +# Curve networks and loft correspondence — 068B + +**B.03 / B.01 / A.02 / D.02 — Verificado no escopo local.** See [068B verification](iterations/068B.md); broader milestones remain **Parcial**. + +## Exact polynomial curve networks + +`surface_control` action `network_plan` takes explicit `u_curves` and `v_curves` arrays, each containing 2–9 native curve feature IDs or unique names, and `expected_revision`. Optional `name` labels the result. Inputs are definitions in one shared local frame; occurrence placement is not inferred. + +Each curve must contain one open, non-rational polynomial edge of degree 1–8: a line, Bezier, or equivalent clamped single-span B-spline. Unsupported rational, multispan, closed, singular or inconsistent networks reject. No input curve is silently fitted, reconstructed from a mesh, or discarded. + +`u_stations` specifies where the V-family curves cross each U curve; `v_stations` specifies the U-family positions on each V curve. Both are ordered normalized parameters, start at 0 and end at 1, and default to uniform spacing. Optional `u_reverse`/`v_reverse` boolean arrays explicitly reverse individual curves before checking crossings. Normalization refers to the exact polynomial parameter, not arc length. + +The worker exactly elevates compatible polynomial bases to a shared Bernstein basis (at least cubic in both directions, yielding at least 4×4 controls for subsequent matching/editing) and constructs the Gordon Boolean sum: + +`S(u,v) = sum_j L_j(v) C_j(u) + sum_i L_i(u) D_i(v) - sum_ij L_i(u)L_j(v) P_ij`. + +The retained `surface_edit` recipe uses `native.op:curve_network`, the ordered curve inputs, `u_count`, and optional station/reversal arrays. It recomputes from those editable native source curves. It does not retain copied B-reps. New recipes require conditional document semantics 57. + +All intersections are checked against the fixed 1e-6 mm position tolerance. The result is one native polynomial face stored in an exactly equivalent clamped B-spline basis for subsequent control-net editing, checked for B-rep validity and native self-interference. Independent 65-point checks on every source curve report measured preservation error; a 17×17 derivative grid rejects observed singular Jacobians. `global_injectivity_verified:false` remains explicit: samples do not prove all between-sample behavior. `curve_basis_identity` is true only when native crossing points coincide numerically without residual gap. + +The action returns a retained, validated `doc_preview` candidate and `network_evidence`. It does not publish. Apply the candidate at the observed revision; stale publication rejects. + +Studio **Surface from curve network** (49980) offers ordered source lists, optional station values and explicit reversal lists. It shows the actual evaluated candidate image and measured crossing/curve error before Apply or Cancel. + +## Loft correspondence diagnostics + +`surface_control` action `loft_diagnose` takes an existing loft `id`, or a proposed ordered `sections` list, with optional `guides` and `controls`, plus `expected_revision`. It reuses the normal native sketch/curve/datum profile resolution and section alignment. It returns topology, endpoint and 32/33-point arc-length correspondence measurements without publishing or silently choosing section direction. + +The report compares direct and reversed correspondence RMS distances. A materially shorter reversal is a review suggestion, not proof that the chosen loft twists or an instruction to reverse it automatically. Closed/open topology changes and different edge counts remain visible. The final loft still passes its existing geometry and guide-deviation checks; diagnostics do not relax those tolerances. + +Studio **Loft section correspondence** replaces the previous alignment JSON input with typed per-section direction, seam edge and circle seam angle controls. It preserves settings by section name when explicitly reordering, displays measured preflight evidence, then previews the complete loft before publishing. **Loft diagnostics** (49981) opens the read-only report for the selected loft. + +## Verification scope + +Native tests compare a six-curve network against an independently defined biquadratic analytic surface throughout a 13×11 grid, exercise exact curve reversal, inconsistent crossings, station/tolerance rejection and reversed loft diagnostics. Host tests cover candidate isolation, revision rejection, editable source dependencies and save/reopen/recompute. Studio tests exercise real forms, candidate cancellation, publication, typed alignment, diagnostics and persistence. All fixtures are synthetic; no manufacturing or global continuity qualification is implied. diff --git a/docs/SURFACE_OFFSET_068B.md b/docs/SURFACE_OFFSET_068B.md new file mode 100644 index 0000000..86b9f54 --- /dev/null +++ b/docs/SURFACE_OFFSET_068B.md @@ -0,0 +1,49 @@ +# Checked surface offsets and thickness — 068B + +**A.02 / B.03 / D.02 — Verificado no escopo local.** The following contract separates exact +candidate checking from sampled curvature screening and manufacturing approval. + +`surface_control` adds two actions, both requiring the observed +`expected_revision`, one feature `id`, `mode:offset|thicken`, a signed `amount` +in millimetres or a named parameter expression, and optional `samples` from 3 +to 33 per UV direction. + +- `offset_check` privately evaluates the native construction and reports current + B-rep topology/interference checks, per-face curvature samples and located + candidate faults when the native checker provides them. +- `offset_plan` additionally requires the inspected `source_brep_sha256`. It + rejects failed trials, creates an ordinary retained `doc_preview` candidate, + and leaves publication to explicit `doc_apply` at the same revision. + +The diagnostic accepts face/shell sources with 1–64 faces. UV points outside +trimmed regions are excluded; undefined curvature stays explicitly counted. +`sampled_min_radius_mm` is null for planar or unavailable samples. Hotspots are +the highest sampled ratios between absolute requested length and curvature +radius. Their locations come from native surface derivatives, but those ratios +are independent of offset sign and are **risk indicators, not a proven failure +cause or a continuous bound**. Native fault bounds describe actual rejected +candidate subshapes; a builder failure without such shapes remains unlocalized. + +The ordinary offset and thickness producers also check their resulting shape +with `BRepAlgoAPI_Check` (topology/self-interference, without using its small-edge +filter to discard geometry). Restored offset/thickness geometry is checked again. +The producer reports `offset_intersection_checked` or +`self_interference_checked`; this is a named native check, not a proof that every +possible surface defect has been excluded. No thickness, tolerance, source +surface or solid is silently changed to make an operation pass. + +Studio exposes **Check surface offset / thickness**, native risk markers, +**Offset diagnostic details**, and **Preview checked offset / thickness**. +The preview shows the actual candidate image and offers Apply/Cancel. Applying +creates one derived definition; existing assembly placements stay unchanged. +Markers follow the inspected occurrence frame and disappear when it is hidden, +replaced or moved. Publication still checks document revision/epoch and source +geometry. Undo restores the prior document. + +Verification source: `surface_offset_068b_tests.cpp` independently compares a +20×20×2 thickness with 800 mm³, checks planar sample accounting, and compares the +centre curvature radius of an authored parabolic cylinder with 10 mm. It also +checks no-mutation diagnostics, retained preview, explicit apply, Undo, stale +revision/hash rejection and invalid inputs. The Studio selftest uses actual +forms, candidate image, Cancel/Apply and stale rejection. Executed results and +captures are recorded in the iteration evidence. diff --git a/docs/SURFACE_QUALITY_068B.md b/docs/SURFACE_QUALITY_068B.md new file mode 100644 index 0000000..13c8279 --- /dev/null +++ b/docs/SURFACE_QUALITY_068B.md @@ -0,0 +1,27 @@ +# Surface matching and analysis — 068B + +**A.02 / B.01 / B.03 / D.02 — Verificado no escopo local.** See [068B verification](iterations/068B.md); broader milestones remain **Parcial**. + +The existing `surface_control` tool has three additional actions. They require the observed `expected_revision`, an exact source feature and an optional semantic face reference. A multi-face source requires an explicit face. + +- `quality` samples native D2 surface derivatives on a 3–65 square UV grid (default 17). It reports signed principal, mean and Gaussian curvature, positions and normals. Points outside trimmed regions and singular samples remain explicit. The grid does not certify extrema between samples. Nonrectangular or holed trims render classified sample points rather than interpolated cells that could bridge holes. +- `seam` samples explicit natural sides (`u_min`, `u_max`, `v_min`, `v_max`) of source and target faces, with optional reversed correspondence and 3–129 checkpoints. The report separates position gap, unoriented tangent-plane angle and the native second-fundamental-form tensor in a common tangent basis. Sides crossing outside a trimmed face reject. This is not arbitrary edge-chain matching. +- `match_plan` prepares one cached `doc_preview` candidate. It needs source/target B-rep hashes, explicit sides, continuity 0/1/2, a positive `max_displacement_mm`, and optional positive `cross_scale` (default 1). Review the candidate and apply its ID with the same revision. + +Matching currently accepts open clamped untrimmed **non-rational BSpline** faces with compatible tangential degrees, pole counts and normalized knot vectors (including multiplicities). Reverse correspondence is explicit. No hidden resampling, tolerance increase or rational-weight approximation occurs. Incompatible inputs reject and leave the source unchanged. + +G0 adjusts the boundary row; G1 also adjusts the first interior row; G2 also adjusts the second interior row. Source normal degree and row count must support the requested order while retaining the opposite boundary. Normalized parameter derivatives establish correspondence; `cross_scale` controls cross-boundary derivative magnitude. The exact source basis and target surface remain unchanged. Every moved pole respects the declared displacement bound. + +The resulting native face passes B-rep validity/interference checks and a 17×17 regular-Jacobian check. Independent native D2 seam measurements verify the requested continuity at checkpoints: position ≤1e-6 mm, angle ≤0.001 degrees, curvature-tensor difference ≤0.0001/mm. `global_continuity_verified` remains false. The checks are not a proof between samples or manufacturing qualification. + +The retained `surface_edit` recipe uses `native.op:match_boundary` with source and target as dependencies, current hashes and explicit references. The source is consumed as the edited output; the target remains a separate output. Changed dependencies require a new inspected plan. The recipe does not embed target B-rep bytes. + +## Studio + +**Surface quality** displays a native-sampled curvature map or camera-dependent zebra reflections. Blue means low absolute principal curvature; red means the report's maximum. Zebra stripes and interpolated triangles are display diagnostics; they never select production geometry. The report retains exact sample statistics and trim/singularity counts. + +Pair forms use explicit readable ID-qualified feature dropdowns and optional semantic face fields. In an assembly, the source dropdown retains the occurrence selected before opening; choosing a target never changes that source frame. Ambiguous or different target frames reject. + +**Check surface seam** displays the two sampled boundaries and gap connectors, alongside numeric evidence. **Match surface boundary** opens explicit source/target/side/continuity/displacement controls, displays the checked exact candidate in cyan, and requires a separate **Apply surface match**. **Hide surface analysis** cancels the visual review. Revision/document, source/target visibility or retained occurrence-frame changes invalidate overlays and reject stale Apply. Placed geometry requires a selected source and a unique target in the same authored occurrence frame; transient display poses reject. In an assembly, Match offers an explicit choice between **New occurrence in source frame** and **Definition only**. The new occurrence uses the candidate's actual feature ID and is included in the same reviewed atomic preview. Original occurrences are never silently retargeted; definition-only deliberately adds no placement. + +Validation sources: `tests/surface_quality_068b_tests.cpp` checks analytic parabolic-cylinder curvature, independently expected G0/G1/G2 pole rows, exact tensor readback, source preservation, hash/bounds/tolerance rejection, target visibility and save/recompute. `surface_quality_selftest_068b.inl` exercises actual controls, all three display modes, matching preview/apply/undo and stale rejection on synthetic surfaces. diff --git a/docs/SURFACING.md b/docs/SURFACING.md index b0b13f1..09cc4c3 100644 --- a/docs/SURFACING.md +++ b/docs/SURFACING.md @@ -129,7 +129,11 @@ origin. A full turn is the closed revolution, not a 360-degree seam. `offset_surface` takes one preceding face or shell. Solids are rejected; use `thicken` for a solid. `p.distance` is signed and must exceed 1e-6 mm in -magnitude. The report sets `offset_intersection_checked` to false. +magnitude. From 068B the producer and restored offset/thickness geometry also +pass the native self-interference check; offset reports +`offset_intersection_checked:true`. Use `surface_control` action `offset_check` +for explicit trials, located candidate faults and sampled curvature risk. +This native check is not a global mathematical or manufacturing certificate. `sew` takes 2 to 16 face or shell inputs at the 1e-6 mm tolerance. `p.solid` defaults to `0` and is accepted only when the result is one shell with no free edges. The report includes `free_edges`. diff --git a/docs/iterations/068B.md b/docs/iterations/068B.md new file mode 100644 index 0000000..c8a67e2 --- /dev/null +++ b/docs/iterations/068B.md @@ -0,0 +1,74 @@ +# 068B — exact surface modeling and inspection + +Runtime **068B / 0.9.69**. **A.02 / B.01 / B.03 / D.02 — Verificado no escopo local**. Broader roadmap milestones remain **Parcial**. + +## Delivered capabilities + +| Capability | Implemented scope | +|---|---| +| Match Surface | Explicit natural-side G0/G1/G2 matching of compatible open, untrimmed, non-rational BSpline faces; source/target hashes, movement bounds, fixed opposite boundary and independently sampled native jets. | +| Loft correspondence | Typed direction/seam controls per section, unique source closure, explicit guide settings and measured preflight diagnostics; no automatic reversal or hidden rematching. | +| Surface analysis | Native principal/mean/Gaussian curvature samples, seam position/tangent/tensor checks, curvature display and continuous display zebra bands. Nonrectangular/holed trims display classified samples without filling their holes. | +| Grouped poles | Pole/row/column/rectangle selection, explicit movement and influence, locked boundaries and verified symmetry of the full pole grid, rational weights and reflected knot basis. | +| Trim / Extend / Sew | Multiple explicit source faces and keep points; area accounting; rectangular-support extension preserving inner holes and authored expressions; exact free-edge/gap diagnosis and reviewed sewing. | +| Curve networks | Exact compatible polynomial Gordon construction from two explicit curve families; cubic-or-higher BSpline output stays editable and can feed control-pole and matching tools. | +| Offset / thickness | Actual native trials, located candidate faults when available, native curvature-risk samples, reviewed candidate publication and topology/self-interference checks on production and restored geometry. | + +Use **All tools / Ctrl+K → Surface modeling and quality**. Existing surface-control editing exposes **Group edit**. All new authoring paths preserve Preview/Apply/Cancel, current revision and Undo. The Match form uses explicit source/target dropdowns; in assemblies it offers a reviewed new occurrence in the selected source frame or definition-only output. Other new surface constructors report their definition-local scope. + +Contracts: [matching/analysis](../SURFACE_QUALITY_068B.md), [networks/lofts](../SURFACE_NETWORK_068B.md), [group editing and face sets](../SURFACE_EDITING_068B.md), [offset/thickness](../SURFACE_OFFSET_068B.md). + +## Authority and persistence + +- B-rep and explicit producer inputs remain geometry authority. Display colors, interpolated bands, normals and thumbnails never select production geometry. +- The existing `surface_control` tool exposes the extensions; catalogue size remains 124. Cached plans stay in their owning session, are excluded from disposable exact-read jobs/batched postconditions, and retain Team ownership with normal command-scope checks. +- Source/target hashes and observed revisions reject stale writes. No tolerance inflation, automatic reference substitution, hidden fragment loss or silent rebase is introduced. +- New persisted `match_boundary`, `curve_network`, `multi_trim` and `extend_trimmed` recipes conditionally require document semantics 57. Existing models and grouped-pole recipes keep their prior conditional format. The app iteration alone never changes a document version. +- Native offset/thickness validation also runs during cached B-rep restoration; old cached reports do not bypass current checks. + +## Observed local verification + +| Check | Result | +|---|---| +| Native CTest | **187/187 passed** | +| Affected Studio suites | **14/14 passed**: surface controls/workflow/quality/network/operations/offset, asynchronous authoring, realtime, authoring assistance, scrolling editor, native picking, parametric authoring, action icons and Skeleton editor | +| Native quality/matching | **71 assertions** including independent parabolic-cylinder curvature, G0/G1/G2, source/target preservation, stale/bounded-domain rejection and trimmed display classification | +| Boundary orientation matrix | **32/32** source-side × target-side × reversed-correspondence cases;129 checkpoints and opposite boundary preservation per case | +| Networks and lofts | **452 native assertions + 28 host assertions**, independent polynomial surface samples, crossings/reversal rejection, exact degree elevation, editable poles and persistence | +| Groups / face operations | **90 assertions**, including 240mm² multi-trim, 336mm² extension without holes, 336−π mm² with a retained circular hole, symmetry/weights/locks and explicit failure reasons | +| Offset / thickness | **32 assertions**, independent 800 mm³ planar thickness and 10 mm parabolic-cylinder curvature radius, candidate custody and stale-input rejection | +| Existing control-editor UI | **103 checks**, including the new grouped-pole preview/apply/Undo path | +| Composed MCP workflow | **32 checks**, all requested operations accepted in the declared compatible synthetic case; see below | + +UI tests exercise actual controls, readable source selectors, unique-name rejection, bitmap previews, Cancel/Apply, Undo, correct result selection, revision/epoch guards, hidden/moved references and explicit assembly placement. The shared preview editor now supports an actual bitmap alongside a multiline measured report with a bounded footer; a compact-work-area test verifies nonuniform image pixels and nonoverlapping image/report/Apply controls. + +Normal, compact and scrollable forms, curvature/zebra/seam overlays, matched surfaces, grouped poles, network/loft previews, trim/extension/sewing results and offset/thickness previews were inspected. After the final string-only Match label/hint shortening, all five selected surface/editor suites passed again; the final Match form and offset preview were inspected. Receipts remain under the local build output. + +### Composed fixture and independent checks + +The final native binaries ran this synthetic sequence: + +1. Construct two compatible cubic Gordon-network surfaces and inspect their control nets. +2. Move interior poles by 0.4 mm while locking boundary poles. +3. Match G2 to the second surface: initial 3 mm gap / 1.718358 degrees / 0.00848528 mm⁻¹ tensor error became 0 gap / 0 angle / 8.538×10⁻¹⁹mm⁻¹ over 65 native checkpoints. +4. Inspect 81 curvature samples, sew two faces into one connected open shell and create checked 0.25 mm thickness. +5. Export STEP, read it back, save/reopen the editable document and re-inspect the seam. Original source/target B-rep hashes remained unchanged. + +The native volume was 301.5157897318 mm³ versus 301.5157896956 mm³ from independent integration of the explicit analytic offset strip (difference 3.62×10⁻⁸mm³). STEP readback differed by 8.6×10⁻¹¹mm³. This is a local OCCT/ARK round trip, not independent-recipient CAD or manufacturing qualification. The final-byte receipt, reproducible harness and synthetic outputs are retained under `verification-068b/surface-interop-release` in the local build tree. + +## Failures retained and resolved + +- Compile integration found missing helper/header declarations, an unsupported OpenGL token, a deleted neighboring legacy function and the long command-line parser's compiler nesting limit. The original neighboring functions were restored and the new flags parse independently. +- Native SDK inspection corrected an arclength solver overload: its fourth argument was an initial guess, not a tolerance. Native/host tests were rerun after the correction. +- Initial UI tests exposed names treated as numeric expressions and a fixture missing expected_revision. Unique-name/ID resolution and explicit revision binding fixed these paths. +- Extension without holes exposed a native builder state assumption: a face-copy builder was not marked done until an inner wire was added. The already validated extended face now handles the zero-hole case; both holed and unholed analytic-area regressions pass. +- Review screenshots exposed a missing bitmap and overlapping multiline footer. The shared editor now displays/scales the actual candidate image and bounds the report above Apply/Cancel. +- Visual/interaction review corrected per-triangle zebra artifacts, clipped essential units, stale occurrence overlays, paired-picker ambiguity, unintended loft dependencies and result selection after Apply. + +## Limits + +Matching requires the documented compatible polynomial BSpline boundary basis; rational, periodic, trimmed or incompatible cases reject. Networks support 2–9 curves per family in the documented single-span polynomial domain, not arbitrary rational/multispan reconstruction. Group editing keeps the existing bounded control-net domain; boundary locks preserve positions, not automatically G1/G2 derivatives. + +Continuity, curvature and deformation samples do not certify between-sample extrema or global continuity/injectivity. Native interference checking is explicitly identified and is not a universal mathematical proof. Extension requires the supported rectangular outer UV boundary; arbitrary trim extension remains unsupported. Sewing reports gaps but does not enlarge tolerances to heal them. Offset risk points alone are not proof of the failure location. + +Only the affected 14 Studio suites were run here; historical unrelated failures are not declared repaired. There was no real-model quality/cost comparison, physical manufacturing qualification, clean-machine audit, signing or online-update deployment. User drawings and the live installed application remain outside test fixtures. diff --git a/include/ark/native_features.hpp b/include/ark/native_features.hpp index da7b26a..91cf1e0 100644 --- a/include/ark/native_features.hpp +++ b/include/ark/native_features.hpp @@ -5,6 +5,8 @@ namespace ark { bool isNativeFeature(FeatureType type); +// Private inspection callers use the same authoritative loft profile resolver. +arkjson::Value surfaceRequestForInspection068B(Document&,const Feature&); Body evaluateNativeFeature(const Feature& feature, const ExprEnv& env, Document& document, std::vector& preceding); // Materialize exact geometry from a prior feature's analytic parameters only diff --git a/include/ark/surface_edit_059c.hpp b/include/ark/surface_edit_059c.hpp index fea6c30..6baf9c8 100644 --- a/include/ark/surface_edit_059c.hpp +++ b/include/ark/surface_edit_059c.hpp @@ -5,4 +5,10 @@ namespace ark { arkjson::Value surfaceControlSchema059(); // Read-only exact inspection and explicit revision-bound SurfaceEdit plans. arkjson::Value surfaceControl059(AgentSession&, const arkjson::Value&); +// These plans retain a candidate in the owning session. A disposable exact-read +// worker or a batched postcondition cannot own the later explicit publication. +inline bool surfaceControlRetainsCandidate068B(const arkjson::Value& args){ + const auto* action=args.find("action");if(!action||action->t!=arkjson::Value::Str)return false; + const auto& value=action->str;return value=="match_plan"||value=="network_plan"||value=="multi_trim_plan"||value=="extend_trimmed_plan"||value=="sew_plan"||value=="offset_plan"; +} } diff --git a/include/ark/surface_network_068b.hpp b/include/ark/surface_network_068b.hpp new file mode 100644 index 0000000..da0e1ca --- /dev/null +++ b/include/ark/surface_network_068b.hpp @@ -0,0 +1,6 @@ +#pragma once +#include "ark/agent.hpp" +namespace ark { +bool surfaceNetworkTool068B(AgentSession&,const arkjson::Value&,arkjson::Value&); +void extendSurfaceNetworkSchema068B(arkjson::Value&); +} diff --git a/include/ark/surface_offset_068b.hpp b/include/ark/surface_offset_068b.hpp new file mode 100644 index 0000000..8f5bf7c --- /dev/null +++ b/include/ark/surface_offset_068b.hpp @@ -0,0 +1,6 @@ +#pragma once +#include "ark/agent.hpp" +namespace ark { +bool surfaceOffsetTool068B(AgentSession&,const arkjson::Value&,arkjson::Value&); +void extendSurfaceOffsetSchema068B(arkjson::Value&); +} diff --git a/include/ark/surface_operations_068b.hpp b/include/ark/surface_operations_068b.hpp new file mode 100644 index 0000000..8251433 --- /dev/null +++ b/include/ark/surface_operations_068b.hpp @@ -0,0 +1,6 @@ +#pragma once +#include "ark/agent.hpp" +namespace ark { +bool surfaceOperationsTool068B(AgentSession&, const arkjson::Value&, arkjson::Value&); +void extendSurfaceOperationsSchema068B(arkjson::Value&); +} diff --git a/include/ark/surface_quality_068b.hpp b/include/ark/surface_quality_068b.hpp new file mode 100644 index 0000000..c23cb38 --- /dev/null +++ b/include/ark/surface_quality_068b.hpp @@ -0,0 +1,6 @@ +#pragma once +#include "ark/agent.hpp" +namespace ark { +bool surfaceQualityTool068B(AgentSession&,const arkjson::Value& args,arkjson::Value& result); +void extendSurfaceQualitySchema068B(arkjson::Value& schema); +} diff --git a/release.json b/release.json index 1a68d00..ad80969 100644 --- a/release.json +++ b/release.json @@ -1,17 +1,12 @@ { - "sequence": 67, - "phase": "G", - "code": "067G", - "version": "0.9.68", + "sequence": 68, + "phase": "B", + "code": "068B", + "version": "0.9.69", "milestones": [ - "B.02", + "A.02", + "B.01", "B.03", - "B.04", - "B.05", - "D.02", - "D.05", - "F.03", - "G.02", - "G.03" + "D.02" ] } diff --git a/src/agent_features.cpp b/src/agent_features.cpp index 5466530..11e06a3 100644 --- a/src/agent_features.cpp +++ b/src/agent_features.cpp @@ -10,6 +10,10 @@ #include "ark/inertial_simulation.hpp" #include "ark/rubber.hpp" #include "ark/surface_edit_059c.hpp" +#include "ark/surface_quality_068b.hpp" +#include "ark/surface_network_068b.hpp" +#include "ark/surface_operations_068b.hpp" +#include "ark/surface_offset_068b.hpp" #include "ark/manufacturing.hpp" #include "ark/component_library_tools.hpp" #include "ark/result_path.hpp" @@ -104,6 +108,7 @@ void validateBatchQuery(const V& query,size_t index){ if(const auto* cap=query.find("max_bytes");cap&&(cap->t!=V::Num||!std::isfinite(cap->num)||std::floor(cap->num)!=cap->num||cap->num<256||cap->num>262144))throw std::runtime_error(prefix+" max_bytes must be an integer from 256 to 262144"); const auto name=text(query,"tool");if(!batchTool(name))throw std::runtime_error(prefix+" tool is not allowed: "+name+"; use the query_batch tool enum; mutation, export and recursive batches are excluded"); const auto& args=required(query,"args");if(args.t!=V::Obj)throw std::runtime_error(prefix+" args must be an object"); + if(name=="surface_control"&&surfaceControlRetainsCandidate068B(args))throw std::runtime_error(prefix+" surface candidate plans require a direct owning-session call"); if(name=="library_vendors"&&(!args.find("operation")||args.find("operation")->asStr()!="list"))throw std::runtime_error(prefix+" library_vendors requires operation:list; policy updates cannot be batched reads"); if(name=="agent_onboard"){const auto* detail=args.find("detail");if(!detail||detail->t!=V::Str||detail->str!="guide")throw std::runtime_error(prefix+" agent_onboard requires explicit detail:guide; document inventory is excluded from batched onboarding");} if(const auto* fields=query.find("fields")){ @@ -172,6 +177,7 @@ void capBatchRow(V& row,const V& query,size_t index){ } V queryValue(AgentSession& s,const V& spec){ const auto tool=text(spec,"tool");if(!queryTools.count(tool))throw std::runtime_error("Condition requires an allowed read-only query"); + if(tool=="surface_control"&&surfaceControlRetainsCandidate068B(required(spec,"args")))throw std::runtime_error("Surface candidate plans are not postcondition reads"); V data=payload(s.call(tool,required(spec,"args")));const std::string path=text(spec,"path");const V* value=&data;size_t start=0; while(startt!=V::Num||expected->num!=(double)s.revision))throw std::runtime_error("Revision conflict; inspect current document before reading wood cutlist");out=inspectWood(s.document,s.revision);} else if(tool=="geometry_query")out=geometry(s,args); @@ -329,6 +335,7 @@ bool callAgentFeature(AgentSession& s,const std::string& tool,const V& args,V& o V executed=submitted,row; if(!blocked.empty()){row=V::makeObj();row.set("isError",V::makeBool(true));V error=V::makeObj();error.set("error_code",V::makeStr("QUERY_BATCH_ROW_SKIPPED"));error.set("error",V::makeStr("Not run: query '"+blocked+"', which this query references, failed or was skipped."));error.set("skipped_due_to",V::makeStr(blocked));batchContent(row,error);} else if(!references.empty()&&!resolveBatchReferences(executed,outputs,failure)){row=V::makeObj();row.set("isError",V::makeBool(true));V error=V::makeObj();error.set("error_code",V::makeStr("QUERY_BATCH_REF_UNRESOLVED"));error.set("error",V::makeStr("Not run: "+failure));batchContent(row,error);} + else if(text(query,"tool")=="surface_control"&&surfaceControlRetainsCandidate068B(executed))throw std::runtime_error("Surface candidate plans require a direct owning-session call, not a resolved batch reference"); else row=s.call(text(query,"tool"),executed); // References read the full result, before this row's own projection. if(const auto* id=query.find("id")){if(required(row,"isError").b)unavailable.insert(id->str);else outputs[id->str]=required(row,"structuredContent");} @@ -423,7 +430,7 @@ void appendAgentFeatureTools(V& tools){ {"manufacturing_propose","Prepare an explicit bounded editable design candidate for a current versioned DFM recommendation. Requires observed expected_revision, feature id, rule_id and rule_version and 1..8 commands. Exact before/after manufacturing reports use identical process/material declarations, expose all rule changes and unresolved checks. Geometry stays uncommitted; accept only after review with doc_apply{candidate_id,expected_revision,accept_dfm:true}. No automatic repair, cost optimization or manufacturing qualification.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0},"id":{"type":["integer","string"]},"rule_id":{"type":"string"},"rule_version":{"type":"integer","minimum":1},"commands":{"type":"array","minItems":1,"maxItems":8,"items":{"type":"object"}},"checks":{"type":"array"}},"required":["expected_revision","id","rule_id","rule_version","commands"],"additionalProperties":false})"}, {"manufacturing_inspect","Read declared fabrication route/process inputs, current exact B-rep evidence, route-specific design requirements, blockers and unknown checks. Each component includes dfm: versioned laser/bend/FDM/CNC/weld rules, explicit evidence/assumptions and typed recommendations; compatible screens do not qualify manufacture. id selects a feature by id/name; otherwise declared and output definitions. Call manufacturing onboarding for process field contracts. Solid-equivalent filament arithmetic is not slicer consumption. No geometry mutation or manufacturing certification.",R"({"type":"object","properties":{"id":{"type":["integer","string"]}},"additionalProperties":false})"}, {"rubber_plan","Plan editable rubber bodies, preview indexed 3D surface patterns, and discover real-time deformable studies. Read-only; agent_onboard topic rubber.",R"({})"}, - {"surface_control","Inspect exact BSpline control nets, find nearby exact vertices and prepare bounded pole-stretch or corner/tangent glue plans. Read-only; load surfacing onboarding.",R"({})"}, + {"surface_control","Inspect exact surfaces/control nets; native curvature/seam/loft/offset/sewing diagnostics, bounded group edits, boundary matching, curve networks, multi-trim and trim-preserving extension. Plans are uncommitted; explicitly review/apply their returned candidate or preview recipe. Load surfacing onboarding.",R"({})"}, {"physics_inspect","Inertial simulation through simulation:{action:capabilities|run,backend:gpu|cpu,...} with expected_revision: exact CAD mass/inertia, convex mesh contacts, gravity, force, torque and unlimited revolute joints; revision-bound display frames only, no FEA or CCD. Default static mode returns exact rigid-body mass, uniform-gravity CG, world inertia and instantaneous force/torque/energy balance. id selects one feature; otherwise visible assembly instances or unconsumed solids. Missing density rejects aggregate mass. SI loads and kinematics; positions mm. Optional support polygon checks gravity-only projection, not contact dynamics. axial_test uses declared material modulus and uniform cross-section; no FEA. beam_test: declared prismatic Euler-Bernoulli point-load bending and optional ideal Euler buckling. weld_test: uniform direct load on declared effective throat. These two tests work without aggregate mass; no geometry inference or production qualification.",R"({"type":"object","properties":{"id":{"type":["integer","string"]},"gravity":{"type":"array","minItems":3,"maxItems":3,"items":{"type":"number"}},"reference_point_mm":{"type":"array"},"loads":{"type":"array","maxItems":64,"items":{"type":"object"}},"velocity_m_s":{"type":"array"},"angular_velocity_rad_s":{"type":"array"},"acceleration_m_s2":{"type":"array"},"angular_acceleration_rad_s2":{"type":"array"},"support":{"type":"object","properties":{"origin_mm":{"type":"array"},"normal":{"type":"array"},"polygon_mm":{"type":"array"}},"required":["origin_mm","normal","polygon_mm"]},"axial_test":{"type":"object","properties":{"material":{"type":"string"},"force_N":{"type":"number"},"area_mm2":{"type":"number"},"length_mm":{"type":"number"}},"required":["material","force_N","area_mm2","length_mm"]},"beam_test":{"type":"object","properties":{"material":{"type":"string"},"support":{"enum":["cantilever_tip","simply_supported_center"]},"length_mm":{"type":"number","exclusiveMinimum":0},"second_moment_mm4":{"type":"number","exclusiveMinimum":0},"extreme_fiber_mm":{"type":"number","exclusiveMinimum":0},"force_N":{"type":"number"},"buckling":{"type":"object","properties":{"minimum_second_moment_mm4":{"type":"number","exclusiveMinimum":0},"area_mm2":{"type":"number","exclusiveMinimum":0},"effective_length_factor":{"type":"number","exclusiveMinimum":0},"compression_N":{"type":"number","minimum":0}},"required":["minimum_second_moment_mm4","area_mm2","effective_length_factor","compression_N"]}},"required":["material","support","length_mm","second_moment_mm4","extreme_fiber_mm","force_N"]},"weld_test":{"type":"object","properties":{"effective_throat_mm":{"type":"number","exclusiveMinimum":0},"effective_length_mm":{"type":"number","exclusiveMinimum":0},"force_N":{"type":"number"},"allowable_stress_Pa":{"type":"number","exclusiveMinimum":0}},"required":["effective_throat_mm","effective_length_mm","force_N"]}}})"}, {"wood_inspect","Read authored Wood blank dimensions, grain and BOM occurrence quantities including hidden copies. Retains supported single-input machining lineage. No cutting allowance, structural or manufacturing qualification is inferred.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0}},"additionalProperties":false})"}, {"materials_inspect","List document materials, declared density in kg/m3 and g/cm3, SI elastic properties and assigned features. material.set accepts density (g/cm3) OR density_kg_m3, plus optional physical:{young_modulus_Pa,poisson_ratio,yield_strength_Pa,thermal_expansion_per_K}. Zero density means unspecified. Values are caller declarations, not a certified material database.",R"({"type":"object"})"}, @@ -440,7 +447,7 @@ void appendAgentFeatureTools(V& tools){ V props=*schema.find("properties"),revision=V::makeObj();revision.set("type",V::makeStr("integer"));revision.set("minimum",V::makeNum(0));props.set("expected_revision",revision);props.set("simulation",inertialSimulationSchema());props.set("rubber",rubberStudySchema());schema.set("properties",props); } if(std::string(d.name)=="rubber_plan")schema=rubberPlanSchema(); - if(std::string(d.name)=="surface_control")schema=surfaceControlSchema059(); + if(std::string(d.name)=="surface_control"){schema=surfaceControlSchema059();extendSurfaceQualitySchema068B(schema);extendSurfaceNetworkSchema068B(schema);extendSurfaceOperationsSchema068B(schema);extendSurfaceOffsetSchema068B(schema);V required=V::makeArr();required.arr={V::makeStr("action"),V::makeStr("expected_revision")};schema.set("required",required);} if(std::string(d.name)=="query_batch"){ V props=*schema.find("properties"),queries=*props.find("queries"),item=*queries.find("items"),fields=*item.find("properties"),name=*fields.find("tool"),names=V::makeArr();for(const auto& allowed:queryTools)names.arr.push_back(V::makeStr(allowed));names.arr.push_back(V::makeStr("agent_onboard"));name.set("enum",names);fields.set("tool",name);item.set("properties",fields);queries.set("items",item);props.set("queries",queries);schema.set("properties",props); arkjson::parse(R"({"type":"object","properties":{"results":{"type":"array","items":{"type":"object","properties":{"query_index":{"type":"integer","minimum":0},"tool":{"type":"string"},"args":{"type":"object"},"isError":{"type":"boolean"},"structuredContent":{"type":"object","description":"A result or explicit row error. QUERY_BATCH_FIELD_MISSING includes query_index, tool, requested_fields, missing_fields, available_fields, tool_succeeded:true, observed_result and recovery:{action:reuse_observed_result,tool,args,hint}."},"content":{"type":"array"},"resolved_args":{"type":"object","description":"Arguments actually executed after resolving $ref values."},"elapsed_ms":{"type":"number","minimum":0}},"required":["query_index","tool","args","structuredContent","content","isError","elapsed_ms"]}},"revision":{"type":"integer"},"error_count":{"type":"integer","minimum":0,"maximum":128}},"required":["results","revision","error_count"]})",output); diff --git a/src/agent_team.cpp b/src/agent_team.cpp index c3194a0..44afd4e 100644 --- a/src/agent_team.cpp +++ b/src/agent_team.cpp @@ -740,7 +740,7 @@ struct AgentTeam::Impl { if(!isError(result)&&name=="doc_info"){std::uint64_t observed;if(receiptRevision(payload(result),observed)){std::lock_guard lock(mutex);roles[index].view.needsInspection=false;roles[index].hasInspectedRevision=true;roles[index].inspectedRevision=observed;}} if(!isError(result)){std::lock_guard lock(mutex);const auto project=field(payload(result),"activity_project_id");const bool changed=!project.empty()&&!preparedProjectId.empty()&&project!=preparedProjectId;const bool boundary=explicitProjectBoundary(actualName,actual,result)||changed;if(boundary){clearPreparedLocked();documentRevisionKnown=false;}std::uint64_t observed=0;if(receiptRevision(payload(result),observed)&&(!documentRevisionKnown||observed>=documentRevision)){documentRevisionKnown=true;documentRevision=observed;}if(!project.empty())preparedProjectId=project;outcomeProjectEpoch=preparedProjectEpoch;} const auto previewAction=field(args,"action"); - const bool programPreview=(name=="parametric_program"&&previewAction=="prepare")||(name=="design_variants"&&(previewAction=="prepare"||previewAction=="save"||previewAction=="remove"))||(name=="design_review"&&previewAction=="prepare_repair"); + const bool programPreview=(name=="parametric_program"&&previewAction=="prepare")||(name=="design_variants"&&(previewAction=="prepare"||previewAction=="save"||previewAction=="remove"))||(name=="design_review"&&previewAction=="prepare_repair")||(name=="surface_control"&&previewAction.size()>=5&&previewAction.compare(previewAction.size()-5,5,"_plan")==0); if(!isError(result)&&(name=="doc_preview"||name=="manufacturing_propose"||programPreview)&&roles[index].config.canWrite){const auto& proof=payload(result);const auto* valid=proof.find("valid");const auto* cached=proof.find("candidate_cached");const auto* recipe=proof.find("recipe");const auto candidate=field(proof,"candidate_id");std::uint64_t observed=0; bool receiptMatches=valid&&valid->t==V::Bool&&valid->b&&cached&&cached->t==V::Bool&&cached->b&&recipe&&recipe->t==V::Obj&&!candidate.empty()&&candidate.size()<=256&&receiptRevision(proof,observed)&&revision(actual)&&observed==(std::uint64_t)actual.find("expected_revision")->num&&(programPreview||samePreparedRecipe(*recipe,authorized)); // Host-generated candidates still require this role's ordinary command scope checks. diff --git a/src/assistant.cpp b/src/assistant.cpp index 4d541b8..0d64585 100644 --- a/src/assistant.cpp +++ b/src/assistant.cpp @@ -1,3 +1,4 @@ +#include "ark/surface_edit_059c.hpp" #include "ark/assistant.hpp" #include "ark/project_memory_tools.hpp" #include "ark/assistant_claude_code.hpp" diff --git a/src/assistant_steering.inl b/src/assistant_steering.inl index 0a55ec3..d0f4ce3 100644 --- a/src/assistant_steering.inl +++ b/src/assistant_steering.inl @@ -1,5 +1,6 @@ bool assistantToolReadOnly(const V& tools,const std::string& name,const V& args){ if(name=="tool_feedback")return true; + if(name=="surface_control"&&surfaceControlRetainsCandidate068B(args))return false; if(name=="snapshot"&&args.t==V::Obj&&!args.find("path"))return true; if(name=="image_asset"&&field(args,"action")=="inspect")return true; if(name=="parametric_program"&&(field(args,"action")=="validate"||field(args,"action")=="examples"||field(args,"action")=="inspect"))return true; diff --git a/src/exact_jobs_046b.cpp b/src/exact_jobs_046b.cpp index e487471..80c07ba 100644 --- a/src/exact_jobs_046b.cpp +++ b/src/exact_jobs_046b.cpp @@ -1,4 +1,5 @@ #include "ark/exact_jobs_046b.hpp" +#include "ark/surface_edit_059c.hpp" #include "ark/native_backend.hpp" #include #include @@ -22,11 +23,13 @@ V withPayload(V result,const V& payload){ } std::string exactJobRejection046B(const std::string& tool,const V& args){ if(args.t!=V::Obj)return "arguments must be an object"; + if(tool=="surface_control"&&surfaceControlRetainsCandidate068B(args))return "A surface candidate must be retained by its owning session"; if(tool=="query_batch"){ const auto* rows=args.find("queries");if(!rows||rows->t!=V::Arr||rows->arr.empty())return "query_batch needs queries"; for(const auto& row:rows->arr){const auto* name=row.find("tool");const auto* values=row.find("args"); if(!name||name->t!=V::Str||!values||values->t!=V::Obj)return "query_batch row is malformed"; - if(!exactReadTools.count(name->str))return "query_batch row "+name->str+" is not on the 046B background exact-read allow-list";} + if(!exactReadTools.count(name->str))return "query_batch row "+name->str+" is not on the 046B background exact-read allow-list"; + if(!exactJobRejection046B(name->str,*values).empty())return "query_batch cannot retain private candidates";} return {}; } if(!exactReadTools.count(tool))return tool+" is not on the 046B background exact-read allow-list"; diff --git a/src/iteration_history.cpp b/src/iteration_history.cpp index 1a3b0a7..9e7f237 100644 --- a/src/iteration_history.cpp +++ b/src/iteration_history.cpp @@ -229,7 +229,7 @@ V iterationCompact(const Document& source,size_t keepRecent,const V& receipt,con record.set("archived_branch_heads",V::makeNum(omittedHeads));record.set("policy",V::makeStr("head_ancestor_suffix_contiguous_undo_clear_redo")); V signedRecord=record;canonical(signedRecord);record.set("sha256",V::makeStr(iterationSha256(signedRecord.dump())));out.set("compaction",record);out.set("compacted",V::makeBool(true));return out; } -bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>56))throw std::runtime_error("Iteration history requires a supported document version 27 or later");if(h->find("compaction")&&root.find("version")->num<50)throw std::runtime_error("Compacted history requires document version 50");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} +bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>57))throw std::runtime_error("Iteration history requires a supported document version 27 or later");if(h->find("compaction")&&root.find("version")->num<50)throw std::runtime_error("Compacted history requires document version 50");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} bool iterationValidate(const Document& document,const V& h,std::string& error){ try{if(h.t!=V::Obj||need(h,"schema").t!=V::Num||(need(h,"schema").num!=1&&need(h,"schema").num!=2))throw std::runtime_error("Unsupported iteration history schema");const V& blobs=need(h,"blobs"),nodes=need(h,"nodes");if(blobs.t!=V::Obj||nodes.t!=V::Arr||nodes.arr.size()>maxNodes)throw std::runtime_error("Invalid history blob/node storage"); const bool derivedOnly=need(h,"schema").num==2;if(derivedOnly)validateMigrations(h);else if(h.find("migrations"))throw std::runtime_error("History migration records require schema 2"); diff --git a/src/model.cpp b/src/model.cpp index 43c8d6d..8613c01 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -24,6 +24,7 @@ bool featureConsumesInputBodies(const Feature& feature){return feature.type!=Fea bool featureConsumesInputBody(const Feature& feature,size_t index){ if(!featureConsumesInputBodies(feature))return false; if(index==2&&feature.type==FeatureType::NativeSolid&&featureOperation(feature)=="curve_pattern")return false; + if(feature.type==FeatureType::SurfaceEdit){const auto* operation=feature.nativeSpec.find("op");if(operation&&(operation->asStr()=="curve_network"||(operation->asStr()=="multi_trim"&&index+1==feature.inputs.size())||(operation->asStr()=="match_boundary"&&index==1)))return false;} if(index==1&&feature.type==FeatureType::SurfaceEdit){const auto* op=feature.nativeSpec.find("op");if(op&&(op->asStr()=="trim_tool"||(op->asStr()=="deform_poles"&&feature.nativeSpec.find("glue"))))return false;} // A support supplies a boundary derivative; it is not joined into the patch. if(feature.type==FeatureType::SurfaceFill&&indexarr)if(const auto* support=c.find("support");support&&support->t==arkjson::Value::Num&&support->num==(double)feature.inputs[index])return false; diff --git a/src/native_features.cpp b/src/native_features.cpp index 53a675a..fce24a1 100644 --- a/src/native_features.cpp +++ b/src/native_features.cpp @@ -538,14 +538,25 @@ V surfaceRequest(const Feature& feature, const ExprEnv& env, Document& document, } } else if (feature.type == FeatureType::SurfaceEdit) { const std::string editOp=required(feature.nativeSpec,"op").asStr(); - const bool paired=editOp=="trim_wire"||editOp=="mutual_trim"||editOp=="trim_tool"||editOp=="ruled"||(editOp=="deform_poles"&&feature.nativeSpec.find("glue")); - if(feature.inputs.size()!=(paired?2u:1u)||(paired&&feature.inputs[0]==feature.inputs[1]))throw std::runtime_error("surface_edit needs one source; trim_wire, mutual_trim, trim_tool and ruled require two distinct inputs"); + const bool paired=editOp=="match_boundary"||editOp=="trim_wire"||editOp=="mutual_trim"||editOp=="trim_tool"||editOp=="ruled"||(editOp=="deform_poles"&&feature.nativeSpec.find("glue")); + const bool many=editOp=="curve_network"||editOp=="multi_trim"; + if(many){const size_t low=editOp=="curve_network"?4:2,high=editOp=="curve_network"?18:17;if(feature.inputs.size()high||std::set(feature.inputs.begin(),feature.inputs.end()).size()!=feature.inputs.size())throw std::runtime_error("Surface network/trim requires distinct bounded native inputs");} + else if(feature.inputs.size()!=(paired?2u:1u)||(paired&&feature.inputs[0]==feature.inputs[1]))throw std::runtime_error("Surface operation input count or identity is invalid"); const Body* source=precedingBody(preceding,feature.inputs.front()); if(!source)throw std::runtime_error("surface_edit input missing"); request.set("input_brep",brepOf(*source,"surface_edit input")); const auto& operation=required(feature.nativeSpec,"op"); if(operation.t!=V::Str)throw std::runtime_error("surface_edit op must be extract_face or trim_plane"); - if(operation.str=="mirror"){ + if(operation.str=="curve_network"){ + for(const auto& field:feature.nativeSpec.obj)if(field.first!="op"&&field.first!="u_count"&&field.first!="u_stations"&&field.first!="v_stations"&&field.first!="u_reverse"&&field.first!="v_reverse")throw std::runtime_error("Unknown curve network field: "+field.first); + request.obj.erase(std::remove_if(request.obj.begin(),request.obj.end(),[](const auto& item){return item.first=="input_brep";}),request.obj.end());V encoded=V::makeArr();for(u64 input:feature.inputs){const auto* body=precedingBody(preceding,input);if(!body)throw std::runtime_error("Network curve dependency is missing");encoded.arr.push_back(brepOf(*body,"network curve"));}request.set("op",V::makeStr("surface_network"));request.set("input_breps",encoded);for(const char* key:{"u_count","u_stations","v_stations","u_reverse","v_reverse"})if(const auto* field=feature.nativeSpec.find(key))request.set(key,numericNative(*field,env)); + }else if(operation.str=="multi_trim"){ + for(const auto& field:feature.nativeSpec.obj)if(field.first!="op"&&field.first!="source_faces"&&field.first!="keep_points")throw std::runtime_error("Unknown multi-trim field: "+field.first); + request.obj.erase(std::remove_if(request.obj.begin(),request.obj.end(),[](const auto& item){return item.first=="input_brep";}),request.obj.end());V breps=V::makeArr(),topologies=V::makeArr();for(size_t i=0;i+1nativeData,"topology"));}const auto* tool=precedingBody(preceding,feature.inputs.back());if(!tool)throw std::runtime_error("Trim tool is missing");request.set("op",V::makeStr("surface_multi_trim"));request.set("source_breps",breps);request.set("source_topologies",topologies);request.set("tool_brep",brepOf(*tool,"trim tool"));request.set("source_faces",required(feature.nativeSpec,"source_faces"));request.set("keep_points",numericNative(required(feature.nativeSpec,"keep_points"),env)); + }else if(operation.str=="match_boundary"){ + for(const auto& field:feature.nativeSpec.obj)if(field.first!="op"&&field.first!="reference"&&field.first!="target_reference"&&field.first!="source_brep_sha256"&&field.first!="target_brep_sha256"&&field.first!="source_side"&&field.first!="target_side"&&field.first!="reverse"&&field.first!="continuity"&&field.first!="cross_scale"&&field.first!="max_displacement_mm"&&field.first!="samples")throw std::runtime_error("Unknown surface match field: "+field.first); + const auto* target=precedingBody(preceding,feature.inputs[1]);if(!target)throw std::runtime_error("Surface match target is missing");request.set("op",V::makeStr("surface_match_068b"));request.set("topology",required(source->nativeData,"topology"));request.set("target_brep",brepOf(*target,"match target"));request.set("target_topology",required(target->nativeData,"topology"));for(const char* key:{"reference","target_reference","source_brep_sha256","target_brep_sha256","source_side","target_side"})if(const auto* field=feature.nativeSpec.find(key))request.set(key,*field);for(const char* key:{"reverse","continuity","cross_scale","max_displacement_mm","samples"})if(const auto* field=feature.nativeSpec.find(key))request.set(key,numericNative(*field,env)); + }else if(operation.str=="mirror"){ for(const auto& field:feature.nativeSpec.obj)if(field.first!="op"&&field.first!="plane"&&field.first!="origin"&&field.first!="normal"&&field.first!="continuity"&&field.first!="tolerance")throw std::runtime_error("Unknown surface mirror field: "+field.first); request.set("op",V::makeStr("surface_mirror"));request.set("continuity",required(feature.nativeSpec,"continuity")); if(const auto* plane=feature.nativeSpec.find("plane")){ @@ -600,9 +611,9 @@ V surfaceRequest(const Feature& feature, const ExprEnv& env, Document& document, } }else if(operation.str=="trim_wire"){ const Body* curve=precedingBody(preceding,feature.inputs[1]);if(!curve)throw std::runtime_error("Surface trim curve input missing");request.set("op",V::makeStr("surface_trim_wire"));request.set("wire_brep",brepOf(*curve,"trim curve"));request.set("keep_point",numericNative(required(feature.nativeSpec,"keep_point"),env)); - }else if(operation.str=="untrim"||operation.str=="extend"){ + }else if(operation.str=="untrim"||operation.str=="extend"||operation.str=="extend_trimmed"){ for(const auto& field:feature.nativeSpec.obj)if(field.first!="op"&&field.first!="bounds"&&field.first!="extension")throw std::runtime_error("Unknown surface domain edit field: "+field.first); - request.set("op",V::makeStr(operation.str=="extend"?"surface_extend":"surface_untrim")); + request.set("op",V::makeStr(operation.str=="extend_trimmed"?"surface_extend_trimmed":operation.str=="extend"?"surface_extend":"surface_untrim")); if(const auto* bounds=feature.nativeSpec.find("bounds"))request.set("bounds",numericNative(*bounds,env)); if(const auto* extension=feature.nativeSpec.find("extension"))request.set("extension",numericNative(*extension,env)); }else if(operation.str=="mutual_trim"){ @@ -1251,6 +1262,11 @@ V rectTubeSolid(const Feature& feature, const ExprEnv& env) { } } // namespace +arkjson::Value surfaceRequestForInspection068B(Document& document,const Feature& feature){ + if(feature.type!=FeatureType::Loft)throw std::runtime_error("Surface inspection request supports Loft only"); + return surfaceRequest(feature,document.buildEnv(),document,document.evalBodies); +} + bool isNativeFeature(FeatureType type) { return isNativeSurfaceFeature(type) || isCurveFeature(type) || type == FeatureType::SheetMetal || type == FeatureType::SourceSheet || type == FeatureType::NativeSolid || diff --git a/src/occt/common.cpp b/src/occt/common.cpp index 685e93f..6591b65 100644 --- a/src/occt/common.cpp +++ b/src/occt/common.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include diff --git a/src/occt/restore_result_031b.inl b/src/occt/restore_result_031b.inl index 71e9a79..f6bc3f9 100644 --- a/src/occt/restore_result_031b.inl +++ b/src/occt/restore_result_031b.inl @@ -120,6 +120,7 @@ V restore(const V& resolved,const V& saved){ const bool multiple=op=="linear_pattern"||op=="circular_pattern"||op=="curve_pattern"||op=="hole_pattern"||op=="split_plane"||op=="split_surface"||op=="split_tool";if(solid&&(count.num<1||count.num>(op=="curve_pattern"?2048:64)||(!multiple&&count.num!=1)))reject("solid count violates operation contract"); if(count.num>1)for(const auto& piece:shapes(shape,TopAbs_SOLID))if(!(properties(piece)>0))reject("saved compound contains a non-positive solid");if(shapes(shape,TopAbs_FACE).empty())reject("wire results require normal derivation replay"); V diagnostics=V::makeObj();if(const auto* prior=savedReport.find("saved_previous_evaluation")){objectUnique(*prior);if(require(*prior,"provenance",V::Str).str!="saved_previous_evaluation"||require(*prior,"derivation_replayed",V::Bool).b)reject("invalid previous-evaluation provenance");diagnostics=require(*prior,"diagnostics",V::Obj);} + if(op=="offset_surface"||op=="thicken"){BRepAlgoAPI_Check offsetCheck(shape,false,true);if(!offsetCheck.IsValid())reject("saved offset/thickness failed current native self-interference check");report.set(op=="offset_surface"?"offset_intersection_checked":"self_interference_checked",V::makeBool(true));} for(const auto& field:savedReport.obj)if(!genericReportField(field.first))diagnostics.set(field.first,field.second); V provenance=V::makeObj();provenance.set("provenance",V::makeStr("saved_previous_evaluation"));provenance.set("derivation_replayed",V::makeBool(false));provenance.set("diagnostics",std::move(diagnostics));report.set("saved_previous_evaluation",std::move(provenance));report.set("derivation_replayed",V::makeBool(false));report.set("snapshot_validation",V::makeStr("current_exact_brep_measurements_and_references")); V validatedTopology=topology(savedTopology,shape,identity),result=V::makeObj();result.set("brep_base64",V::makeStr(encoded));result.set("report",std::move(report));result.set("mesh",displayMeshData(shape));result.set("topology",validatedTopology); diff --git a/src/occt/surface_match_068b.inl b/src/occt/surface_match_068b.inl new file mode 100644 index 0000000..3840bb9 --- /dev/null +++ b/src/occt/surface_match_068b.inl @@ -0,0 +1,54 @@ +// 068B / B.03: native face diagnostics and explicitly bounded spline matching. +// Included after surface_deform_059c.inl in surfacing.cpp's private namespace. +void qualityNeed068(bool ok,const std::string& message){if(!ok)throw std::runtime_error("SURFACE_QUALITY: "+message);} +struct QualityFace068 {TopoDS_Face face;Handle(Geom_Surface) surface;double u0,u1,v0,v1;std::string hash,reference;}; +QualityFace068 qualityFace068(const V& request,bool target=false){ + const char* encodedKey=target?"target_brep":"input_brep";const char* topologyKey=target?"target_topology":"topology";const char* referenceKey=target?"target_reference":"reference"; + const auto& encoded=required(request,encodedKey);const auto& topology=required(request,topologyKey);QualityFace068 out;out.hash=sha256(base64Decode(encoded.str));qualityNeed068(required(topology,"brep_sha256").asStr()==out.hash,"Exact topology fingerprint differs from source"); + V selector=V::makeObj();selector.set("input_brep",encoded);selector.set("topology",topology); + const auto faces=shapes(readBrep(encoded.str),TopAbs_FACE);qualityNeed068(!faces.empty(),"Source has no exact faces"); + if(const auto* reference=request.find(referenceKey))selector.set("reference",*reference); + else {qualityNeed068(faces.size()==1,"Select one semantic face of this multi-face source");for(const auto& row:required(topology,"references").arr)if(row.find("kind")&&row.find("kind")->asStr()=="face"&&row.find("status")&&row.find("status")->asStr()=="bound"&&row.find("indices")&&row.find("indices")->arr.size()==1){selector.set("reference",required(row,"name"));break;}} + qualityNeed068(selector.find("reference")!=nullptr,"No unique bound face reference");out.reference=required(selector,"reference").asStr();const auto index=semanticFaceIndexNative(selector);qualityNeed068(index>=0&&(size_t)indexCopy());if(!location.IsIdentity())out.surface->Transform(location.Transformation());BRepTools::UVBounds(out.face,out.u0,out.u1,out.v0,out.v1); + qualityNeed068(std::isfinite(out.u0)&&std::isfinite(out.u1)&&std::isfinite(out.v0)&&std::isfinite(out.v1)&&out.u1>out.u0&&out.v1>out.v0,"Face has no finite parameter rectangle");return out; +} +bool qualityRectangle068(const QualityFace068& source){ + if(shapes(source.face,TopAbs_WIRE).size()!=1||shapes(source.face,TopAbs_EDGE).size()!=4)return false; + auto same=[](double a,double b){return std::abs(a-b)<=1e-10*std::max({1.,std::abs(a),std::abs(b)});};std::set sides; + for(const auto& entity:shapes(source.face,TopAbs_EDGE)){const auto edge=TopoDS::Edge(entity);if(BRep_Tool::Degenerated(edge))return false;double first,last;auto curve=BRep_Tool::CurveOnSurface(edge,source.face,first,last);if(curve.IsNull())return false;if(auto trimmed=Handle(Geom2d_TrimmedCurve)::DownCast(curve);!trimmed.IsNull())curve=trimmed->BasisCurve();if(Handle(Geom2d_Line)::DownCast(curve).IsNull())return false;const auto p=curve->Value(first),q=curve->Value(last);int side=-1; + if(same(p.X(),q.X())&&same(std::min(p.Y(),q.Y()),source.v0)&&same(std::max(p.Y(),q.Y()),source.v1))side=same(p.X(),source.u0)?0:same(p.X(),source.u1)?1:-1; + if(same(p.Y(),q.Y())&&same(std::min(p.X(),q.X()),source.u0)&&same(std::max(p.X(),q.X()),source.u1))side=same(p.Y(),source.v0)?2:same(p.Y(),source.v1)?3:-1; + if(side<0||!sides.insert(side).second)return false; + }return true; +} +SurfaceJet031B qualityJet068(const Handle(Geom_Surface)& surface,double u,double v){SurfaceJet031B jet;surface->D2(u,v,jet.point,jet.du,jet.dv,jet.duu,jet.dvv,jet.duv);jet.normal=jet.du.Crossed(jet.dv);qualityNeed068(jet.normal.Magnitude()>1e-12,"Singular native surface differential");jet.normal.Normalize();return jet;} +std::array qualityCurvatures068(const SurfaceJet031B& j,double orientation){const double E=j.du.SquareMagnitude(),F=j.du.Dot(j.dv),G=j.dv.SquareMagnitude(),D=E*G-F*F;qualityNeed068(D>1e-24*std::max(1.,E*G),"Singular native surface metric");const double L=j.duu.Dot(j.normal)*orientation,M=j.duv.Dot(j.normal)*orientation,N=j.dvv.Dot(j.normal)*orientation;const double H=(E*N-2*F*M+G*L)/(2*D),K=(L*N-M*M)/D;const double delta=std::sqrt(std::max(0.,H*H-K));return {H+delta,H-delta};} +int qualitySide068(const V& request,const char* key){const auto side=required(request,key).asStr();if(side=="u_min")return 0;if(side=="u_max")return 1;if(side=="v_min")return 2;if(side=="v_max")return 3;throw std::runtime_error("SURFACE_QUALITY: side must be u_min/u_max/v_min/v_max");} +std::array qualitySideUV068(double u0,double u1,double v0,double v1,int side,double t){if(side<2)return {side==0?u0:u1,v0+(v1-v0)*t};return {u0+(u1-u0)*t,side==2?v0:v1};} +V qualitySeamEvidence068(const Handle(Geom_Surface)& a,const Handle(Geom_Surface)& b,const std::array& ab,const std::array& bb,int sideA,int sideB,bool reverse,int count){ + V rows=V::makeArr();double gapMax=0,angleMax=0,tensorMax=0; + for(int i=0;i0,"No regular samples inside selected face");V out=V::makeObj();out.set("source_brep_sha256",V::makeStr(source.hash));out.set("face_reference",V::makeStr(source.reference));out.set("grid_size",V::makeNum(count));out.set("display_grid_cells_safe",V::makeBool(qualityRectangle068(source)));out.set("samples",grid);out.set("valid_samples",V::makeNum(valid));out.set("singular_samples",V::makeNum(singular));out.set("outside_trim_samples",V::makeNum(outside));out.set("min_curvature_per_mm",V::makeNum(minK));out.set("max_curvature_per_mm",V::makeNum(maxK));out.set("max_abs_curvature_per_mm",V::makeNum(maxAbs));out.set("authority",V::makeStr("native face D2 samples; raster interpolation is display only; no between-sample extrema or manufacturing qualification"));return out; +} +V surfaceSeam068B(const V& request){deformKeys059(request,{"op","input_brep","topology","reference","target_brep","target_topology","target_reference","source_side","target_side","reverse","samples","tolerance"});tolerance(request);const auto a=qualityFace068(request),b=qualityFace068(request,true);const int sideA=qualitySide068(request,"source_side"),sideB=qualitySide068(request,"target_side"),count=request.find("samples")?integer(required(request,"samples"),"samples",3,129):33;if(const auto* flag=request.find("reverse"))qualityNeed068(flag->t==V::Bool,"reverse must be a boolean");const bool reverse=request.find("reverse")&&required(request,"reverse").b;for(int i=0;iu0,pair.first->u1,pair.first->v0,pair.first->v1,pair.second.first,pair.second.second);BRepClass_FaceClassifier classifier(pair.first->face,gp_Pnt2d(uv[0],uv[1]),kTolerance);qualityNeed068(classifier.State()==TopAbs_IN||classifier.State()==TopAbs_ON,"Selected natural side crosses outside trimming; extract a supported rectangular face");}auto out=qualitySeamEvidence068(a.surface,b.surface,{a.u0,a.u1,a.v0,a.v1},{b.u0,b.u1,b.v0,b.v1},sideA,sideB,reverse,count);out.set("source_brep_sha256",V::makeStr(a.hash));out.set("target_brep_sha256",V::makeStr(b.hash));out.set("source_face",V::makeStr(a.reference));out.set("target_face",V::makeStr(b.reference));return out;} +std::pair qualityPole068(const Handle(Geom_BSplineSurface)& s,int side,int inward,int tangent){if(side<2)return {side==0?inward+1:s->NbUPoles()-inward,tangent+1};return {tangent+1,side==2?inward+1:s->NbVPoles()-inward};} +std::array,3> qualityCoefficients068(const SurfaceControls059& source,int side){ + auto copy=Handle(Geom_BSplineSurface)::DownCast(source.surface->Copy());std::array,3> result{};const int normal=side<2?copy->NbUPoles():copy->NbVPoles(),tangent=side<2?copy->NbVPoles():copy->NbUPoles();const auto uv=qualitySideUV068(source.u0,source.u1,source.v0,source.v1,side,.5);const double range=side<2?source.u1-source.u0:source.v1-source.v0,sign=side%2?-1.:1.; + for(int row=0;rowNbUPoles();++u)for(int v=1;v<=copy->NbVPoles();++v)copy->SetPole(u,v,gp_Pnt(0,0,0));for(int i=0;iSetPole(pole.first,pole.second,gp_Pnt(1,0,0));}gp_Pnt p;gp_Vec du,dv,duu,dvv,duv;copy->D2(uv[0],uv[1],p,du,dv,duu,dvv,duv);result[0][row]=p.X();result[1][row]=(side<2?du.X():dv.X())*range*sign;result[2][row]=(side<2?duu.X():dvv.X())*range*range;} + return result; +} +V surfaceMatch068B(const V& request){ + deformKeys059(request,{"op","input_brep","topology","reference","source_brep_sha256","target_brep","target_topology","target_reference","target_brep_sha256","source_side","target_side","reverse","continuity","cross_scale","max_displacement_mm","samples","tolerance"});tolerance(request);auto a=surfaceControls059(request);V target=V::makeObj();target.set("input_brep",required(request,"target_brep"));target.set("topology",required(request,"target_topology"));if(auto ref=request.find("target_reference"))target.set("reference",*ref);auto b=surfaceControls059(target);qualityNeed068(required(request,"source_brep_sha256").asStr()==a.hash&&required(request,"target_brep_sha256").asStr()==b.hash,"Source or target hash changed; inspect and prepare again"); + const int sa=qualitySide068(request,"source_side"),sb=qualitySide068(request,"target_side"),order=integer(required(request,"continuity"),"continuity",0,2),count=request.find("samples")?integer(required(request,"samples"),"samples",3,129):33;if(const auto* flag=request.find("reverse"))qualityNeed068(flag->t==V::Bool,"reverse must be a boolean");const bool reverse=request.find("reverse")&&required(request,"reverse").b;const double maximum=number(required(request,"max_displacement_mm"),"max_displacement_mm"),scale=request.find("cross_scale")?number(required(request,"cross_scale"),"cross_scale"):1.;qualityNeed068(maximum>0&&maximum<=1e5&&scale>0&&scale<=100,"Explicit displacement or cross-scale outside range"); + qualityNeed068(!a.surface->IsURational()&&!a.surface->IsVRational()&&!b.surface->IsURational()&&!b.surface->IsVRational(),"Boundary matching currently requires non-rational spline surfaces; rational source preserved");const int an=sa<2?a.surface->NbUPoles():a.surface->NbVPoles(),bn=sb<2?b.surface->NbUPoles():b.surface->NbVPoles(),at=sa<2?a.surface->NbVPoles():a.surface->NbUPoles(),bt=sb<2?b.surface->NbVPoles():b.surface->NbUPoles(),ad=sa<2?a.surface->VDegree():a.surface->UDegree(),bd=sb<2?b.surface->VDegree():b.surface->UDegree(),normalDegree=sa<2?a.surface->UDegree():a.surface->VDegree();qualityNeed068(an>=order+2&&normalDegree>=std::max(1,order),"Source needs enough pole rows and degree to match while preserving its opposite boundary");qualityNeed068(at==bt&&ad==bd,"Boundary tangent pole counts/degrees differ; explicitly rebuild compatible curves first"); + const int ak=sa<2?a.surface->NbVKnots():a.surface->NbUKnots(),bk=sb<2?b.surface->NbVKnots():b.surface->NbUKnots();qualityNeed068(ak==bk,"Boundary tangent knot counts differ");auto knot=[](const auto& s,int side,int i){return side<2?s->VKnot(i):s->UKnot(i);};auto mult=[](const auto& s,int side,int i){return side<2?s->VMultiplicity(i):s->UMultiplicity(i);};for(int i=1;i<=ak;++i){const int j=reverse?bk+1-i:i;const double x=(knot(a.surface,sa,i)-knot(a.surface,sa,1))/(knot(a.surface,sa,ak)-knot(a.surface,sa,1)),y=(knot(b.surface,sb,j)-knot(b.surface,sb,1))/(knot(b.surface,sb,bk)-knot(b.surface,sb,1));qualityNeed068(std::abs(x-(reverse?1-y:y))<=1e-12&&mult(a.surface,sa,i)==mult(b.surface,sb,j),"Boundary normalized knot vectors differ");} + const auto ac=qualityCoefficients068(a,sa),bc=qualityCoefficients068(b,sb);auto changed=Handle(Geom_BSplineSurface)::DownCast(a.surface->Copy());double movedMax=0;for(int t=0;t desired{},result{};for(int r=0;rPole(bp.first,bp.second).XYZ()*bc[d][r];}desired[1]*=-scale;desired[2]*=scale*scale;for(int r=0;r<=order;++r){qualityNeed068(std::abs(ac[r][r])>1e-12,"Source boundary basis is singular");gp_XYZ p=desired[r];for(int j=0;jPole(ap.first,ap.second).Distance(gp_Pnt(result[r]));movedMax=std::max(movedMax,displacement);qualityNeed068(displacement<=maximum,"Matching would exceed the explicit pole displacement bound");changed->SetPole(ap.first,ap.second,gp_Pnt(result[r]));}} + for(int u=0;u<=16;++u)for(int v=0;v<=16;++v)qualityJet068(changed,a.u0+(a.u1-a.u0)*u/16,a.v0+(a.v1-a.v0)*v/16); + BRepBuilderAPI_MakeFace maker(changed,a.u0,a.u1,a.v0,a.v1,kTolerance);qualityNeed068(maker.IsDone(),"Matched face construction failed");auto face=maker.Face();face.Orientation(a.face.Orientation());qualityNeed068(BRepCheck_Analyzer(face).IsValid()&&BRepAlgoAPI_Check(face).IsValid(),"Matched face failed native validity/interference checks");const auto before=qualitySeamEvidence068(a.surface,b.surface,{a.u0,a.u1,a.v0,a.v1},{b.u0,b.u1,b.v0,b.v1},sa,sb,reverse,count),after=qualitySeamEvidence068(changed,b.surface,{a.u0,a.u1,a.v0,a.v1},{b.u0,b.u1,b.v0,b.v1},sa,sb,reverse,count);const char* acceptance=order==0?"sampled_g0":order==1?"sampled_g1":"sampled_g2";qualityNeed068(required(after,acceptance).b,"Native boundary jets failed the requested sampled continuity");auto result=surfaceEditResult(face,"surface_match_boundary");auto report=required(result,"report");report.set("source_brep_sha256",V::makeStr(a.hash));report.set("target_brep_sha256",V::makeStr(b.hash));report.set("requested_continuity",V::makeNum(order));report.set("max_pole_displacement_mm",V::makeNum(movedMax));report.set("basis_preserved",V::makeBool(true));report.set("opposite_boundary_preserved",V::makeBool(true));report.set("before",before);report.set("after",after);report.set("global_continuity_verified",V::makeBool(false));report.set("manufacturing_qualified",V::makeBool(false));result.set("report",report);return result; +} diff --git a/src/occt/surface_network_068b.inl b/src/occt/surface_network_068b.inl new file mode 100644 index 0000000..f60f9b8 --- /dev/null +++ b/src/occt/surface_network_068b.inl @@ -0,0 +1,70 @@ +// Exact compatible polynomial curve networks and read-only loft correspondence. +// Included in surfacing.cpp's private namespace after surfaceEditResult. +void networkNeed068(bool ok,const std::string& reason){if(!ok)throw std::runtime_error("SURFACE_NETWORK: "+reason);} +void networkKeys068(const V& object,std::initializer_list keys){networkNeed068(object.t==V::Obj,"Expected object");for(const auto& item:object.obj)networkNeed068(std::any_of(keys.begin(),keys.end(),[&](const char* key){return item.first==key;}),"Unknown field: "+item.first);} +std::vector networkStations068(const V& request,const char* key,size_t count){ + std::vector out;const auto* authored=request.find(key); + if(authored){networkNeed068(authored->t==V::Arr&&authored->arr.size()==count,std::string(key)+" must match the transverse curve count");for(const auto& x:authored->arr)out.push_back(number(x,key));} + else for(size_t i=0;iout[i-1]+1e-5&&out[i]<=1,"Stations must be strictly increasing and separated by more than 1e-5"); + return out; +} +bool networkReverse068(const V& request,const char* key,size_t index,size_t count){const auto* a=request.find(key);if(!a)return false;networkNeed068(a->t==V::Arr&&a->arr.size()==count,std::string(key)+" must match family count");for(const auto& v:a->arr)networkNeed068(v.t==V::Bool,"Curve reversal must be boolean");return a->arr[index].b;} +Handle(Geom_BezierCurve) networkCurve068(const V& encoded,bool reverse){ + networkNeed068(encoded.t==V::Str,"Curve B-rep must be text");const auto shape=readBrep(encoded.str);const auto edges=shapes(shape,TopAbs_EDGE); + networkNeed068((shape.ShapeType()==TopAbs_WIRE||shape.ShapeType()==TopAbs_EDGE)&&shapes(shape,TopAbs_FACE).empty()&&edges.size()==1,"Each network curve must contain one exact open polynomial edge"); + const auto edge=TopoDS::Edge(edges.front());BRepAdaptor_Curve adaptor(edge);networkNeed068(!adaptor.IsClosed()&&!BRep_Tool::Degenerated(edge),"Closed or degenerate network edges are unsupported"); + Handle(Geom_BezierCurve) curve; + if(adaptor.GetType()==GeomAbs_Line){NCollection_Array1 poles(1,2);poles(1)=adaptor.Value(adaptor.FirstParameter());poles(2)=adaptor.Value(adaptor.LastParameter());curve=new Geom_BezierCurve(poles);} + else{ + double first,last;TopLoc_Location location;auto original=BRep_Tool::Curve(edge,location,first,last);networkNeed068(!original.IsNull(),"Missing native curve"); + Handle(Geom_TrimmedCurve) trimmed=new Geom_TrimmedCurve(original,first,last);auto spline=GeomConvert::CurveToBSplineCurve(trimmed); + networkNeed068(!spline.IsNull()&&!spline->IsRational()&&!spline->IsPeriodic()&&spline->NbKnots()==2,"Network currently requires non-rational single-span polynomial curves"); + networkNeed068(spline->Degree()>=1&&spline->Degree()<=8&&spline->NbPoles()==spline->Degree()+1,"Network curve degree must be 1..8 with a clamped single-span basis"); + NCollection_Array1 poles(1,spline->NbPoles());for(int i=1;i<=spline->NbPoles();++i)poles(i)=spline->Pole(i).Transformed(location.Transformation());curve=new Geom_BezierCurve(poles); + } + if((edge.Orientation()==TopAbs_REVERSED)!=reverse)curve->Reverse();return curve; +} +double choose068(int n,int k){if(k<0||k>n)return 0;double r=1;for(int i=1;i<=k;++i)r*=double(n-k+i)/i;return r;} +// Lagrange interpolation expressed exactly in the common Bernstein basis. +std::vector> networkBasis068(const std::vector& stations,int degree){ + std::vector> basis; + for(size_t j=0;j power{1};for(size_t k=0;k next(power.size()+1,0);for(size_t i=0;i b(degree+1,0);for(int i=0;i<=degree;++i)for(int k=0;k<=i&&k<(int)power.size();++k)b[i]+=power[k]*choose068(i,k)/choose068(degree,k);basis.push_back(std::move(b));} + return basis; +} +V surfaceNetwork068(const V& request){ + networkKeys068(request,{"op","input_breps","u_count","u_stations","v_stations","u_reverse","v_reverse","tolerance"});tolerance(request); + const auto& encoded=required(request,"input_breps");networkNeed068(encoded.t==V::Arr,"input_breps must be an ordered array");const int nu=integer(required(request,"u_count"),"u_count",2,9),nv=(int)encoded.arr.size()-nu;networkNeed068(nv>=2&&nv<=9,"Network requires 2..9 curves in each family"); + const auto us=networkStations068(request,"u_stations",nv),vs=networkStations068(request,"v_stations",nu); + std::vector uc,vc;int degreeU=std::max(3,nv-1),degreeV=std::max(3,nu-1); + for(int i=0;iDegree());} + for(int i=0;iDegree());} + std::vector> cross(nv,std::vector(nu));double crossingError=0; + for(int i=0;iValue(us[i]),b=vc[i]->Value(vs[j]);const auto gap=a.Distance(b);crossingError=std::max(crossingError,gap);networkNeed068(gap<=kTolerance,"Curves do not intersect at the authored normalized stations (U "+std::to_string(j)+", V "+std::to_string(i)+", gap "+std::to_string(gap)+" mm)");cross[i][j]=a;} + for(auto& c:uc)c->Increase(degreeU);for(auto& c:vc)c->Increase(degreeV); + const auto ub=networkBasis068(us,degreeU),vb=networkBasis068(vs,degreeV); + NCollection_Array2 poles(1,degreeU+1,1,degreeV+1); + for(int a=0;a<=degreeU;++a)for(int b=0;b<=degreeV;++b){gp_XYZ p(0,0,0);for(int j=0;jPole(a+1).XYZ()*vb[j][b];for(int i=0;iPole(b+1).XYZ()*ub[i][a];for(int i=0;iValue(u,vs[j]).Distance(uc[j]->Value(u)));++count;} + for(int i=0;iValue(us[i],v).Distance(vc[i]->Value(v)));++count;} + networkNeed068(error<=kTolerance,"Gordon result fails native curve preservation checkpoints"); + double minJacobian=1e300;for(int i=0;i<=16;++i)for(int j=0;j<=16;++j){gp_Pnt p;gp_Vec du,dv;surface->D1(i/16.,j/16.,p,du,dv);const double jac=du.Crossed(dv).Magnitude();networkNeed068(std::isfinite(jac)&&jac>1e-10,"Network has an observed singular or folded parameter region");minJacobian=std::min(minJacobian,jac);} + const auto editableBasis=GeomConvert::SurfaceToBSplineSurface(surface);networkNeed068(!editableBasis.IsNull(),"Exact polynomial basis conversion failed");BRepBuilderAPI_MakeFace maker(editableBasis,kTolerance);networkNeed068(maker.IsDone()&&BRepCheck_Analyzer(maker.Face()).IsValid(),"Network produced an invalid B-rep face");BRepAlgoAPI_Check interference(maker.Face());networkNeed068(interference.IsValid(),"Network failed native self-interference check"); + V out=surfaceEditResult(maker.Face(),"curve_network"),report=required(out,"report");report.set("construction",V::makeStr("exact_polynomial_Gordon_Boolean_sum"));report.set("u_curves",V::makeNum(nu));report.set("v_curves",V::makeNum(nv));report.set("u_degree",V::makeNum(degreeU));report.set("v_degree",V::makeNum(degreeV));report.set("crossing_max_gap_mm",V::makeNum(crossingError));report.set("curve_observed_max_error_mm",V::makeNum(error));report.set("curve_checkpoints",V::makeNum(count));report.set("min_sampled_jacobian",V::makeNum(minJacobian));report.set("curve_basis_identity",V::makeBool(crossingError==0));report.set("global_injectivity_verified",V::makeBool(false));report.set("authority",V::makeStr("native polynomial curves and Bernstein coefficients; no mesh fitting"));out.set("report",report);return out; +} + +std::vector loftSamples068(const Profile& section){ + std::vector lengths;double total=0;for(const auto& edge:section.edges){BRepAdaptor_Curve c(edge.edge);const double length=GCPnts_AbscissaPoint::Length(c,1e-9);networkNeed068(length>1e-9,"Degenerate loft section edge");lengths.push_back(length);total+=length;} + std::vector points;const int samples=section.closed?32:33; + for(int k=0;kaccumulated+lengths[edge])accumulated+=lengths[edge++];BRepAdaptor_Curve c(section.edges[edge].edge);const bool reversed=section.edges[edge].edge.Orientation()==TopAbs_REVERSED;const double from=reversed?c.LastParameter():c.FirstParameter(),to=reversed?c.FirstParameter():c.LastParameter();const double travel=std::clamp(distance-accumulated,0.,lengths[edge]);double parameter=from;if(travel>=lengths[edge]-1e-9)parameter=to;else if(travel>1e-9){GCPnts_AbscissaPoint solve(1e-9,c,(reversed?-1:1)*travel,from);networkNeed068(solve.IsDone(),"Loft arc-length correspondence failed");parameter=solve.Parameter();}points.push_back(c.Value(parameter));}return points; +} +V loftDiagnostics068(const V& request){ + validateLoftControls(request);const auto& profiles=required(request,"profiles");networkNeed068(profiles.t==V::Arr&&profiles.arr.size()>=2&&profiles.arr.size()<=32,"Loft needs 2..32 sections"); + V out=V::makeObj(),rows=V::makeArr(),pairs=V::makeArr();std::vector sections;std::vector indices;bool compatible=true; + for(size_t i=0;ifind("section_alignment")));rows.arr.push_back(row);sections.push_back(std::move(section));indices.push_back(i);} + for(size_t i=1;i100000)throw std::runtime_error("Offset diagnostic amount must exceed 1e-6 and not exceed 100000 mm"); + const int count=request.find("samples")?integer(*request.find("samples"),"samples",3,33):9;const auto encoded=required(request,"input_brep").asStr();const auto shape=readBrep(encoded);const auto faces=shapes(shape,TopAbs_FACE);const auto& topology=required(request,"topology");const auto hash=sha256(base64Decode(encoded));if(required(topology,"brep_sha256").asStr()!=hash)throw std::runtime_error("Offset diagnostic source topology changed"); + if(!shapes(shape,TopAbs_SOLID).empty()||faces.empty()||faces.size()>64)throw std::runtime_error("Offset diagnostic requires an open face/shell with 1..64 faces"); + V out=V::makeObj(),faceRows=V::makeArr(),hotspots=V::makeArr();size_t totalSamples=0,totalUndefined=0,totalSkipped=0;double peak=0; + for(size_t index=0;indexasStr()=="face"&&indices&&indices->arr.size()==1&&indices->arr[0].num==double(index)){reference=required(row,"name").asStr();break;}} + BRepAdaptor_Surface support(face,true);double maxCurvature=0;size_t checked=0,undefined=0,skipped=0;V peakPoint;std::vector> warnings; + for(int u=0;u=maxCurvature){maxCurvature=curvature;peakPoint=vec(point.XYZ());}const double ratio=std::abs(amount)*curvature;if(ratio>=.8){V row=V::makeObj(),uv=V::makeArr();uv.arr={V::makeNum(pu),V::makeNum(pv)};row.set("face_index",V::makeNum(double(index)));row.set("face_reference",V::makeStr(reference));row.set("point_mm",vec(point.XYZ()));row.set("uv",uv);row.set("curvature_abs_per_mm",V::makeNum(curvature));row.set("radius_mm",V::makeNum(1./curvature));row.set("magnitude_to_radius_ratio",V::makeNum(ratio));row.set("kind",V::makeStr("sampled_curvature_risk"));warnings.push_back({ratio,row});}} + catch(const Standard_Failure&){++undefined;} + } + std::stable_sort(warnings.begin(),warnings.end(),[](const auto& a,const auto& b){return a.first>b.first;});for(size_t i=0;i(16,warnings.size());++i)hotspots.arr.push_back(warnings[i].second); + V row=V::makeObj();row.set("face_index",V::makeNum(double(index)));row.set("face_reference",V::makeStr(reference));row.set("checked_samples",V::makeNum(double(checked)));row.set("undefined_samples",V::makeNum(double(undefined)));row.set("trimmed_out_samples",V::makeNum(double(skipped)));row.set("max_abs_curvature_per_mm",V::makeNum(maxCurvature));row.set("sampled_min_radius_mm",maxCurvature>1e-14?V::makeNum(1./maxCurvature):V{});row.set("peak_point_mm",peakPoint);faceRows.arr.push_back(row);totalSamples+=checked;totalUndefined+=undefined;totalSkipped+=skipped;peak=std::max(peak,maxCurvature); + } + out.set("mode",V::makeStr(mode));out.set("amount_mm",V::makeNum(amount));out.set("source_brep_sha256",V::makeStr(hash));out.set("faces",faceRows);out.set("hotspots",hotspots);out.set("checked_samples",V::makeNum(double(totalSamples)));out.set("undefined_samples",V::makeNum(double(totalUndefined)));out.set("trimmed_out_samples",V::makeNum(double(totalSkipped)));out.set("sampled_min_radius_mm",peak>1e-14?V::makeNum(1./peak):V{});out.set("candidate_valid",V::makeBool(false));out.set("candidate_self_interference_checked",V::makeBool(false));out.set("faults",V::makeArr()); + try{ + V model=V::makeObj();model.set("input_brep",V::makeStr(encoded));model.set(mode=="offset"?"distance":"thickness",V::makeNum(amount));model.set("tolerance",V::makeNum(kTolerance)); + // Use the same native construction as the producer, keeping rejected + // candidate shapes private long enough to report actual fault bounds. + auto candidate=rawSurfaceOffset068(shape,amount,mode=="thicken");if(mode=="thicken"){if(shapes(candidate,TopAbs_SOLID).size()!=1)throw std::runtime_error("Thickness did not produce one solid");if(properties(candidate)<0)candidate.Reverse();}BRepAlgoAPI_Check check(candidate,false,true);out.set("candidate_self_interference_checked",V::makeBool(true));V faults=V::makeArr(); + for(NCollection_List::Iterator it(check.Result());it.More();it.Next()){const auto& defect=it.Value();for(const auto* entries:{&defect.GetFaultyShapes1(),&defect.GetFaultyShapes2()})for(NCollection_List::Iterator f(*entries);f.More();f.Next()){if(faults.arr.size()>=128)break;const auto box=bounds(f.Value());V item=V::makeObj(),extent=V::makeArr();for(double value:box)extent.arr.push_back(V::makeNum(value));item.set("native_status",V::makeNum(int(defect.GetCheckStatus())));item.set("candidate_bounds_mm",extent);item.set("kind",V::makeStr("native_candidate_fault"));faults.arr.push_back(item);}} + out.set("faults",faults);if(!check.IsValid())throw std::runtime_error("Native candidate contains self-interference or invalid topology; see candidate fault bounds");const V produced=shapeResult(candidate,mode=="thicken");out.set("candidate_valid",V::makeBool(true));out.set("candidate_report",required(produced,"report")); + }catch(const Standard_Failure& e){out.set("candidate_error",V::makeStr(std::string("OCCT: ")+e.GetMessageString()));}catch(const std::exception& e){out.set("candidate_error",V::makeStr(e.what()));} + out.set("scope",V::makeStr("Read-only exact native trial and trimmed-face curvature samples. Hotspots compare offset magnitude with sampled radii, independent of sign: they are risk locations, not a certified cause or a continuous bound. Native fault bounds identify actual candidate check failures when available. No automatic thickness change, tolerance inflation or source edit."));return out; +} diff --git a/src/occt/surface_operations_068b.inl b/src/occt/surface_operations_068b.inl new file mode 100644 index 0000000..ecf22ee --- /dev/null +++ b/src/occt/surface_operations_068b.inl @@ -0,0 +1,37 @@ +// 068B: explicit face sets, hole-preserving extension and sewing diagnostics. +// Include after the existing surfacing helpers, inside their private namespace. +TopoDS_Face operationFace068(const V& encoded,const V& topology,const std::string& reference){ + const auto shape=readBrep(encoded.asStr());const auto fs=shapes(shape,TopAbs_FACE);if(reference.empty()){if(!shapes(shape,TopAbs_SOLID).empty()||fs.size()!=1)throw std::runtime_error("Choose a semantic face for multi-face/solid source");return TopoDS::Face(fs.front());} + if(required(topology,"brep_sha256").asStr()!=sha256(base64Decode(encoded.asStr())))throw std::runtime_error("Source face topology digest is stale"); + int index=-1,matches=0;for(const auto& r:required(topology,"references").arr){if(required(r,"kind").asStr()!="face"||required(r,"name").asStr()!=reference)continue;const auto* status=r.find("status"),*indices=r.find("indices");if(!status||(status->asStr()!="bound"&&status->asStr()!="merged")||!indices||indices->arr.size()!=1)continue;const double n=indices->arr.front().num;if(n<0||n>=fs.size()||n!=std::floor(n))continue;index=(int)n;++matches;}if(matches!=1)throw std::runtime_error("Face reference is missing, stale or ambiguous");return TopoDS::Face(fs[index]); +} +V surfaceMultiTrim068B(const V& request){ + sfKeys059(request,{"op","source_breps","source_topologies","source_faces","tool_brep","keep_points","tolerance"});tolerance(request); + const auto& sources=required(request,"source_breps"),&topologies=required(request,"source_topologies"),&references=required(request,"source_faces"),&points=required(request,"keep_points"); + if(sources.t!=V::Arr||sources.arr.empty()||sources.arr.size()>16||topologies.arr.size()!=sources.arr.size()||references.arr.size()!=sources.arr.size()||points.arr.size()!=sources.arr.size())throw std::runtime_error("Multi-trim needs 1..16 explicit source faces and one keep point per face"); + const auto tool=sfDecode059(request,"tool_brep");sfNativeCheck059(tool,"Multi-trim cutter");TopoDS_Compound result;BRep_Builder builder;builder.MakeCompound(result);V evidence=V::makeArr();std::set seen;size_t cut=0; + for(size_t i=0;i args,tools;args.Append(face);tools.Append(tool);BRepAlgoAPI_Splitter split;split.SetArguments(args);split.SetTools(tools);split.SetNonDestructive(true);split.Build();if(!split.IsDone()||split.HasErrors())throw std::runtime_error("Multi-trim splitter failed at source "+std::to_string(i));const auto pieces=shapes(split.Shape(),TopAbs_FACE);if(pieces.empty()||pieces.size()>64)throw std::runtime_error("Multi-trim requires 1..64 accounted regions per source"); + double area=0;TopoDS_Face selected;size_t matches=0,chosen=0;V regions=V::makeArr();for(size_t j=0;jstd::max(1e-6,before*1e-8))throw std::runtime_error("Multi-trim area conservation failed");sfNativeCheck059(selected,"Multi-trim retained face");builder.Add(result,selected);if(pieces.size()>1)++cut;V row=V::makeObj();row.set("source",V::makeNum(i));row.set("face",references.arr[i]);row.set("source_area_mm2",V::makeNum(before));row.set("retained_area_mm2",V::makeNum(properties(selected,'a')));row.set("removed_area_mm2",V::makeNum(before-properties(selected,'a')));row.set("regions",regions);row.set("selected_region",V::makeNum(chosen));row.set("unchanged",V::makeBool(pieces.size()==1));evidence.arr.push_back(row); + } + if(!cut)throw std::runtime_error("The cutter did not split any selected source face");auto output=shapeResult(result,false),report=required(output,"report");report.set("operation",V::makeStr("surface_multi_trim"));report.set("per_source",evidence);report.set("retained_faces",V::makeNum(sources.arr.size()));report.set("area_conservation_checked",V::makeBool(true));report.set("sewn",V::makeBool(false));report.set("selection_authority",V::makeStr("Exact source face references and explicit local keep points; every removed region accounted"));output.set("report",report);return output; +} +V surfaceDomainInspect068B(const V& request){sfKeys059(request,{"op","input_brep","tolerance"});tolerance(request);const auto face=singleSurface031B(required(request,"input_brep"),"Surface domain inspection");const auto uv=faceBounds031B(face);V out=V::makeObj();out.set("uv_bounds",boundsValue031B(uv));Handle(Geom_Surface) support=BRep_Tool::Surface(face);while(!Handle(Geom_RectangularTrimmedSurface)::DownCast(support).IsNull())support=Handle(Geom_RectangularTrimmedSurface)::DownCast(support)->BasisSurface();const bool bounded=!Handle(Geom_BoundedSurface)::DownCast(support).IsNull();out.set("bounded_support",V::makeBool(bounded));out.set("recommended_extension",V::makeStr(bounded?"length":"uv_bounds"));out.set("support_type",V::makeStr(support->DynamicType()->Name()));out.set("holes",V::makeNum(shapes(face,TopAbs_WIRE).size()-1));out.set("area_mm2",V::makeNum(properties(face,'a')));out.set("uv_units",V::makeStr("Native support parameters, not generally millimetres"));out.set("source_brep_sha256",V::makeStr(sha256(base64Decode(required(request,"input_brep").asStr()))));return out;} +V surfaceExtendTrimmed068B(const V& request){ + sfKeys059(request,{"op","input_brep","bounds","extension","tolerance"});tolerance(request);const auto face=singleSurface031B(required(request,"input_brep"),"Trim-preserving extension");const auto bounds=faceBounds031B(face);const auto outer=BRepTools::OuterWire(face);if(outer.IsNull())throw std::runtime_error("Extension needs a rectangular outer boundary"); + // Existing bounds define a rectangle only if every native outer edge stays on + // one of its four parameter lines; arbitrary outer trims are not restored. + for(BRepTools_WireExplorer it(outer,face);it.More();it.Next()){double first,last;const auto curve=BRep_Tool::CurveOnSurface(it.Current(),face,first,last);if(curve.IsNull())throw std::runtime_error("Outer trim lacks exact pcurve");Handle(Geom2d_Curve) basis=curve;while(!Handle(Geom2d_TrimmedCurve)::DownCast(basis).IsNull())basis=Handle(Geom2d_TrimmedCurve)::DownCast(basis)->BasisCurve();if(Handle(Geom2d_Line)::DownCast(basis).IsNull())throw std::runtime_error("Outer boundary must use exact straight UV segments");bool side[4]={true,true,true,true};for(int j=0;j<=16;++j){const auto p=curve->Value(first+(last-first)*j/16.);side[0]&=std::abs(p.X()-bounds[0])<=1e-8;side[1]&=std::abs(p.X()-bounds[1])<=1e-8;side[2]&=std::abs(p.Y()-bounds[2])<=1e-8;side[3]&=std::abs(p.Y()-bounds[3])<=1e-8;}if(!side[0]&&!side[1]&&!side[2]&&!side[3])throw std::runtime_error("Preserving an arbitrary outer trim while extending is unsupported; select a rectangular support boundary");} + V base=request;base.set("op",V::makeStr("surface_extend"));const auto extended=untrimExtendSurface031B(base,true);const auto extendedFace=singleSurface031B(required(extended,"brep_base64"),"Extended result");BRepBuilderAPI_MakeFace maker(extendedFace);BRep_Builder builder;size_t holes=0;double holeError=0; + for(const auto& shape:shapes(face,TopAbs_WIRE)){if(shape.IsSame(outer))continue;const auto wire=TopoDS::Wire(shape);BRepBuilderAPI_Copy copy(wire);const auto copied=TopoDS::Wire(copy.Shape());for(BRepTools_WireExplorer it(wire,face);it.More();it.Next()){const auto original=it.Current();const auto changed=TopoDS::Edge(copy.ModifiedShape(original));double first,last;const auto pc=BRep_Tool::CurveOnSurface(original,face,first,last);if(pc.IsNull())throw std::runtime_error("Hole lacks an exact pcurve");builder.UpdateEdge(changed,Handle(Geom2d_Curve)::DownCast(pc->Copy()),extendedFace,kTolerance);for(int j=0;j<=16;++j){const auto uv=pc->Value(first+(last-first)*j/16.);holeError=std::max(holeError,BRep_Tool::Surface(face)->Value(uv.X(),uv.Y()).Distance(BRep_Tool::Surface(extendedFace)->Value(uv.X(),uv.Y())));}}maker.Add(copied);++holes;} + if((holes&&!maker.IsDone())||holeError>kTolerance)throw std::runtime_error("Hole-preserving extension failed native support checks");const TopoDS_Face result=holes?maker.Face():extendedFace;sfNativeCheck059(result,"Hole-preserving extension");const auto wires=shapes(result,TopAbs_WIRE);if(wires.size()!=holes+1)throw std::runtime_error("Extension changed the number of trimming holes");const double before=properties(face,'a'),after=properties(result,'a');if(after<=before+1e-8)throw std::runtime_error("Extension must add positive measured area");auto output=surfaceEditResult(result,"surface_extend_trimmed"),report=required(output,"report");report.set("holes_preserved",V::makeNum(holes));report.set("holes_removed",V::makeBool(false));report.set("original_area_mm2",V::makeNum(before));report.set("added_area_mm2",V::makeNum(after-before));report.set("hole_support_max_error_mm",V::makeNum(holeError));report.set("support_extension",required(extended,"report"));report.set("scope",V::makeStr("Rectangular outer UV support extension with original inner wires retained; native validity and sampled support preservation, not arbitrary outer-boundary extension"));output.set("report",report);return output; +} +V surfaceSewInspect068B(const V& request){ + sfKeys059(request,{"op","inputs","topologies","tolerance"});tolerance(request);V attempt=request;attempt.set("op",V::makeStr("sew"));attempt.set("solid",V::makeBool(false));attempt.set("require_connected",V::makeBool(false));const auto evaluated=sewSurfaces(attempt);V out=required(evaluated,"report");const auto& inputs=required(request,"inputs");const auto* topologies=request.find("topologies");if(topologies&&topologies->arr.size()!=inputs.arr.size())throw std::runtime_error("Sew topology count differs from source count"); + BRepBuilderAPI_Sewing sewing(kTolerance);sewing.SetMaxTolerance(kTolerance);sewing.SetLocalTolerancesMode(false);std::vector sources;for(const auto& encoded:inputs.arr){sources.push_back(readBrep(encoded.asStr()));sewing.Add(sources.back());}sewing.Perform();V boundaries=V::makeArr(),pairs=V::makeArr();std::vector free; + if(sewing.NbFreeEdges()>256)throw std::runtime_error("Boundary diagnostics supports at most 256 free edges");for(int i=1;i<=sewing.NbFreeEdges();++i){const auto edge=sewing.FreeEdge(i);free.push_back(edge);BRepAdaptor_Curve curve(edge);V row=V::makeObj(),matches=V::makeArr();row.set("boundary",V::makeNum(i-1));row.set("length_mm",V::makeNum(GCPnts_AbscissaPoint::Length(curve,1e-8)));row.set("start_mm",vec(curve.Value(curve.FirstParameter()).XYZ()));row.set("end_mm",vec(curve.Value(curve.LastParameter()).XYZ())); + for(size_t j=0;jarr[j],"references").arr){const auto* indices=ref.find("indices");if(required(ref,"kind").asStr()=="edge"&&indices&&indices->arr.size()==1&&indices->arr[0].num==double(k)){match.set("reference",required(ref,"name"));break;}}matches.arr.push_back(match);}}row.set("source_matches",matches);boundaries.arr.push_back(row);} + for(size_t i=0;ikTolerance&&distance.Value() #include #include +#include +#include +#include +#include #include #include #include @@ -103,6 +107,8 @@ namespace ark::occt { namespace { using V = arkjson::Value; constexpr double kTolerance = 1.0e-6; +TopoDS_Shape rawSurfaceOffset068(const TopoDS_Shape&,double,bool); +void validateSurfaceOffset068(const TopoDS_Shape&); const V& required(const V& object, const char* key) { if (object.t != V::Obj) throw std::runtime_error("Expected object"); @@ -1571,11 +1577,10 @@ V offsetSurface(const V& request) { if (!shapes(source, TopAbs_SOLID).empty()) throw std::runtime_error("offset_surface requires a face or shell, not a solid"); if (shapes(source, TopAbs_FACE).empty()) throw std::runtime_error("offset_surface input has no faces"); - BRepOffsetAPI_MakeOffsetShape maker; - maker.PerformBySimple(source, distance); - if (!maker.IsDone()) throw std::runtime_error("OCCT surface offset failed"); - return tag(shapeResult(maker.Shape(), false), "offset_surface", - "offset_intersection_checked", V::makeBool(false)); + const auto offset=rawSurfaceOffset068(source,distance,false); + validateSurfaceOffset068(offset); + return tag(shapeResult(offset, false), "offset_surface", + "offset_intersection_checked", V::makeBool(true)); } V sewSurfaces(const V& request) { @@ -1719,10 +1724,7 @@ V thicken(const V& request) { open = faces(i).Extent() == 1 && !BRep_Tool::Degenerated(TopoDS::Edge(faces.FindKey(i))); if (!open) throw std::runtime_error("thicken requires an open face or shell, but this shell is closed (no free boundary edges); thicken an open skin (an open profile with solid:0), or build the solid with solid:1 and hollow it with native_solid shell"); } - BRepOffsetAPI_MakeThickSolid maker; - maker.MakeThickSolidBySimple(source, thickness); - if (!maker.IsDone()) throw std::runtime_error("OCCT thickening failed"); - TopoDS_Shape solid = maker.Shape(); + TopoDS_Shape solid=rawSurfaceOffset068(source,thickness,true); if (shapes(solid, TopAbs_SOLID).size() != 1) throw std::runtime_error("OCCT thickening did not return one solid: type=" + std::to_string(solid.ShapeType()) + @@ -1732,8 +1734,13 @@ V thicken(const V& request) { // Reversal negates the same integral, so the measured volume is reused. const double signedVolume = properties(solid); if (signedVolume < 0) solid.Reverse(); - return solidShapeResult(solid, std::abs(signedVolume)); + validateSurfaceOffset068(solid); + V result=solidShapeResult(solid,std::abs(signedVolume)),report=*result.find("report");report.set("self_interference_checked",V::makeBool(true));result.set("report",report);return result; } +#include "surface_match_068b.inl" +#include "surface_network_068b.inl" +#include "surface_operations_068b.inl" +#include "surface_offset_068b.inl" } // namespace V profileCurveNative(const V& profile){ @@ -1747,6 +1754,16 @@ V modelSurfaceNative(const V& request) { if (operation.str == "loft") return loft(request); if (operation.str == "surface_fill") return surfaceFill(request); if (operation.str == "surface_nurbs") return surfaceNurbs(request); + if (operation.str == "surface_quality_068b") return surfaceQuality068B(request); + if (operation.str == "surface_seam_068b") return surfaceSeam068B(request); + if (operation.str == "surface_match_068b") return surfaceMatch068B(request); + if (operation.str == "surface_network") return surfaceNetwork068(request); + if (operation.str == "loft_diagnostics") return loftDiagnostics068(request); + if (operation.str == "surface_domain_inspect") return surfaceDomainInspect068B(request); + if (operation.str == "surface_multi_trim") return surfaceMultiTrim068B(request); + if (operation.str == "surface_extend_trimmed") return surfaceExtendTrimmed068B(request); + if (operation.str == "surface_sew_inspect") return surfaceSewInspect068B(request); + if (operation.str == "surface_offset_diagnostics") return surfaceOffsetDiagnostics068B(request); if (operation.str == "thicken") return thicken(request); if (operation.str == "extrude_surface") return extrudeSurface(request); if (operation.str == "revolve_surface") return revolveSurface(request); diff --git a/src/onboarding.cpp b/src/onboarding.cpp index 0940fe0..2853070 100644 --- a/src/onboarding.cpp +++ b/src/onboarding.cpp @@ -42,6 +42,17 @@ arkjson::Value agentOnboard(const AgentSession& session,const arkjson::Value& ar auto list=[](std::initializer_list strings){V a=V::makeArr();for(auto s:strings)a.arr.push_back(V::makeStr(s));return a;}; r.set("workflow",list({"Reuse agent_onboard detail:guide for static guidance. Read doc_info detail:revision for current revision/status, or doc_info detail:digest for a compact per-revision inventory whose fingerprints, sent back as known_fingerprints, return only later changes. Then use object_context for selected targets or filtered doc_info detail:design for required operations/dependencies and measured evidence. Use doc_get only when the full document is needed.","Use doc_preview detail:changes for compact checked proposals and doc_apply with expected_revision. One batch recomputes once; any failure rolls back the entire batch.","Use created_ids returned by a batch for later feature inputs. Do not assume IDs or use triangle IDs as persistent references.","Inspect native_inspect detail:properties for current native validity/physical properties, report for operation diagnostics, full for reference topology. Mesh/raycast evidence is display tessellation.","Keep queries compact; request meshes or snapshots only when needed. Save the parametric document with doc_save."})); r.set("available_topics",list({"bom","fasteners","components","vendors","plastics","motion","manufacturing","physics","automation","overview","sketch","tube","assembly","surfacing","sheet","solids","mesh","materials","frames","electronics","routing","suspension","skeleton","drawings","holes","cad_import","containers","stamps","planes","history","configurations","wood","networks","lighting","hud","exploded_views","schematics","rubber","transmission","programs","variants","design_review"})); + if(topic=="surfacing"){ + r.set("surface_modeling_068b",list({ + "surface_control exposes quality (native sampled curvature), seam (native boundary jets), match_plan (bounded existing-boundary G0/G1/G2), group_plan (explicit pole groups/locks/symmetry), loft_diagnose, network_plan, operations_inspect, multi_trim_plan, extend_trimmed_plan, sew_inspect/sew_plan and offset_check/offset_plan. Read the current tool schema and use the observed expected_revision.", + "New *_plan actions may return cached doc_preview candidates: review their native evidence and explicitly apply candidate_id at the same revision. Existing stretch/glue/group plans also expose a preview call recipe. A plan is never a published surface. Team candidates retain role ownership and ordinary command scope checks.", + "Match requires exact source/target fingerprints and explicit natural sides of compatible non-rational open BSpline faces; no silent basis fitting. Independent native sampled positional, tangent-plane and common-tangent curvature-tensor evidence is separate from requested derivative order. Unsupported rational/trimmed/periodic or incompatible basis cases reject.", + "Curve networks use explicit intersecting curve families with declared station/reversal correspondence. Supported Gordon construction works on exact compatible single-span polynomial curves. Invalid crossings and unsupported bases reject; meshes never choose production surface geometry.", + "Multi-trim retains explicitly selected source fragments and reports removed regions. Trim-preserving extension supports explicit rectangular outer boundaries with inner holes; unsupported trims reject. Sewing reports exact free-boundary references/gaps and never increases tolerance to close a shell.", + "Offset diagnostics sample native curvature on trimmed faces, trial the actual producer and check candidate topology/self-interference. Magnitude-to-radius hotspots are risk locations, not a proved failure cause or a global safety certificate. Keep undefined samples explicit; never alter thickness automatically.", + "Curvature/zebra displays use native sample positions/normals but interpolated colors and reflections are display evidence. All reported continuity/curvature domains and between-sample limitations remain explicit. No manufacturing or global G2 certification is inferred." + })); + } r.set("drawing_authorization",V::makeStr(drawingAuthorization)); if(topic=="variants"){ r.set("tools",list({"design_variants","parametric_program","doc_info","doc_apply","snapshot","native_inspect"})); diff --git a/src/serialize.cpp b/src/serialize.cpp index e2ca719..d2086de 100644 --- a/src/serialize.cpp +++ b/src/serialize.cpp @@ -502,6 +502,7 @@ bool arcRecipeDocument(const Document& doc){ return false; } +bool surfaceFeaturesRequire57(const Document& document){for(const auto& f:document.features)if(f.type==FeatureType::SurfaceEdit){const auto* op=f.nativeSpec.find("op");if(op&&(op->asStr()=="match_boundary"||op->asStr()=="curve_network"||op->asStr()=="multi_trim"||op->asStr()=="extend_trimmed"))return true;}return false;} } // namespace // --------------------------------------------------------------------------- @@ -671,6 +672,7 @@ std::string documentToJson(const Document& doc,bool includeAudit,bool includeHis if(!doc.parametricPrograms.isNull()){validateParametricPrograms(doc.parametricPrograms);r.set("parametric_programs",doc.parametricPrograms);r.set("version",Value::makeNum(55));} if(!doc.designVariants.isNull()){validateDesignVariants(doc.designVariants);r.set("design_variants",doc.designVariants);r.set("version",Value::makeNum(56));} for(const auto& drawing:doc.drawings)if(drawing.find("geometric_tolerances")){r.set("version",Value::makeNum(56));break;} + if(surfaceFeaturesRequire57(doc))r.set("version",Value::makeNum(57)); if(includeAudit&&includeHistory)iterationPersist(r,doc); canonicalDocumentKeys(r); std::string serialized=r.dump(); @@ -681,7 +683,7 @@ std::string documentToJson(const Document& doc,bool includeAudit,bool includeHis static bool documentFromValue(Value& v,Document& doc,std::string* err){ auto fail=[&](const std::string& m){ if(err)*err=m; return false; }; if(v.t!=Value::Obj) return fail("root must be object"); - if(auto ver=v.find("version"); ver && (ver->t!=Value::Num || !std::isfinite(ver->num)||ver->num!=std::floor(ver->num)||ver->num<1||ver->num>56)) + if(auto ver=v.find("version"); ver && (ver->t!=Value::Num || !std::isfinite(ver->num)||ver->num!=std::floor(ver->num)||ver->num<1||ver->num>57)) return fail("unsupported document version"); Value history;std::string historyError;if(!iterationExpand(v,history,historyError))return fail(historyError); if(const auto* nodes=v.find("assembly");nodes&&nodes->t==Value::Arr)for(const auto& node:nodes->arr)if(const auto* pattern=node.find("pattern");pattern&&pattern->find("carry_frame")){ @@ -963,6 +965,7 @@ static bool documentFromValue(Value& v,Document& doc,std::string* err){ for(const auto& node:nd.assembly)if(assemblyPatternHasCarry(node.pattern)){const auto* version=v.find("version");if(!version||version->num<44)return fail("Pattern carry frames require document version 44");} if(curvePattern044BNeedsVersion47(nd)){const auto* version=v.find("version");if(!version||version->num<47)return fail("044B curve pattern paths, pitch spacing, frames and support inputs require document version 47");} if(media044BNeedsVersion47(nd)){const auto* version=v.find("version");if(!version||version->num<47)return fail("044B procedural appearance patterns, animated GIF/video assets and stamp playback require document version 47");} + if(surfaceFeaturesRequire57(nd)){const auto* version=v.find("version");if(!version||version->num<57)return fail("068B surface match/network/multi-trim/trim-preserving extension require document version 57");} if(profileRegions046BNeedsVersion48(nd)){const auto* version=v.find("version");if(!version||version->num<48)return fail("046B profile region selections (native.regions) require document version 48");} if(motionReceiptsRequireDocumentVersion49(nd)){const auto* version=v.find("version");if(!version||version->num<49)return fail("049A baked motion receipts (frames_sha256, frames as derived data) require document version 49");} try{validateAppearanceAuthoring024B(nd,false);}catch(const std::exception& error){return fail(error.what());} diff --git a/src/surface_edit_059c.cpp b/src/surface_edit_059c.cpp index 90721f7..845e5ea 100644 --- a/src/surface_edit_059c.cpp +++ b/src/surface_edit_059c.cpp @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include namespace ark { namespace { @@ -16,10 +19,38 @@ u64 id(const Document& document,const V& value){u64 result=0;unsigned count=0;fo V json(const char* str){V v;need(arkjson::parse(str,v),"Internal schema error");return v;} NativePayload exact(Document& d,u64 source){ensureNativeBody(d,source,d.evalBodies);for(const auto& b:d.evalBodies)if(b.id==source){need(b.nativeData.find("brep_base64")&&b.nativeData.find("topology"),"Exact source B-rep and topology are required");return b.nativeData;}throw std::runtime_error("SURFACE_CONTROL: source has no evaluated body");} void transfer(const V& from,V& to,std::initializer_list fields){for(const auto* k:fields)if(const auto* p=from.find(k))to.set(k,*p);} +V groupEdits068(const V& controls,const V& args){ + const int nu=(int)field(controls,"u_count").num,nv=(int)field(controls,"v_count").num;const auto& poles=field(controls,"poles").arr; + const auto& selection=field(args,"selection");keys(selection,{"mode","poles","u","v","u_min","u_max","v_min","v_max"});const auto mode=text(selection,"mode"); + if(mode=="poles")keys(selection,{"mode","poles"});else if(mode=="row")keys(selection,{"mode","u"});else if(mode=="column")keys(selection,{"mode","v"});else if(mode=="rectangle")keys(selection,{"mode","u_min","u_max","v_min","v_max"}); + auto index=[&](const V& value,int cap){need(value.t==V::Num&&std::isfinite(value.num)&&value.num>=0&&value.num> selected; + if(mode=="poles"){const auto& list=field(selection,"poles");need(list.t==V::Arr&&!list.arr.empty()&&list.arr.size()<=128,"Choose 1..128 explicit poles");for(const auto& p:list.arr){need(p.t==V::Arr&&p.arr.size()==2,"Selected pole is [u,v]");need(selected.emplace(index(p.arr[0],nu),index(p.arr[1],nv)).second,"Duplicate selected pole");}} + else if(mode=="row"){int u=index(field(selection,"u"),nu);for(int v=0;vt==V::Num&&std::isfinite(r->num)&&r->num>=0&&r->num<=32,"Influence radius is 0..32 control-net steps");radius=r->num;} + std::set locked;if(const auto* list=args.find("lock_boundaries")){need(list->t==V::Arr,"lock_boundaries must be an array");for(const auto& b:list->arr){need(b.t==V::Str&&(b.str=="u_min"||b.str=="u_max"||b.str=="v_min"||b.str=="v_max"),"Unknown locked boundary");locked.insert(b.str);}} + auto isLocked=[&](int u,int v){return(u==0&&locked.count("u_min"))||(u==nu-1&&locked.count("u_max"))||(v==0&&locked.count("v_min"))||(v==nv-1&&locked.count("v_max"));}; + std::map,std::array> moves; + for(int u=0;u0&&(radius==0||distance>=radius))continue;const double t=distance==0?1.:1.-distance/radius,weight=t*t*(3.-2.*t);moves[{u,v}]={d[0]*weight,d[1]*weight,d[2]*weight};} + if(const auto* mirror=args.find("symmetry")){keys(*mirror,{"direction","axis","origin_mm"});const auto direction=text(*mirror,"direction"),axis=text(*mirror,"axis");need(direction=="u"||direction=="v","Symmetry direction is u or v");need(axis=="x"||axis=="y"||axis=="z","Symmetry axis is x, y or z");int k=axis=="x"?0:axis=="y"?1:2;const auto& o=field(*mirror,"origin_mm");need(o.t==V::Num&&std::isfinite(o.num),"Finite symmetry origin required"); + const auto& knots=field(controls,direction=="u"?"u_knots":"v_knots").arr;const auto& multiplicities=field(controls,direction=="u"?"u_multiplicities":"v_multiplicities").arr;need(knots.size()>=2&&knots.size()==multiplicities.size(),"Incomplete symmetry basis");const double knotStart=knots.front().num,knotSpan=knots.back().num-knotStart;need(knotSpan>0,"Degenerate symmetry knot span");for(size_t i=0;isecond[j]-mirrored[j])<=1e-10,"Selected displacements conflict with declared symmetry");moves[other]=mirrored;} + } + V edits=V::makeArr();for(const auto& [at,change]:moves){if(std::hypot(change[0],std::hypot(change[1],change[2]))<=1e-12)continue;V row=V::makeObj(),offset=V::makeArr();row.set("u",V::makeNum(at.first));row.set("v",V::makeNum(at.second));for(double x:change)offset.arr.push_back(V::makeNum(x));row.set("delta_mm",offset);edits.arr.push_back(row);}need(!edits.arr.empty()&&edits.arr.size()<=128,"Group selection must move 1..128 unlocked poles; choose a smaller region");return edits; +} } -V surfaceControlSchema059(){return json(R"({"type":"object","properties":{"action":{"type":"string","enum":["inspect","candidates","stretch_plan","glue_plan"]},"expected_revision":{"type":"integer","minimum":0},"id":{"type":["integer","string"]},"reference":{"type":"string"},"source_brep_sha256":{"type":"string"},"target_id":{"type":["integer","string"]},"target_brep_sha256":{"type":"string"},"u":{"type":"integer","minimum":0,"maximum":31},"v":{"type":"integer","minimum":0,"maximum":31},"max_distance_mm":{"type":"number","exclusiveMinimum":0,"maximum":1000},"limit":{"type":"integer","minimum":1,"maximum":64},"max_displacement_mm":{"type":"number","exclusiveMinimum":0,"maximum":100000},"edits":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"u":{"type":"integer","minimum":0,"maximum":31},"v":{"type":"integer","minimum":0,"maximum":31},"delta_mm":{"type":"array","minItems":3,"maxItems":3,"items":{"type":"number"}}},"required":["u","v","delta_mm"],"additionalProperties":false}},"target_vertex":{"type":"string"},"target_edge":{"type":"string"},"tangent_axis":{"type":"string","enum":["none","u","v"]},"tangent_tolerance_deg":{"type":"number","exclusiveMinimum":0,"maximum":1},"name":{"type":"string"}},"required":["action","expected_revision","id"],"additionalProperties":false})");} +V surfaceControlSchema059(){return json(R"({"type":"object","properties":{"action":{"type":"string","enum":["inspect","candidates","stretch_plan","glue_plan","group_plan"]},"expected_revision":{"type":"integer","minimum":0},"id":{"type":["integer","string"]},"reference":{"type":"string"},"source_brep_sha256":{"type":"string"},"target_id":{"type":["integer","string"]},"target_brep_sha256":{"type":"string"},"u":{"type":"integer","minimum":0,"maximum":31},"v":{"type":"integer","minimum":0,"maximum":31},"max_distance_mm":{"type":"number","exclusiveMinimum":0,"maximum":1000},"limit":{"type":"integer","minimum":1,"maximum":64},"max_displacement_mm":{"type":"number","exclusiveMinimum":0,"maximum":100000},"edits":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"u":{"type":"integer","minimum":0,"maximum":31},"v":{"type":"integer","minimum":0,"maximum":31},"delta_mm":{"type":"array","minItems":3,"maxItems":3,"items":{"type":"number"}}},"required":["u","v","delta_mm"],"additionalProperties":false}},"target_vertex":{"type":"string"},"target_edge":{"type":"string"},"tangent_axis":{"type":"string","enum":["none","u","v"]},"tangent_tolerance_deg":{"type":"number","exclusiveMinimum":0,"maximum":1},"name":{"type":"string"},"selection":{"type":"object"},"delta_mm":{"type":"array","minItems":3,"maxItems":3,"items":{"type":"number"}},"influence_radius":{"type":"number","minimum":0,"maximum":32},"lock_boundaries":{"type":"array","items":{"type":"string","enum":["u_min","u_max","v_min","v_max"]}},"symmetry":{"type":"object","properties":{"direction":{"enum":["u","v"]},"axis":{"enum":["x","y","z"]},"origin_mm":{"type":"number"}},"required":["direction","axis","origin_mm"],"additionalProperties":false}},"required":["action","expected_revision","id"],"additionalProperties":false})");} V surfaceControl059(AgentSession& session,const V& args){ const auto& revision=field(args,"expected_revision");need(revision.t==V::Num&&revision.num==(double)session.revision,"Revision changed; inspect the current document");const auto action=text(args,"action"); + if(action=="group_plan"){ + keys(args,{"action","expected_revision","id","reference","source_brep_sha256","max_displacement_mm","selection","delta_mm","influence_radius","lock_boundaries","symmetry","name"});V inspect=V::makeObj();inspect.set("action",V::makeStr("inspect"));transfer(args,inspect,{"expected_revision","id","reference"});const V controls=surfaceControl059(session,inspect);need(text(args,"source_brep_sha256")==text(controls,"source_brep_sha256"),"Source B-rep changed; inspect the current control net");V expanded=V::makeObj();expanded.set("action",V::makeStr("stretch_plan"));transfer(args,expanded,{"expected_revision","id","reference","source_brep_sha256","max_displacement_mm","name"});expanded.set("edits",groupEdits068(controls,args));V result=surfaceControl059(session,expanded);result.set("expanded_edits",field(expanded,"edits"));result.set("selection",field(args,"selection"));result.set("group_scope",V::makeStr("Explicit source control-net indices; smoothstep influence in grid-index distance, locked boundary poles unchanged, optional whole-net mirror with equal rational weights and reflected knot/multiplicity basis. Existing exact deformation validity checks apply."));return result; + } if(action=="inspect")keys(args,{"action","expected_revision","id","reference"}); else if(action=="candidates")keys(args,{"action","expected_revision","id","reference","source_brep_sha256","target_id","target_brep_sha256","u","v","max_distance_mm","limit"}); else if(action=="stretch_plan")keys(args,{"action","expected_revision","id","reference","source_brep_sha256","max_displacement_mm","edits","name"}); diff --git a/src/surface_network_068b.cpp b/src/surface_network_068b.cpp new file mode 100644 index 0000000..8fafee0 --- /dev/null +++ b/src/surface_network_068b.cpp @@ -0,0 +1,43 @@ +#include "ark/surface_network_068b.hpp" +#include "ark/native_backend.hpp" +#include "ark/native_features.hpp" +#include +#include +#include +namespace ark { namespace { +using V=arkjson::Value; +const V& get(const V& v,const char* key){static const V nil;const auto* p=v.find(key);return p?*p:nil;} +void require(bool ok,const std::string& message){if(!ok)throw std::runtime_error("SURFACE_NETWORK: "+message);} +void keys(const V& v,std::initializer_list allowed){require(v.t==V::Obj,"Expected object");for(const auto& p:v.obj)require(std::any_of(allowed.begin(),allowed.end(),[&](const char* key){return p.first==key;}),"Unknown field "+p.first);} +u64 feature(const Document& d,const V& value){u64 found=0;unsigned matches=0;for(const auto& f:d.features)if((value.t==V::Num&&value.num==(double)f.id)||(value.t==V::Str&&value.str==f.name)){found=f.id;++matches;}require(matches==1,"Choose one existing unambiguous feature");return found;} +V result(const V& reply){require(!get(reply,"isError").b,get(get(reply,"structuredContent"),"error").asStr());return get(reply,"structuredContent");} +void transfer(const V& a,V& b,std::initializer_list names){for(const auto* name:names)if(const auto* p=a.find(name))b.set(name,*p);} +} +bool surfaceNetworkTool068B(AgentSession& session,const V& args,V& out){ + const auto action=get(args,"action").asStr();if(action!="network_plan"&&action!="loft_diagnose")return false; + const auto& revision=get(args,"expected_revision");require(revision.t==V::Num&&revision.num==(double)session.revision,"Revision changed; inspect current geometry"); + if(action=="network_plan")keys(args,{"action","expected_revision","name","u_curves","v_curves","u_stations","v_stations","u_reverse","v_reverse"}); + else keys(args,{"action","expected_revision","id","sections","guides","controls"}); + Document snapshot=session.document;snapshot.evaluatingBodies=nullptr; + if(action=="loft_diagnose"){ + Feature selected;if(args.find("id")){const auto id=feature(snapshot,get(args,"id"));selected=*snapshot.find(id);require(selected.type==FeatureType::Loft,"Select an existing loft");} + else{selected.type=FeatureType::Loft;selected.p["solid"]="0";selected.nativeSpec=V::makeObj();} + transfer(args,selected.nativeSpec,{"sections","guides","controls"}); + if(args.find("guides")&&get(args,"guides").t==V::Arr&&get(args,"guides").arr.empty())selected.nativeSpec.obj.erase(std::remove_if(selected.nativeSpec.obj.begin(),selected.nativeSpec.obj.end(),[](const auto& entry){return entry.first=="guides";}),selected.nativeSpec.obj.end()); + require(get(selected.nativeSpec,"sections").t==V::Arr,"Choose ordered loft sections"); + for(const auto& section:get(selected.nativeSpec,"sections").arr)if(section.t==V::Str)for(const auto& f:snapshot.features)if(f.name==section.str&&isCurveFeature(f.type))ensureNativeBody(snapshot,f.id,snapshot.evalBodies); + for(const auto& guide:get(selected.nativeSpec,"guides").arr)if(guide.t==V::Str)for(const auto& f:snapshot.features)if(f.name==guide.str&&isCurveFeature(f.type))ensureNativeBody(snapshot,f.id,snapshot.evalBodies); + auto request=surfaceRequestForInspection068B(snapshot,selected);request.set("op",V::makeStr("loft_diagnostics"));out=nativeModelRequest(request);out.set("revision",revision);if(args.find("id"))out.set("id",get(args,"id"));return true; + } + V encoded=V::makeArr(),inputs=V::makeArr();std::set unique; + for(const auto* family:{"u_curves","v_curves"}){const auto& curves=get(args,family);require(curves.t==V::Arr&&curves.arr.size()>=2&&curves.arr.size()<=9,"Each family needs 2..9 explicit curve IDs or names");for(const auto& source:curves.arr){const auto id=feature(snapshot,source);require(unique.insert(id).second,"Each network curve may occur only once");require(isCurveFeature(snapshot.find(id)->type),"Network inputs must be native curve features");ensureNativeBody(snapshot,id,snapshot.evalBodies);const Body* body=nullptr;for(const auto& b:snapshot.evalBodies)if(b.id==id)body=&b;require(body&&body->nativeData.find("brep_base64"),"Curve has no exact native B-rep");encoded.arr.push_back(*body->nativeData.find("brep_base64"));inputs.arr.push_back(V::makeNum((double)id));}} + V native=V::makeObj();native.set("op",V::makeStr("curve_network"));native.set("u_count",V::makeNum((double)get(args,"u_curves").arr.size()));transfer(args,native,{"u_stations","v_stations","u_reverse","v_reverse"}); + V request=native;request.set("op",V::makeStr("surface_network"));request.set("input_breps",encoded);const auto measured=nativeModelRequest(request); + const std::string name=args.find("name")?get(args,"name").asStr():"Curve network";require(!name.empty()&&name.size()<=128,"Choose a nonempty result name"); + V command=V::makeObj();command.set("op",V::makeStr("feature.add"));command.set("type",V::makeStr("surface_edit"));command.set("name",V::makeStr(name));command.set("inputs",inputs);command.set("native",native);V commands=V::makeArr();commands.arr.push_back(command);V preview=V::makeObj();preview.set("expected_revision",revision);preview.set("commands",commands);preview.set("detail",V::makeStr("changes"));out=result(session.call("doc_preview",preview));require(get(out,"valid").b&&get(out,"candidate_cached").b,"Network preview did not validate");out.set("network_evidence",get(measured,"report"));out.set("coordinate_space",V::makeStr("Explicit curve definitions in shared local coordinates; no occurrence transforms are inferred"));return true; +} +void extendSurfaceNetworkSchema068B(V& schema){ + V properties=get(schema,"properties"),action=get(properties,"action"),choices=get(action,"enum");for(const char* name:{"network_plan","loft_diagnose"})choices.arr.push_back(V::makeStr(name));action.set("enum",choices);properties.set("action",action); + V extra;arkjson::parse(R"({"u_curves":{"type":"array","minItems":2,"maxItems":9,"items":{"type":["integer","string"]}},"v_curves":{"type":"array","minItems":2,"maxItems":9,"items":{"type":["integer","string"]}},"u_stations":{"type":"array","minItems":2,"maxItems":9,"items":{"type":"number","minimum":0,"maximum":1}},"v_stations":{"type":"array","minItems":2,"maxItems":9,"items":{"type":"number","minimum":0,"maximum":1}},"u_reverse":{"type":"array","minItems":2,"maxItems":9,"items":{"type":"boolean"}},"v_reverse":{"type":"array","minItems":2,"maxItems":9,"items":{"type":"boolean"}},"sections":{"type":"array","minItems":2,"maxItems":32,"items":{"type":"string"}},"guides":{"type":"array","maxItems":8,"items":{"type":"string"}},"controls":{"type":"object"}})",extra);for(const auto& p:extra.obj)properties.set(p.first,p.second);schema.set("properties",properties);V required=V::makeArr();required.arr={V::makeStr("action"),V::makeStr("expected_revision")};schema.set("required",required); +} +} diff --git a/src/surface_offset_068b.cpp b/src/surface_offset_068b.cpp new file mode 100644 index 0000000..235c6e6 --- /dev/null +++ b/src/surface_offset_068b.cpp @@ -0,0 +1,38 @@ +#include "ark/surface_offset_068b.hpp" +#include "ark/native_features.hpp" +#include "ark/native_backend.hpp" +#include +#include +namespace ark { namespace { +using V=arkjson::Value; +const V& offsetField068(const V& value,const char* name){static const V nil;auto p=value.find(name);return p?*p:nil;} +void offsetNeed068(bool ok,const std::string& why){if(!ok)throw std::runtime_error("SURFACE_OFFSET: "+why);} +V offsetJson068(const char* value){V out;offsetNeed068(arkjson::parse(value,out),"Internal schema");return out;} +} +bool surfaceOffsetTool068B(AgentSession& session,const V& args,V& out){ + const auto action=offsetField068(args,"action").asStr();if(action!="offset_check"&&action!="offset_plan")return false; + for(const auto& item:args.obj)offsetNeed068(item.first=="action"||item.first=="expected_revision"||item.first=="id"||item.first=="mode"||item.first=="amount"||item.first=="samples"||item.first=="source_brep_sha256"||item.first=="name","Unknown field: "+item.first); + const auto& revision=offsetField068(args,"expected_revision");offsetNeed068(revision.t==V::Num&&revision.num==double(session.revision),"Revision changed; inspect again"); + const auto& selector=offsetField068(args,"id");u64 id=0;unsigned matches=0;for(const auto& f:session.document.features)if((selector.t==V::Num&&selector.num==double(f.id))||(selector.t==V::Str&&selector.str==f.name)){id=f.id;++matches;} + offsetNeed068(matches==1,"Choose one existing, unambiguous feature"); + const auto mode=offsetField068(args,"mode").asStr();offsetNeed068(mode=="offset"||mode=="thicken","Choose offset or thicken"); + const auto& authored=offsetField068(args,"amount");bool valid=false;double amount=authored.t==V::Num?authored.num:authored.t==V::Str?evalExpr(authored.str,session.document.buildEnv(),&valid):0; + if(authored.t==V::Num)valid=std::isfinite(amount);offsetNeed068(valid&&std::isfinite(amount)&&std::abs(amount)>1e-6&&std::abs(amount)<=100000,"Amount must be a finite nonzero length, at most 100000 mm"); + Document snapshot=session.document;snapshot.evaluatingBodies=nullptr;ensureNativeBody(snapshot,id,snapshot.evalBodies);const Body* body=nullptr;for(const auto& b:snapshot.evalBodies)if(b.id==id)body=&b; + offsetNeed068(body&&body->nativeData.find("brep_base64")&&body->nativeData.find("topology"),"An exact source face or shell is required"); + const V native=body->nativeData;const auto& topology=offsetField068(native,"topology");const auto& hash=offsetField068(topology,"brep_sha256");offsetNeed068(hash.t==V::Str&&hash.str.size()==64,"Source has no exact fingerprint"); + if(action=="offset_plan"||args.find("source_brep_sha256"))offsetNeed068(offsetField068(args,"source_brep_sha256").asStr()==hash.str,"Source geometry changed; repeat the diagnostic"); + V request=V::makeObj();request.set("op",V::makeStr("surface_offset_diagnostics"));request.set("input_brep",offsetField068(native,"brep_base64"));request.set("topology",topology);request.set("mode",V::makeStr(mode));request.set("amount",V::makeNum(amount));if(args.find("samples"))request.set("samples",offsetField068(args,"samples")); + V diagnosis=nativeModelRequest(request);diagnosis.set("revision",revision);diagnosis.set("id",V::makeNum(double(id)));diagnosis.set("source_brep_sha256",hash); + if(action=="offset_check"){out=diagnosis;return true;} + offsetNeed068(offsetField068(diagnosis,"candidate_valid").b,offsetField068(diagnosis,"candidate_error").asStr()); + V command=offsetJson068(R"({"op":"feature.add"})"),parameters=V::makeObj(),inputs=V::makeArr();command.set("type",V::makeStr(mode=="offset"?"offset_surface":"thicken"));command.set("name",V::makeStr(args.find("name")?offsetField068(args,"name").asStr():mode=="offset"?"Checked surface offset":"Checked surface thickness"));parameters.set(mode=="offset"?"distance":"thickness",authored);command.set("p",parameters);inputs.arr.push_back(V::makeNum(double(id)));command.set("inputs",inputs); + const auto* source=session.document.find(id);if(source&&!source->material.empty())command.set("material",V::makeStr(source->material));if(source&&source->appearance.t==V::Obj)command.set("appearance",source->appearance); + V preview=V::makeObj(),commands=V::makeArr();commands.arr.push_back(command);preview.set("commands",commands);preview.set("expected_revision",revision);preview.set("detail",V::makeStr("changes"));const V response=session.call("doc_preview",preview); + offsetNeed068(!offsetField068(response,"isError").b,offsetField068(response,"structuredContent").dump());out=offsetField068(response,"structuredContent");offsetNeed068(offsetField068(out,"valid").b&&offsetField068(out,"candidate_cached").b,"Exact preview could not be retained");out.set("offset_diagnostics",diagnosis);return true; +} +void extendSurfaceOffsetSchema068B(V& schema){ + V props=offsetField068(schema,"properties"),action=offsetField068(props,"action"),choices=offsetField068(action,"enum");for(const char* name:{"offset_check","offset_plan"})choices.arr.push_back(V::makeStr(name));action.set("enum",choices);props.set("action",action); + props.set("mode",offsetJson068(R"({"type":"string","enum":["offset","thicken"]})"));props.set("amount",offsetJson068(R"({"type":["number","string"],"description":"Signed distance/thickness in mm or a named parameter expression; the source is never changed by diagnostics."})"));schema.set("properties",props); +} +} diff --git a/src/surface_operations_068b.cpp b/src/surface_operations_068b.cpp new file mode 100644 index 0000000..e471332 --- /dev/null +++ b/src/surface_operations_068b.cpp @@ -0,0 +1,34 @@ +#include "ark/surface_operations_068b.hpp" +#include "ark/native_features.hpp" +#include "ark/native_backend.hpp" +#include +#include +#include +#include +namespace ark { namespace { +using V=arkjson::Value; +const V& at(const V& v,const char* key){const auto* p=v.find(key);if(!p)throw std::runtime_error(std::string("SURFACE_OPERATIONS: Missing ")+key);return *p;} +void require(bool pass,const std::string& message){if(!pass)throw std::runtime_error("SURFACE_OPERATIONS: "+message);} +void keys(const V& v,std::initializer_list allowed){require(v.t==V::Obj,"Expected object");for(const auto& kv:v.obj)require(std::any_of(allowed.begin(),allowed.end(),[&](const auto* k){return kv.first==k;}),"Unknown field "+kv.first);} +u64 feature(const Document& d,const V& value){u64 found=0;for(const auto& f:d.features)if((value.t==V::Num&&value.num==(double)f.id)||(value.t==V::Str&&value.str==f.name)){require(!found,"Ambiguous feature");found=f.id;}require(found,"Unknown source feature");return found;} +V exact(Document& d,u64 id){ensureNativeBody(d,id,d.evalBodies);for(const auto& b:d.evalBodies)if(b.id==id){require(b.nativeData.find("brep_base64")&&b.nativeData.find("topology"),"Exact source geometry required");return b.nativeData;}throw std::runtime_error("SURFACE_OPERATIONS: No evaluated source");} +V payload(const V& r){require(!at(r,"isError").b,r.find("structuredContent")?r.find("structuredContent")->dump():"Tool failed");return at(r,"structuredContent");} +V number(u64 n){return V::makeNum((double)n);} +} +bool surfaceOperationsTool068B(AgentSession& s,const V& a,V& out){ + const auto* actionValue=a.find("action");if(!actionValue||actionValue->t!=V::Str)return false;const auto action=actionValue->str;if(action!="operations_inspect"&&action!="multi_trim_plan"&&action!="extend_trimmed_plan"&&action!="sew_inspect"&&action!="sew_plan")return false; + if(action=="operations_inspect")keys(a,{"action","expected_revision","id"});else if(action=="extend_trimmed_plan")keys(a,{"action","expected_revision","id","bounds","extension","name"});else if(action=="multi_trim_plan")keys(a,{"action","expected_revision","sources","tool_id","keep_points","name"});else if(action=="sew_inspect")keys(a,{"action","expected_revision","sources"});else keys(a,{"action","expected_revision","sources","solid","require_connected","name"});const auto& rev=at(a,"expected_revision");require(rev.t==V::Num&&rev.num==double(s.revision),"Revision changed; inspect current source");Document snapshot=s.document;snapshot.evaluatingBodies=nullptr;V native=V::makeObj(),inputs=V::makeArr(),sourceRows=V::makeArr(); + auto append=[&](u64 id){const auto data=exact(snapshot,id);inputs.arr.push_back(number(id));V row=V::makeObj();row.set("id",number(id));row.set("source_brep_sha256",at(at(data,"topology"),"brep_sha256"));sourceRows.arr.push_back(row);return data;}; + if(action=="operations_inspect"){const auto id=feature(snapshot,at(a,"id"));const auto data=exact(snapshot,id);out=V::makeObj();out.set("revision",rev);out.set("id",number(id));out.set("source_brep_sha256",at(at(data,"topology"),"brep_sha256"));out.set("references",at(at(data,"topology"),"references"));out.set("report",at(data,"report"));V domain=V::makeObj();domain.set("op",V::makeStr("surface_domain_inspect"));domain.set("input_brep",at(data,"brep_base64"));try{out.set("domain",nativeModelRequest(domain));}catch(const std::exception& error){out.set("domain_unavailable",V::makeStr(error.what()));}return true;} + if(action=="extend_trimmed_plan"){append(feature(snapshot,at(a,"id")));native.set("op",V::makeStr("extend_trimmed"));require(bool(a.find("bounds"))!=bool(a.find("extension")),"Choose bounds or length extension, not both");for(const auto* k:{"bounds","extension"})if(const auto* p=a.find(k))native.set(k,*p);} + else {const auto& sources=at(a,"sources");require(sources.t==V::Arr&&sources.arr.size()>=(action=="multi_trim_plan"?1u:2u)&&sources.arr.size()<=16,"Choose 1..16 trim sources or 2..16 sew sources");V breps=V::makeArr(),topologies=V::makeArr(),faces=V::makeArr();std::set unique; + for(const auto& source:sources.arr){const V* ref=&source;std::string face;if(source.t==V::Obj){keys(source,{"id","face"});ref=&at(source,"id");if(const auto* f=source.find("face")){require(f->t==V::Str,"Face name must be text");face=f->str;}}const auto id=feature(snapshot,*ref);require(unique.insert(id).second,"Use each source feature once; extract distinct faces first for repeated body sources");const auto data=append(id);breps.arr.push_back(at(data,"brep_base64"));topologies.arr.push_back(at(data,"topology"));faces.arr.push_back(V::makeStr(face));if(action!="multi_trim_plan")require(face.empty(),"Sew consumes explicit face/shell definitions; extract semantic faces first");} + if(action=="multi_trim_plan"){native.set("op",V::makeStr("multi_trim"));native.set("source_faces",faces);const auto& points=at(a,"keep_points");require(points.t==V::Arr&&points.arr.size()==sources.arr.size(),"One keep point is required per source face");native.set("keep_points",points);const auto tool=feature(snapshot,at(a,"tool_id"));require(!unique.count(tool),"Trimming tool cannot also be a source");append(tool);} + else{native.set("op",V::makeStr("sew"));if(action=="sew_inspect"){V request=V::makeObj();request.set("op",V::makeStr("surface_sew_inspect"));request.set("inputs",breps);request.set("topologies",topologies);out=nativeModelRequest(request);out.set("revision",rev);out.set("sources",sourceRows);return true;}} + } + V command=V::makeObj();command.set("op",V::makeStr("feature.add"));const bool sew=action=="sew_plan";command.set("type",V::makeStr(sew?"sew":"surface_edit"));command.set("name",a.find("name")?*a.find("name"):V::makeStr(sew?"Sewn surface set":action=="multi_trim_plan"?"Trimmed surface set":"Extended surface with holes"));command.set("inputs",inputs); + if(sew){V p=V::makeObj();bool solid=false;if(const auto* v=a.find("solid")){require(v->t==V::Bool,"solid must be boolean");solid=v->b;}p.set("solid",V::makeStr(solid?"1":"0"));command.set("p",p);native=V::makeObj();bool connected=true;if(const auto* v=a.find("require_connected")){require(v->t==V::Bool,"require_connected must be boolean");connected=v->b;}native.set("require_connected",V::makeBool(connected));} + command.set("native",native);V commands=V::makeArr();commands.arr.push_back(command);V preview=V::makeObj();preview.set("expected_revision",rev);preview.set("commands",commands);preview.set("detail",V::makeStr("changes"));out=payload(s.call("doc_preview",preview));if(!at(out,"valid").b){const auto* failed=out.find("candidate_result");const auto* error=failed?failed->find("error"):nullptr;throw std::runtime_error("SURFACE_OPERATIONS: "+(error?error->asStr():"Native operation rejected the candidate"));}require(at(out,"candidate_cached").b,"Validated candidate could not be retained; reduce its size and prepare again");out.set("sources",sourceRows);out.set("operation",V::makeStr(action));out.set("note",V::makeStr("Reviewed exact candidate only; publish candidate_id with expected_revision. Tool/other source objects are not discarded."));return true; +} +void extendSurfaceOperationsSchema068B(V& schema){auto props=at(schema,"properties"),action=at(props,"action"),choices=at(action,"enum");for(const auto* name:{"operations_inspect","multi_trim_plan","extend_trimmed_plan","sew_inspect","sew_plan"})choices.arr.push_back(V::makeStr(name));action.set("enum",choices);props.set("action",action);for(const auto* name:{"sources","keep_points","bounds"}){V shape=V::makeObj();shape.set("type",V::makeStr("array"));props.set(name,shape);}V id=V::makeObj(),types=V::makeArr();types.arr={V::makeStr("integer"),V::makeStr("string")};id.set("type",types);props.set("tool_id",id);V object=V::makeObj();object.set("type",V::makeStr("object"));props.set("extension",object);V flag=V::makeObj();flag.set("type",V::makeStr("boolean"));props.set("solid",flag);props.set("require_connected",flag);schema.set("properties",props);V required=V::makeArr();required.arr={V::makeStr("action"),V::makeStr("expected_revision")};schema.set("required",required);} +} diff --git a/src/surface_quality_068b.cpp b/src/surface_quality_068b.cpp new file mode 100644 index 0000000..3de9727 --- /dev/null +++ b/src/surface_quality_068b.cpp @@ -0,0 +1,30 @@ +#include "ark/surface_quality_068b.hpp" +#include "ark/native_features.hpp" +#include "ark/native_backend.hpp" +#include +#include +#include +namespace ark { namespace { +using V=arkjson::Value; +void require(bool value,const std::string& reason){if(!value)throw std::runtime_error("SURFACE_QUALITY: "+reason);} +const V& get(const V& v,const char* k){static V nil;const auto* value=v.find(k);return value?*value:nil;} +std::string text(const V& v,const char* k){const auto& value=get(v,k);require(value.t==V::Str&&!value.str.empty()&&value.str.size()<=256,std::string("Expected ")+k);return value.str;} +void keys(const V& v,std::initializer_list allowed){require(v.t==V::Obj,"Expected an object");for(const auto& field:v.obj)require(std::any_of(allowed.begin(),allowed.end(),[&](const char* name){return field.first==name;}),"Unknown field "+field.first);} +u64 feature(const Document& d,const V& value){u64 result=0;int matches=0;for(const auto& f:d.features)if((value.t==V::Num&&value.num==(double)f.id)||(value.t==V::Str&&value.str==f.name)){result=f.id;++matches;}require(matches==1,"Choose one current exact feature ID or unique name");return result;} +NativePayload native(Document& d,u64 id){ensureNativeBody(d,id,d.evalBodies);for(const auto& b:d.evalBodies)if(b.id==id){require(b.nativeData.find("brep_base64")&&b.nativeData.find("topology"),"Exact B-rep source is required");return b.nativeData;}throw std::runtime_error("SURFACE_QUALITY: no exact body");} +void copy(const V& from,V& to,std::initializer_list fields){for(const auto* key:fields)if(const auto* value=from.find(key))to.set(key,*value);} +V parse(const char* s){V v;require(arkjson::parse(s,v),"Internal schema error");return v;} +} +bool surfaceQualityTool068B(AgentSession& session,const V& args,V& out){ + const auto action=get(args,"action").asStr();if(action!="quality"&&action!="seam"&&action!="match_plan")return false; + if(action=="quality")keys(args,{"action","expected_revision","id","reference","samples"}); + else if(action=="seam")keys(args,{"action","expected_revision","id","reference","target_id","target_reference","source_side","target_side","reverse","samples"}); + else keys(args,{"action","expected_revision","id","reference","source_brep_sha256","target_id","target_reference","target_brep_sha256","source_side","target_side","reverse","continuity","cross_scale","max_displacement_mm","samples","name"}); + require(get(args,"expected_revision").t==V::Num&&get(args,"expected_revision").num==(double)session.revision,"Revision changed; inspect the current document again");if(auto value=args.find("reverse"))require(value->t==V::Bool,"reverse must be a boolean"); + auto snapshot=std::make_unique(session.document);snapshot->evaluatingBodies=nullptr;const auto source=feature(*snapshot,get(args,"id"));const auto sourceData=native(*snapshot,source);V request=V::makeObj();request.set("op",V::makeStr(action=="quality"?"surface_quality_068b":action=="seam"?"surface_seam_068b":"surface_match_068b"));request.set("input_brep",*sourceData.find("brep_base64"));request.set("topology",*sourceData.find("topology"));copy(args,request,{"reference","source_brep_sha256","samples","source_side","target_side","reverse","continuity","cross_scale","max_displacement_mm"}); + u64 target=0;if(action!="quality"){target=feature(*snapshot,get(args,"target_id"));require(target!=source,"Select distinct source and target features");const auto targetData=native(*snapshot,target);request.set("target_brep",*targetData.find("brep_base64"));request.set("target_topology",*targetData.find("topology"));copy(args,request,{"target_reference","target_brep_sha256"});} + const V evaluated=nativeModelRequest(request);if(action!="match_plan"){out=evaluated;out.set("revision",V::makeNum((double)session.revision));out.set("id",V::makeNum((double)source));if(target)out.set("target_id",V::makeNum((double)target));out.set("coordinate_space",V::makeStr("definition local millimetres; occurrence transforms are not inferred"));return true;} + V recipe=V::makeObj();recipe.set("op",V::makeStr("match_boundary"));copy(args,recipe,{"reference","target_reference","source_brep_sha256","target_brep_sha256","source_side","target_side","reverse","continuity","cross_scale","max_displacement_mm","samples"});V command=V::makeObj(),inputs=V::makeArr();inputs.arr={V::makeNum((double)source),V::makeNum((double)target)};command.set("op",V::makeStr("feature.add"));command.set("type",V::makeStr("surface_edit"));command.set("name",V::makeStr(args.find("name")?text(args,"name"):"Matched surface boundary"));command.set("inputs",inputs);command.set("native",recipe);V commands=V::makeArr();commands.arr.push_back(command);V previewArgs=V::makeObj();previewArgs.set("expected_revision",V::makeNum((double)session.revision));previewArgs.set("detail",V::makeStr("changes"));previewArgs.set("commands",commands);V preview=V::makeObj();preview.set("tool",V::makeStr("doc_preview"));preview.set("arguments",previewArgs);const auto prepared=session.call("doc_preview",previewArgs);require(!get(prepared,"isError").b,prepared.dump());out=get(prepared,"structuredContent");require(get(out,"valid").b&&get(out,"candidate_cached").b,"Matching preview was not retained; inspect the rejection before applying");out.set("revision",V::makeNum((double)session.revision));out.set("commands",commands);out.set("preview",preview);out.set("evidence",get(evaluated,"report"));out.set("scope",V::makeStr("Read-only bounded compatible non-rational BSpline boundary plan. Preview and explicitly apply. Native sampled continuity is not a global guarantee or manufacturing qualification."));return true; +} +void extendSurfaceQualitySchema068B(V& schema){V props=get(schema,"properties"),action=get(props,"action"),choices=get(action,"enum");for(const char* name:{"quality","seam","match_plan"})choices.arr.push_back(V::makeStr(name));action.set("enum",choices);props.set("action",action);const auto fields=parse(R"({"target_reference":{"type":"string"},"source_side":{"type":"string","enum":["u_min","u_max","v_min","v_max"]},"target_side":{"type":"string","enum":["u_min","u_max","v_min","v_max"]},"reverse":{"type":"boolean"},"continuity":{"type":"integer","minimum":0,"maximum":2},"cross_scale":{"type":"number","exclusiveMinimum":0,"maximum":100},"samples":{"type":"integer","minimum":3,"maximum":129}})");for(const auto& field:fields.obj)props.set(field.first,field.second);schema.set("properties",props);} +} diff --git a/src/view/action_icons_selftest.inl b/src/view/action_icons_selftest.inl index 432e70d..db4c159 100644 --- a/src/view/action_icons_selftest.inl +++ b/src/view/action_icons_selftest.inl @@ -1,7 +1,7 @@ const u64 revision=g_session.revision,epoch=g_documentEpoch; const int originalW=winW,originalH=winH,originalModule=g_toolModule;const bool originalDock=g_assistantDockOpen; auto failure=[&](const std::string& detail){std::ofstream(shotPath+".action-icons-test.log")<<"FAIL: "< actions{58,357,585,586,587,590,549,152,153,154,650,659,687,710,730,731,732,750,755,49960,49920,49921,49922,49940,49941,49942}; + const std::vector actions{58,357,585,586,587,590,549,152,153,154,650,659,687,710,730,731,732,750,755,49960,49920,49921,49922,49940,49941,49942,49980,49981,50000,50001,50002,50003,50004,49506,50020,50021,50022,50023,50040,50041,50042,50043}; HMENU menu=CreatePopupMenu();for(int action:actions)AppendMenuA(menu,MF_STRING,(UINT_PTR)action,"Action icon");decorateMenu(menu); for(size_t i=0;i& r){ {auto& compare=r[49940];rect(compare,.14f,.16f,.44f,.54f);rect(compare,.42f,.3f,.44f,.54f);} {auto& repair=r[49941];cube(repair,.4f,.4f,.5f);pencil(repair,.5f,.5f,.35f);} {auto& hide=r[49942];rect(hide,.18f,.22f,.64f,.56f);line(hide,.15f,.85f,.85f,.15f);} + {auto& i=r[49980];for(float v:{.2f,.4f,.6f,.8f}){poly(i,{{.12f,v},{.5f,v-.08f},{.88f,v}});poly(i,{{v,.12f},{v+.06f,.5f},{v,.88f}});}} + {auto& i=r[49981];poly(i,{{.18f,.18f},{.36f,.48f},{.18f,.82f}});poly(i,{{.72f,.18f},{.56f,.48f},{.82f,.82f}});for(float y:{.23f,.5f,.77f})line(i,.38f,y,.55f,y);} + {auto& i=r[50000];plane(i,.5f,.5f,.7f,.52f);for(float v:{.32f,.46f,.6f})poly(i,{{.2f,v+.12f},{.47f,v-.06f},{.8f,v+.05f}});} + {auto& i=r[50001];line(i,.32f,.15f,.32f,.85f);line(i,.68f,.15f,.68f,.85f);arrow(i,.48f,.5f,.33f,.5f,.09f);arrow(i,.52f,.5f,.67f,.5f,.09f);} + {auto& i=r[50002];poly(i,{{.16f,.2f},{.4f,.4f},{.5f,.8f}});poly(i,{{.84f,.2f},{.6f,.4f},{.5f,.8f}});arrow(i,.22f,.64f,.42f,.64f,.09f);arrow(i,.78f,.64f,.58f,.64f,.09f);} + {auto& i=r[50003];line(i,.2f,.2f,.8f,.8f);line(i,.8f,.2f,.2f,.8f);} + {auto& i=r[50004];check(i,.18f,.24f,.64f);} + {auto& i=r[49506];for(float v:{.22f,.5f,.78f}){line(i,v,.18f,v,.82f);line(i,.18f,v,.82f,v);}for(auto p:{std::pair{.22f,.22f},{.5f,.22f},{.22f,.5f},{.5f,.5f}})circle(i,p.first,p.second,.055f);} + {auto& i=r[50020];plane(i,.5f,.5f,.7f,.55f);line(i,.15f,.85f,.85f,.15f);} + {auto& i=r[50021];rect(i,.14f,.22f,.45f,.58f);circle(i,.35f,.5f,.10f);arrow(i,.64f,.5f,.9f,.5f,.1f);} + {auto& i=r[50022];line(i,.4f,.14f,.4f,.86f);line(i,.6f,.14f,.6f,.86f);for(float y:{.22f,.42f,.62f,.82f})line(i,.32f,y,.68f,y-.07f);} + r[50023]=r[50022]; + {auto& i=r[50040];plane(i,.42f,.36f,.6f,.35f);plane(i,.57f,.66f,.6f,.35f);line(i,.18f,.5f,.18f,.78f);} + {auto& i=r[50041];plane(i,.4f,.35f,.6f,.35f);check(i,.43f,.54f,.42f);} + {auto& i=r[50042];rect(i,.2f,.12f,.6f,.76f);for(float y:{.3f,.5f,.7f})line(i,.3f,y,.7f,y);} + r[50043]=r[50003]; // Configurations: one part shown as three stacked variants with a selected front. {auto& configs=r[44080];rect(configs,.34f,.14f,.52f,.4f);poly(configs,{{.24f,.62f},{.24f,.24f},{.34f,.24f}});poly(configs,{{.14f,.72f},{.14f,.34f},{.24f,.34f}}); poly(configs,{{.14f,.72f},{.14f,.86f},{.66f,.86f},{.66f,.54f}});check(configs,.6f,.34f,.22f);} diff --git a/src/view/geometry_authoring.inl b/src/view/geometry_authoring.inl index d2d6169..8a15842 100644 --- a/src/view/geometry_authoring.inl +++ b/src/view/geometry_authoring.inl @@ -2,9 +2,17 @@ static void helixDialog(){ using V=arkjson::Value;const u64 revision=g_session.revision,epoch=g_documentEpoch;std::vector fields{{"Curve name","Helix"},{"Radius / expression","20"},{"Pitch per turn / mm","10"},{"Turns / expression","3"},{"Start angle / degrees","0"},{"Origin XYZ","[0,0,0]"},{"Axis XYZ","[0,0,1]"},{"Radial X axis XYZ","[1,0,0]"},{"Handedness +1 or -1","1"}};if(!editFields("Helix curve","An editable spatial helix can drive a sweep or be used as a reference curve. Dimensions remain source expressions.",fields))return;V spec=V::makeObj(),command=V::makeObj();spec.set("op",V::makeStr("helix"));const char* scalar[]={"radius","pitch","turns","start_angle"};for(int i=0;i<4;++i)spec.set(scalar[i],V::makeStr(trimField(fields[(size_t)i+1].value)));spec.set("origin",frameFormTriple(fields[5].value));spec.set("axis",frameFormTriple(fields[6].value));spec.set("x_axis",frameFormTriple(fields[7].value));spec.set("handedness",V::makeNum(formNumber(fields[8].value)));command.set("op",V::makeStr("feature.add"));command.set("type",V::makeStr("curve"));command.set("name",V::makeStr(fields[0].value));command.set("native",spec);applyUiCommandAtRevision(command,revision,epoch);if(!g_error){selBody=(int)g_bodyIds.size()-1;frameScene();} } static void loftControlDialog(){ - using V=arkjson::Value;auto* source=selectedPartFeature();if(!source||source->type!=FeatureType::Loft)throw std::runtime_error("Select a loft feature to edit section alignment and guide controls");const Feature snapshot=*source;const u64 revision=g_session.revision,epoch=g_documentEpoch;auto* sections=snapshot.nativeSpec.find("sections");if(!sections||sections->t!=V::Arr)throw std::runtime_error("Loft has no section source list");V controls=V::makeObj(),alignment=V::makeArr();if(auto* existing=snapshot.nativeSpec.find("controls"))controls=*existing;if(auto* existing=controls.find("section_alignment"))alignment=*existing;else for(const auto& section:sections->arr){(void)section;V item=V::makeObj();item.set("reverse",V::makeBool(false));item.set("seam_edge",V::makeNum(0));item.set("seam_angle",V::makeNum(0));alignment.arr.push_back(item);} - std::vector fields{{"Ordered section sketches",joinedSketchList(sections)},{"Guide sketches / curves (semicolon list)",joinedSketchList(snapshot.nativeSpec.find("guides"))},{"Section alignment JSON",alignment.dump()},{"Guide verification samples",spatialField(controls,"guide_samples","17")},{"Maximum observed guide deviation / mm",spatialField(controls,"max_guide_deviation_mm","0.05")},{"Require ordered guide contacts","1",true},{"Maximum degree",snapshot.get("max_degree","8")},{"Continuity / 0, 1 or 2",snapshot.get("continuity","1")}}; - if(!editFields("Loft section and guide controls","One alignment row per section: reverse, seam_edge (closed multi-edge sections) and seam_angle degrees (single circles). Guide deviation is a sampled fit check; it does not relax geometry tolerances.",fields))return;V native=snapshot.nativeSpec,newSections=V::makeArr(),guides=V::makeArr();auto names=[&](const std::string& text,V& list,bool section){std::istringstream tokens(text);std::string name;while(std::getline(tokens,name,';'))if(!(name=trimField(name)).empty()){if(section&&!g_doc.findSketch(name)&&std::none_of(g_doc.planes.begin(),g_doc.planes.end(),[&](const auto& plane){return plane.name==name;}))throw std::runtime_error("Unknown section: "+name);list.arr.push_back(V::makeStr(name));}};names(fields[0].value,newSections,true);names(fields[1].value,guides,false);if(!arkjson::parse(fields[2].value,alignment)||alignment.t!=V::Arr||alignment.arr.size()!=newSections.arr.size())throw std::runtime_error("Alignment JSON needs exactly one row per section");controls.set("section_alignment",alignment);controls.set("guide_samples",V::makeNum(formNumber(fields[3].value)));controls.set("max_guide_deviation_mm",V::makeNum(formNumber(fields[4].value)));controls.set("require_ordered_contacts",V::makeBool(fields[5].value=="1"));native.set("sections",newSections);native.set("guides",guides);native.set("controls",controls);V p=V::makeObj(),command=V::makeObj();p.set("max_degree",V::makeStr(fields[6].value));p.set("continuity",V::makeStr(fields[7].value));command.set("op",V::makeStr("feature.edit"));command.set("id",V::makeNum((double)snapshot.id));command.set("native",native);command.set("p",p);applyUiCommandAtRevision(command,revision,epoch); + using V=arkjson::Value;using namespace surface_network_view_068b;const auto* source=selectedPartFeature();if(!source||source->type!=FeatureType::Loft)throw std::runtime_error("Select a loft to edit section direction and seams");const Feature snapshot=*source;const auto revision=g_session.revision,epoch=g_documentEpoch; + const auto& previous=field(snapshot.nativeSpec,"sections");if(previous.t!=V::Arr)throw std::runtime_error("Loft has no ordered sections");V controls=field(snapshot.nativeSpec,"controls");if(controls.isNull())controls=V::makeObj();const auto oldAlignment=field(controls,"section_alignment"); + std::vector form{{"Sections / ordered ; names",joinedSketchList(&previous)},{"Guides / optional ; names",joinedSketchList(snapshot.nativeSpec.find("guides"))},{"Edit direction and seam per section","1",true},{"Guide checkpoints",spatialField(controls,"guide_samples","17")},{"Maximum guide deviation / mm",spatialField(controls,"max_guide_deviation_mm","0.05")},{"Require ordered guide contacts",field(controls,"require_ordered_contacts").t==V::Bool&&!field(controls,"require_ordered_contacts").b?"0":"1",true},{"Maximum degree",snapshot.get("max_degree","8")},{"Continuity / 0, 1 or 2",snapshot.get("continuity","1")}}; + if(!editFields("Loft section correspondence","Reorder the section names explicitly. Direction, seam edge and circular seam angle are edited in typed section forms.",form,false,"Review sections"))return; + if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Document changed while editing loft");const auto sectionNames=names(form[0].value),guideNames=names(form[1].value);if(sectionNames.size()<2||sectionNames.size()>32||guideNames.size()>8)throw std::runtime_error("Loft requires 2..32 sections and at most 8 guides");surface_workflow_059c::Context sourceContext(&snapshot);std::vector validatedInputs;const auto validatedSections=surface_workflow_059c::profiles(sourceContext,form[0].value,false,validatedInputs);const auto validatedGuides=surface_workflow_059c::profiles(sourceContext,form[1].value,true,validatedInputs);V alignment=V::makeArr(); + for(const auto& section:sectionNames){V row=V::makeObj();row.set("reverse",V::makeBool(false));row.set("seam_edge",V::makeNum(0));row.set("seam_angle",V::makeNum(0));for(size_t i=0;i fields{{"Reverse direction",field(row,"reverse").b?"1":"0",true},{"Seam edge (closed)",spatialField(row,"seam_edge","0")},{"Circle seam / deg",spatialField(row,"seam_angle","0")}};const auto title="Loft section / "+section;if(!editFields(title.c_str(),"Open curves use seam edge 0. Seam angle applies only to a single closed analytic circle. No alignment is guessed.",fields))return;const double edge=formNumber(fields[1].value);if(edge<0||edge>127||edge!=std::floor(edge))throw std::runtime_error("Seam edge must be an integer from 0 to 127");row.set("reverse",V::makeBool(fields[0].value=="1"));if(fields[1].value!=spatialField(row,"seam_edge","0"))row.set("seam_edge",V::makeStr(trimField(fields[1].value)));formNumber(fields[2].value);if(fields[2].value!=spatialField(row,"seam_angle","0"))row.set("seam_angle",V::makeStr(trimField(fields[2].value)));}alignment.arr.push_back(row); + } + controls.set("section_alignment",alignment);for(const auto* key:{"guide_samples","max_guide_deviation_mm","require_ordered_contacts"})controls.obj.erase(std::remove_if(controls.obj.begin(),controls.obj.end(),[&](const auto& p){return p.first==key;}),controls.obj.end());if(!guideNames.empty()){const double sample=formNumber(form[3].value),error=formNumber(form[4].value);if(sample<2||sample>129||sample!=std::floor(sample)||error<1e-6||error>.05)throw std::runtime_error("Guide checks require 2..129 samples and error 1e-6..0.05 mm");controls.set("guide_samples",V::makeNum(sample));controls.set("max_guide_deviation_mm",V::makeNum(error));controls.set("require_ordered_contacts",V::makeBool(form[5].value=="1"));} + V native=snapshot.nativeSpec;native.set("sections",validatedSections);native.set("controls",controls);if(guideNames.empty())native.obj.erase(std::remove_if(native.obj.begin(),native.obj.end(),[](const auto& p){return p.first=="guides";}),native.obj.end());else native.set("guides",validatedGuides);V diagnostic=V::makeObj();diagnostic.set("id",V::makeNum((double)snapshot.id));diagnostic.set("sections",validatedSections);diagnostic.set("guides",validatedGuides);diagnostic.set("controls",controls);if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Document changed before loft preflight");const auto measured=diagnose(diagnostic);std::vector report{{"Correspondence evidence",diagnosticsText(measured)}};if(!editFields("Loft preflight","Review any topology or direction warnings. Continue evaluates the complete loft and guides as an uncommitted candidate.",report,true,"Preview",nullptr,true))return; + if(revision!=g_session.revision||epoch!=g_documentEpoch)throw std::runtime_error("Document changed during loft review");const double degree=formNumber(form[6].value),continuity=formNumber(form[7].value);if(degree<1||degree>8||degree!=std::floor(degree)||continuity<0||continuity>2||continuity!=std::floor(continuity))throw std::runtime_error("Degree must be 1..8 and continuity 0, 1 or 2");V parameters=V::makeObj();parameters.set("max_degree",V::makeStr(form[6].value));parameters.set("continuity",V::makeStr(form[7].value));V command=V::makeObj(),inputs=V::makeArr();command.set("op",V::makeStr("feature.edit"));command.set("id",V::makeNum((double)snapshot.id));command.set("p",parameters);command.set("native",native);for(auto id:validatedInputs)inputs.arr.push_back(V::makeNum((double)id));command.set("inputs",inputs);V commands=V::makeArr();commands.arr.push_back(command);V request=V::makeObj();request.set("commands",commands);request.set("expected_revision",V::makeNum((double)revision));request.set("detail",V::makeStr("changes"));const auto prepared=runTool("doc_preview",request);if(g_error)return;if(reviewCandidate(field(prepared,"structuredContent"),"Loft / exact preview",revision,epoch))g_status="Loft correspondence saved / native guide validation passed"; } static void selectTangentFaces(){ using V=arkjson::Value;auto selected=std::find_if(g_picked.rbegin(),g_picked.rend(),[](const SelectionItem& item){return item.kind=="face"&&item.feature;});if(selected==g_picked.rend())throw std::runtime_error("Select an exact named face before expanding its tangent patch");const SelectionItem seed=*selected;const u64 revision=g_session.revision,epoch=g_documentEpoch;int body=-1;for(size_t i=0;i