From 18eb4f84599ad4d84ec528ce69cb61a7ca835177 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Tue, 24 Nov 2026 23:49:18 +0800 Subject: [PATCH] Organize the MCP tool code by place and the Design commands by heading Each place an agent finds commands under (Objects, Plates, View and windows and so on) now has one source file under Mcp/Tools/, and the Design tab's commands have one file per Design heading, so a developer finds a command where tool_list lists it and adds a new one beside its neighbours. A unit test fails when a command is added in another place's file. No change to what agents or people see: the command catalog is byte-identical. --- .github/workflows/check_operation_calls.yml | 4 +- docs/CAD/design/SKETCHER_TOOL_ARCHITECTURE.md | 6 +- docs/HLSD/design-tab.md | 4 +- docs/HLSD/mcp-server.md | 69 +- docs/HLSD/mcp-tools.md | 11 +- localization/i18n/list.txt | 38 +- scripts/CAD/README.md | 4 +- scripts/CAD/gen_offer_table.py | 2 +- scripts/CAD/tool_atlas.json | 2 +- scripts/check_operation_calls.py | 23 +- scripts/operation_calls_baseline.txt | 39 +- src/slic3r/CMakeLists.txt | 43 +- src/slic3r/GUI/ActionRegistry.cpp | 2 +- src/slic3r/GUI/CAD/DesignOffer.hpp | 2 +- src/slic3r/GUI/CAD/DesignPanel.cpp | 2 +- src/slic3r/GUI/CAD/DesignPanel.hpp | 4 +- src/slic3r/GUI/CommandCatalog.hpp | 2 +- src/slic3r/GUI/Mcp/McpTools.hpp | 426 +- src/slic3r/GUI/Mcp/McpToolsActions.cpp | 298 - src/slic3r/GUI/Mcp/McpToolsCad.cpp | 6191 ----------------- .../{McpToolsCad.hpp => McpToolsDesign.hpp} | 73 +- src/slic3r/GUI/Mcp/McpToolsGizmos.cpp | 451 -- src/slic3r/GUI/Mcp/McpToolsLayers.cpp | 688 -- src/slic3r/GUI/Mcp/McpToolsPreferences.cpp | 238 - src/slic3r/GUI/Mcp/McpToolsPrinter.cpp | 230 - src/slic3r/GUI/Mcp/McpToolsProject.cpp | 1030 --- src/slic3r/GUI/Mcp/McpToolsPython.cpp | 506 -- src/slic3r/GUI/Mcp/McpToolsRecord.cpp | 454 -- src/slic3r/GUI/Mcp/McpToolsReplay.cpp | 217 - .../{McpToolsApp.cpp => Tools/AppTools.cpp} | 345 +- .../CatalogTools.cpp} | 264 +- src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp | 172 + src/slic3r/GUI/Mcp/Tools/DesignCommon.hpp | 192 + .../GUI/Mcp/Tools/DesignConstructTools.cpp | 316 + .../GUI/Mcp/Tools/DesignHistoryTools.cpp | 1159 +++ .../GUI/Mcp/Tools/DesignInspectTools.cpp | 599 ++ .../GUI/Mcp/Tools/DesignSketchTools.cpp | 1708 +++++ src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp | 1167 ++++ .../GUI/Mcp/Tools/DesignSurfaceTools.cpp | 126 + src/slic3r/GUI/Mcp/Tools/DesignTools.cpp | 1287 ++++ src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp | 531 ++ .../{McpToolsUi.cpp => Tools/GuiTools.cpp} | 388 +- .../ObjectTools.cpp} | 1008 ++- src/slic3r/GUI/Mcp/Tools/PlateTools.cpp | 2102 ++++++ .../PluginTools.cpp} | 7 +- .../PresetTools.cpp} | 1227 +--- .../PrinterTools.cpp} | 292 +- src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp | 589 ++ src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp | 1313 ++++ .../ToolsCommon.cpp} | 64 +- .../{McpToolsView.cpp => Tools/ViewTools.cpp} | 752 +- src/slic3r/GUI/Mcp/UiInspector.cpp | 2 +- src/slic3r/GUI/NativeCommands.cpp | 49 +- src/slic3r/GUI/NativeCommands.hpp | 8 +- tests/libslic3r/test_caddocument.cpp | 2 +- tests/slic3rutils/test_command_catalog.cpp | 45 + tests/slic3rutils/test_mcp_cad.cpp | 44 +- tests/slic3rutils/test_operations.cpp | 2 +- tools/mcp/test-entries/commands.md | 4 +- tools/mcp/test-entries/files.md | 2 +- tools/mcp/test-entries/gui_tools.md | 6 +- tools/mcp/test-entries/objects.md | 8 +- tools/mcp/test-entries/slice_preview.md | 8 +- tools/mcp/test-entries/windows_web.md | 2 +- 64 files changed, 13719 insertions(+), 13130 deletions(-) delete mode 100644 src/slic3r/GUI/Mcp/McpToolsActions.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsCad.cpp rename src/slic3r/GUI/Mcp/{McpToolsCad.hpp => McpToolsDesign.hpp} (91%) delete mode 100644 src/slic3r/GUI/Mcp/McpToolsGizmos.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsLayers.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsPreferences.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsPrinter.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsProject.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsPython.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsRecord.cpp delete mode 100644 src/slic3r/GUI/Mcp/McpToolsReplay.cpp rename src/slic3r/GUI/Mcp/{McpToolsApp.cpp => Tools/AppTools.cpp} (63%) rename src/slic3r/GUI/Mcp/{McpToolsApi.cpp => Tools/CatalogTools.cpp} (72%) create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignCommon.hpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/DesignTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp rename src/slic3r/GUI/Mcp/{McpToolsUi.cpp => Tools/GuiTools.cpp} (84%) rename src/slic3r/GUI/Mcp/{McpToolsScene.cpp => Tools/ObjectTools.cpp} (79%) create mode 100644 src/slic3r/GUI/Mcp/Tools/PlateTools.cpp rename src/slic3r/GUI/Mcp/{McpToolsPlugins.cpp => Tools/PluginTools.cpp} (99%) rename src/slic3r/GUI/Mcp/{McpToolsConfig.cpp => Tools/PresetTools.cpp} (67%) rename src/slic3r/GUI/Mcp/{McpToolsInstall.cpp => Tools/PrinterTools.cpp} (51%) create mode 100644 src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp create mode 100644 src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp rename src/slic3r/GUI/Mcp/{McpToolsCommon.cpp => Tools/ToolsCommon.cpp} (90%) rename src/slic3r/GUI/Mcp/{McpToolsView.cpp => Tools/ViewTools.cpp} (72%) diff --git a/.github/workflows/check_operation_calls.yml b/.github/workflows/check_operation_calls.yml index 9a7c1d5b29..543e8c542c 100644 --- a/.github/workflows/check_operation_calls.yml +++ b/.github/workflows/check_operation_calls.yml @@ -7,7 +7,7 @@ on: push: paths: - 'src/slic3r/GUI/NativeCommands.cpp' - - 'src/slic3r/GUI/Mcp/McpTools*.cpp' + - 'src/slic3r/GUI/Mcp/Tools/*.cpp' - 'src/slic3r/plugin/host/*.cpp' - 'scripts/check_operation_calls.py' - 'scripts/operation_calls_baseline.txt' @@ -15,7 +15,7 @@ on: pull_request: paths: - 'src/slic3r/GUI/NativeCommands.cpp' - - 'src/slic3r/GUI/Mcp/McpTools*.cpp' + - 'src/slic3r/GUI/Mcp/Tools/*.cpp' - 'src/slic3r/plugin/host/*.cpp' - 'scripts/check_operation_calls.py' - 'scripts/operation_calls_baseline.txt' diff --git a/docs/CAD/design/SKETCHER_TOOL_ARCHITECTURE.md b/docs/CAD/design/SKETCHER_TOOL_ARCHITECTURE.md index 79df661562..666df8d955 100644 --- a/docs/CAD/design/SKETCHER_TOOL_ARCHITECTURE.md +++ b/docs/CAD/design/SKETCHER_TOOL_ARCHITECTURE.md @@ -306,7 +306,7 @@ codebase. Current state, verified: **"Measure (no GUI route)"** and is permanently disabled (`DesignPanel.cpp:6519`). With no refusal in the row, it contributes nothing to the family's "why" line either. - The maths exists, for MCP callers only: the `measure` CAD tool (`cad_measure` in - `Mcp/McpToolsCad.cpp`) — refs `{face|edge|point}`, distance = `|pa - pb|` of **representative + `Mcp/Tools/DesignInspectTools.cpp`) — refs `{face|edge|point}`, distance = `|pa - pb|` of **representative points** (face centroid, edge mid-sample), angle = `acos(da·db)` when both refs carry a direction. - The correct OCCT primitive is already linked and already used: `BRepExtrema_DistShapeShape` (`GeometryEngine.cpp:31`, `:457`). @@ -444,7 +444,7 @@ thresholds move nothing for `v <= 0` (Length/Diameter/Radius, `:611-613`) or `v solver as a constraint it must satisfy and cannot, silently corrupting the sketch. So a guard at the top of `apply_dimension` refuses a value that is not finite, not above zero for a length, radius or diameter, or negative for a distance, and says why on the status line, before it moves or records -anything. The `sketch_set_value` CAD tool (`Mcp/McpToolsCad.cpp`) checks the same rule, and refuses a +anything. The `sketch_set_value` CAD tool (`Mcp/Tools/DesignSketchTools.cpp`) checks the same rule, and refuses a selection with nothing to dimension, before it calls `apply_dimension`, so that its call fails with the reason rather than reporting a value the sketch tool refused only on its status line. The GUI and the agent surface are equally safe callers of the function. @@ -529,7 +529,7 @@ Three rules the type enforces, each closing a defect above: from §0.2) — the same type for the solver path, the geometric path and the MCP server. The range guard `apply_dimension` runs becomes `apply`'s `Refused`, so every caller learns of a refusal from the result rather than from the status line, and `sketch_set_value` in - `Mcp/McpToolsCad.cpp` keeps no copy of the check. `Refused` keeps the field open with the typed + `Mcp/Tools/DesignSketchTools.cpp` keeps no copy of the check. `Refused` keeps the field open with the typed text and the reason, which is also what makes the `Coincident`-flip reversible: the dimension keeps its `type` and only its value changes. 3. **One dimension per (type, operand pair) lives in one `std::vector`**, and the diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 07bb72ab72..60ba9aec2c 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -412,7 +412,7 @@ takes no place on the favourites bar meanwhile. A folded item's action runs its arguments. A call whose arguments are exactly those that choose an item (none for an entry's own item) does what the menu item does, only in the mode the item belongs to, and replies `{"interactive": true, ...}` with what the tab shows then (its busy reason and status line); with other arguments, or `silent: true`, the -commands (`Mcp/McpToolsCad.*`) describe the design, read topology, measure, and run the same verbs the offer +commands (`Mcp/McpToolsDesign.hpp`, `Mcp/Tools/Design*.cpp`) describe the design, read topology, measure, and run the same verbs the offer does — they re-implement nothing, so a scripted action and a clicked one cannot diverge. Where a GUI action is bound to a selection, a card or a dialog, its work is split into a function both callers share, and the command calls that function with explicit arguments instead of driving the widgets. The command set, what each command @@ -544,7 +544,7 @@ and replay tests. | `src/slic3r/GUI/CAD/DesignRowList.*` | the Feature tree and Bodies lists, with per-row actions | | `src/slic3r/GUI/CAD/DesignCanvas.*` | viewport integration | | `src/slic3r/GUI/CAD/DesignSketchTool.*` | in-canvas sketching | -| `src/slic3r/GUI/Mcp/McpToolsCad.*` | the automation surface: the Design commands made from the table, their silent forms (`kSilentForms`) and their gate | +| `src/slic3r/GUI/Mcp/McpToolsDesign.hpp`, `src/slic3r/GUI/Mcp/Tools/Design*.cpp` | the automation surface: the Design commands made from the table, their silent forms (`silent_forms()`) and their gate; `DesignTools.cpp` holds the gate, the registration and the Document heading's commands, and each other heading's are in a file of its own (`DesignSketchTools.cpp`, `DesignSolidTools.cpp` and so on) | | `src/slic3r/GUI/CAD/DesignInteraction.hpp` | the Esc level contract | | `src/slic3r/GUI/CAD/DesignOffer.hpp` | the generated table: the offer, the Speed Dial actions and the commands | | `scripts/CAD/tool_atlas.json` | source of truth for the table | diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 6af7600a02..be9ff16c9a 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -612,8 +612,8 @@ A check only one route makes stays with that route, as a step of its own before changes a setting of the app), or it calls the undo and redo of a history (`undo`, `redo`). An entry that names operations fails the test, so a new command has to say which it is. - `scripts/check_operation_calls.py`, run by the `Check operation calls` workflow, bans in the callers' files - (`NativeCommands.cpp`, the `McpTools*.cpp` files but the Design commands' `McpToolsCad.cpp`, - `plugin/host/*.cpp`) the owner methods the operations call, by name. A banned call that stays, because + (`NativeCommands.cpp`, the places' files `Mcp/Tools/*.cpp`, `plugin/host/*.cpp`; not the Design commands' + `Mcp/Tools/Design*.cpp`) the owner methods the operations call, by name. A banned call that stays, because another function uses the same owner method or the caller is an asking path, is listed in `scripts/operation_calls_baseline.txt` by file and exact source line, under its reason. The check fails on a banned call that is not listed and on a listed line the source no longer has. @@ -631,15 +631,14 @@ arguments is `listed`, so `tools/list` shows it. The menu items that take no arg lists them with the Design tab's commands and the operations plugins offer, and `tool_call` runs them all. The commands are the process's command catalog (`CommandCatalog`, `NativeCommands::instance()`). Startup -builds it, with no automation runtime: `register_all_commands()` gathers each family of commands in a fixed -order of calls (app, api, project, config, preference, install, scene, layer, view, plugin, replay, python, -record, action, ui), each through its `register_*_tools(catalog)` in its `McpTools*.cpp`, gives each the -group of its place (`NativeCommands::place_heading()`, which reads the name's first word; a name with no -place throws), and sorts them stably by place: `tool_list`, `tool_describe`, `tool_call` and `app_state` -first, as what an -agent starts with, then the places in the order above, each place's commands in their families' order. The +builds it, with no automation runtime: `register_all_commands()` gathers each place's commands through the +`register__tools(catalog)` of its file, `Mcp/Tools/Tools.cpp` (Objects and Parts share +`ObjectTools.cpp`), gives each the group of its place (`NativeCommands::place_heading()`, which reads the +name's first word; a name with no place throws), and sorts them stably by place: `tool_list`, +`tool_describe`, `tool_call` and `app_state` first, as what an agent starts with, then the places in the order +mcp-tools.md lists them, each place's commands in the order its file adds them. The Design tab's commands come before Driving the GUI, in a CAD build with the CAD feature on -(`register_cad_commands()`; see Design tab), and the source of the operations plugins offer is added beside +(`register_design_tools()`; see Design tab), and the source of the operations plugins offer is added beside them. A command is made with `inspect_tool()`, `mutate_tool()`, `record_tool()` or `recover_input_tool()`, which build it through `long_command()` with its function unchanged, so it runs where its call does, or, for one made from menu items, with `menu_command()`, which builds it through `ui_command()` with the items as its @@ -805,7 +804,11 @@ and `tool_list` a command, since the name may be a command's that has no action; command. For a Design tab action that is not shown it says when the action is there instead, and that `tool_call` runs its command from any tab, or, when the catalog leaves its command out, why. -Each tool family lives in its own `McpTools*.cpp`. List tools take `limit` and `offset` and reply +Each place's commands live in its own file under `Mcp/Tools/`, with the helpers only they use; a helper +another place's commands use too is declared in `McpTools.hpp`, and the schema and handler helpers every place +uses are in `ToolsCommon.cpp`. The Design commands, made from the Design table, are the one place in several +files, one per Design heading: `DesignTools.cpp` (with the gate and the registration), `DesignSketchTools.cpp`, +`DesignSolidTools.cpp` and so on, which share their helpers through `DesignCommon.hpp`. List tools take `limit` and `offset` and reply `{items, offset, total}` (`page()`; `object_list`, a tree, has `plates` and `outside` in place of `items`), with `next_offset` while more remain: `action_list` too. The server instructions give that shape once, rather than every description, and each `limit` states its default. A default is what an agent @@ -830,7 +833,7 @@ narrow conversion would use the ANSI code page. `object_list` lays the model out as the Objects panel does: `plates`, each `{index, name, objects}` with the objects that have an instance on it, then `outside`, the objects with an instance on no -plate. `objects_by_plate()` builds it from `object_info()` and `volume_info()` (McpToolsScene.cpp, +plate. `objects_by_plate()` builds it from `object_info()` and `volume_info()` (ObjectTools.cpp, libslic3r only, so unit tests build them from a `Model`) and a callback that says which plate an instance is on. The handler's is `instance_plate()`: the plate registry's answer or, for an instance the registry does not hold, as Fill bed leaves its new ones, the first plate the instance stands on, @@ -1740,7 +1743,7 @@ plugin itself. ### Design tab: the Design commands The Design tab's sketches, features, reads and measurements, feature and body edits and its commit to the -plate are commands of the catalog (`Mcp/McpToolsCad.cpp`) in the group `Design`, not listed, so agents that +plate are commands of the catalog (`Mcp/Tools/Design*.cpp`) in the group `Design`, not listed, so agents that never open the Design tab pay in `tools/list` for their names alone. The command set itself, how the commands are named and what each takes, is in [mcp-tools.md](mcp-tools.md), The Design tab's commands. The names end `tool_list`'s description while the catalog holds the commands (`design_command_index()`): that they are the @@ -1755,10 +1758,10 @@ in the header), and a command's is its entry's `section`. So an agent learns fro commands exist, that they are CAD and where each works, and reads a command's manual only when it asks `tool_describe` for it. The description stays within 4096 characters, the most a client is known to keep of one. The commands that open a tool have Speed Dial actions while the Design tab is shown (see Speed Dial catalog). -`register_all_commands()` adds them through `register_cad_commands()` only +`register_all_commands()` adds them through `register_design_tools()` only when the catalog is built with the CAD feature on (`CatalogOptions::cad`, which startup takes in the editor from the value in force: the `enable_cad_feature` preference, or `--cad` for the run). With it off the catalog -holds none, and records that it leaves them out (`leave_out_cad_commands()`), a folded item's id among them, +holds none, and records that it leaves them out (`leave_out_design_tools()`), a folded item's id among them, which names a Speed Dial action: `tool_call {tool: "hole"}` is an unknown command whose error says the feature was off when OrcaSlicer started and how a person turns it on, and `app_state` carries `cad_note`, how a person turns the feature on (`cad_note()`, in the editor while the catalog holds no Design command or the feature is @@ -1829,12 +1832,12 @@ own or another mode than its command's item, two items of a command have the sam handlers, an item's arguments are its command's own, own `args` sit on an entry without a handler and a block or are `{}`, or a command has no `section` (and a folded or greyed item has one). -An entry with a tool block has a silent form, whose function `kSilentForms` binds by the entry's id; a unit +An entry with a tool block has a silent form, whose function `silent_forms()` binds by the entry's id; a unit test fails for a block with no function and a function with no block. The block gives the silent form's access, a summary of one sentence (at most 120 characters), details, typed params with units, defaults and limits, one to three examples and whether it reports a rejected rebuild in its reply (`ok_false`); the header -carries it as JSON text (`doc`). `register_cad_commands()` makes a -command of each entry that is one (`design_command()`, through `cad_command()`), in the table's order. It is +carries it as JSON text (`doc`). `register_design_tools()` makes a +command of each entry that is one (`table_command()`, through `design_command()`), in the table's order. It is `read_only` and `idempotent` for a `read` block, and has the entry's icon. Its description is the summary, the details, with `ok_false` how a rejected rebuild shows, and, for a command whose menu items a call's arguments choose, those argument sets each with its items' names (`opening_calls()`), so that the name a person knows @@ -1846,7 +1849,7 @@ a sketch" by its menu item. Its examples are the block's, each `{title, calls: [ with the command it documents, where an argument `{"from_call": i, "key": k}` is the value under `k` in the result of call `i`, and a call that gives nothing else of a command that opens a tool with no arguments is `{"silent": true}`. Its input -schema (`cad_input_schema()`) is built from the params: a type written `"a|b"` is the list of both, `min`, +schema (`design_input_schema()`) is built from the params: a type written `"a|b"` is the list of both, `min`, `exclusive_min` and `max` are `minimum`, `exclusiveMinimum` and `maximum`, `enum` and `default` carry over, the unit joins the description, and a param without a default is required. A param whose default is null is one its function reads as left out when it is null (no limit, the open sketch), so its type also admits null, @@ -1888,7 +1891,7 @@ choosing arguments. So a call meant to run that gives only an item's arguments o reply says so. A call that opens a tool, an agent's or a Speed Dial action's, is the person's form (`open_tool()`, on the -item's entry). It passes `cad_gate()` with `CadAccess::None`, whose only busy rule is the rebuild's, so the +item's entry). It passes `design_gate()` with `CadAccess::None`, whose only busy rule is the rebuild's, so the recipe is loaded and the call refused while the model is being rebuilt, and runs the item's handler in place (`DesignPanel::mcp_run_verb()`), as the menu item and the tab's keys do: an open card does not refuse it, since each tool decides what that means to it. Before the handler runs, `open_refusal()` refuses it in two cases @@ -1933,7 +1936,7 @@ An agent finds them as it finds any command `tools/list` does not show: `tool_li them, each with its heading and what it does, and `tool_describe {tool}` gives one's manual: its group, access labels, description, parameters, menu items and examples. `tool_call {tool, args}` runs one, its arguments validated against its schema, and replies with the tool's own reply, less an `"ok": true` and an empty `"error"`, -which say nothing a reply that is no error doesn't (`cad_command()`); an `ok` false and its `error`, a rejected +which say nothing a reply that is no error doesn't (`design_command()`); an `ok` false and its `error`, a rejected rebuild's, stay. A replay step calls one by its name or through `tool_call`, and `orca_mcp.py`'s `call_command()` from Python. An unknown name is answered as any unknown command is: with the closest key (`invalid_argument`), or, for a Design command's name @@ -1942,7 +1945,7 @@ was off at startup, and how a person turns it on; in the G-code viewer, which ha preference says, that a person opens the project in the editor (`CatalogOptions::editor`). A call runs its function on the UI thread: a person's pick in place, an automated call in one UI closure -under the mutate guard, then `settle()`. Before the silent form, `cad_gate()` refuses a call by its cause, in +under the mutate guard, then `settle()`. Before the silent form, `design_gate()` refuses a call by its cause, in this order. The MCP server is up before the main window, so first come `ui_plater()`'s "shutting down" and "still starting" refusals, as for any tool. Then, each `design_unavailable`, the G-code viewer, which has no Design tab; the CAD feature off (Preferences > Features); and a Design panel that cannot be built (no page was made @@ -1951,7 +1954,7 @@ panel is otherwise built on the first call, since in a headless session nobody c `app_state.design_tab` says whether this session has the page. Then come a busy Design tab (`design_busy`, whose `hint` says that `confirm_tool` keeps what is open when its Confirm is on and `cancel_tool` discards it, and that a rebuild ends by itself), and a `generation` that is not an integer of 0 or more (`invalid_argument`; -`cad_generation()` takes it stored signed too, as a script's Python integers arrive) or not the model's +`design_generation()` takes it stored signed too, as a script's Python integers arrive) or not the model's (`stale_ids`). Before the generation is read, the project's recipe is loaded into an empty document (`DesignPanel::hydrate_from_model()`), as showing the tab would. @@ -2272,16 +2275,16 @@ the Bodies row's Move and Place on Face: where the body goes for Commit to Plate no undo step, and the project file does not keep it; a placement follows its body when the bodies are renumbered, by the transient `uid` of the feature that made it (`CadFeature::uid`). -`undo` and `redo` are commands of The app, each with an action of its own (`McpToolsApp.cpp`), shared by the +`undo` and `redo` are commands of The app, each with an action of its own (`AppTools.cpp`), shared by the Design tab and the project, and act on the history of the tab shown, as Edit > Undo and Redo and the top bar's buttons do: the Design tab's while `MainFrame::shown_design_panel()` is not null, else the project's. `history`, `design` or `project`, names one for automation, which acts whatever tab is shown: a Design command runs with Prepare in front, so a replay that drives the Design tab from there would otherwise -undo a project change. The Design history's is `cad_undo_redo()`: Edit > Undo and Redo with the +undo a project change. The Design history's is `design_undo_redo()`: Edit > Undo and Redo with the Design tab shown (`menu_undo_redo()`, behind the same `menu_can_undo_redo()` gate), the Design history, or inside a sketch session the sketch's own, which takes off or puts back the last drawn -shape, past `cad_gate()` with sketch access, so it runs in a sketch session and is refused under an +shape, past `design_gate()` with sketch access, so it runs in a sketch session and is refused under an open card, Constrain mode or a pending body Move, and during a rebuild. A refusal is the call's error and never falls through to the other history. The project's is `Plater::undo()` and `redo()`, the Edit menu's, which step past the snapshots that do not modify the project to the nearest one that does and load it, and leave @@ -2296,7 +2299,7 @@ included: a person's pick from the Speed Dial does what the Edit menu's item doe that item it does nothing and shows nothing: on the Design tab's history through `menu_undo_redo()` where `menu_can_undo_redo()` allows, and on the project's only where `Plater::can_undo()` (or `can_redo()`) holds, so not from the Preview or while a job runs, since `Plater::undo()` itself acts wherever it is called. The reply is the action's, with `history` and, for the -Design tab's, `result`, `cad_undo_redo()`'s reply (its `scope` and what that scope holds); with the CAD feature off, or in a build without CAD, +Design tab's, `result`, `design_undo_redo()`'s reply (its `scope` and what that scope holds); with the CAD feature off, or in a build without CAD, `design` fails ("The CAD feature is off"). Their examples, which call Design commands, are only in a catalog that holds them. The Design history is not saved with a project. @@ -2436,7 +2439,7 @@ Design table with a handler that is offered in the tab's mode, in the table's or by `Mcp::offered_in_mode()`), while `MainFrame::shown_design_panel()` is not null and the CAD feature is on, and none otherwise, so the Speed Dial has the sketch's actions in an open sketch, the model's outside one, and no Design tab action on another tab, nor once the feature is turned off: the tab stays until the restart, but -`cad_gate()` would refuse every pick of its actions. A Design command with a handler of its own has its action +`design_gate()` would refuse every pick of its actions. A Design command with a handler of its own has its action under its key (`orca_command:sketch_trim:orca`); a menu item folded into a Design command keeps its action under the item's id (`orca_command:sk_array:orca`), one of the command's `actions`, with the item's title and icon, and a pick runs the command with the item's arguments, as `tool_call {"tool": "sketch_pattern", "args": @@ -2639,7 +2642,7 @@ done. ### Making a feature reachable A feature is a command, named for its place, then its verb (see [mcp-tools.md](mcp-tools.md)), -declared in the `McpTools*.cpp` of its place beside the commands of that place: +declared in its place's file (`Mcp/Tools/Tools.cpp`) beside the commands of that place: 1. Build it with `inspect_tool()` for pure observation, which runs inline, read-only and unjournaled, or with `mutate_tool()` for anything that changes the app, which runs as a journaled job under the mutate guard; @@ -3825,7 +3828,7 @@ recording counts as active until its file is closed, for the one-at-a-time rule `apply_recording_overrides()` with its defaults, the Balanced preset, and refuses `encode` without an ffmpeg before anything records. The encode deletes the `.mkv` once the MP4 is written unless `keep_raw_video_file` keeps it, as every encode does (see Encoding). The recording keeps `recording_encode`'s arguments (`RecordingOptions::encode`), and the `recording_stop` -that reports it, once its file is closed, starts the encode with `start_encode()` (`McpToolsRecord.cpp`): a job of +that reports it, once its file is closed, starts the encode with `start_encode()` (`RecordingTools.cpp`): a job of its own, outside the journal (a replayed `recording_start` asks for it again), whose envelope the report carries as `encode`, so the agent waits for the MP4 by that job's id. A recording that ended on its own is encoded when the next `recording_stop` reports it; one nothing reports, a client's that ended with @@ -4085,7 +4088,7 @@ taken, as by the replay that runs this one as a step in the same second, gets `- replay's `${replay_dir}` is its `out_dir`. The engine (`McpReplay.cpp`, wx-free) and the job around it (`run_replay_job()` in -`McpToolsReplay.cpp`) are shared by `replay_run`, `--run` and Action Replay. A run +`RecordingTools.cpp`) are shared by `replay_run`, `--run` and Action Replay. A run stops before its next step, and stops waiting on a step's job, once the runtime stops or a stop was asked for any job in its lineage (`JobRegistry::request_stop()`), so a nested `replay_run` stops with the run that holds it. Stop requests last the session, and `JobRegistry` records each job's ancestor @@ -4511,7 +4514,7 @@ dependencies as its first work starts. `run_python_code()` is a session with one with streaming, quoting, Cell events and cell results off and a stop closing every window of the run, which is how it keeps the run described above. -**The session job.** `start_python_session()` (`McpToolsPython.cpp`) hosts the panel's session as an unjournaled +**The session job.** `start_python_session()` (`RecordingTools.cpp`) hosts the panel's session as an unjournaled person's `script_run` job (`run_python_session_job()`), which the runtime follows (`follow()`) on a thread that `stop()` joins and `stop_followed()` stops. The job is idle for `app_wait {for: "idle"}` as any `script_run` job is, so agents' and plugins' runs overlap with it, sharing no state, tracebacks included. It owns what its calls leave behind for the @@ -4922,7 +4925,7 @@ replay, the setup a client copies, the stdio bridge and the token), which `libsl Its tests are in `tests/automation/`, run with `automation_tests` (the `test_mcp_*` cases are tagged `[Mcp]`, `test_command_catalog`'s `[CommandCatalog]`); that suite links the library and libslic3r and nothing of `libslic3r_gui`, so it builds without wx and the embedded Python. What -needs the GUI library (the runtime, the endpoint, the tool families, the process catalog `NativeCommands` +needs the GUI library (the runtime, the endpoint, the places' commands, the process catalog `NativeCommands` builds) is tested in `tests/slic3rutils/`: the `test_mcp_*.cpp` cases are tagged `[Mcp]`, and the other files named below carry tags of their own (`test_command_catalog` `[CommandCatalog]`, `test_operations` `[Operations]`, `test_imgui_wrapper` `[ImGuiWrapper]`), so diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index aa20db08c1..c7e4c750c6 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -20,8 +20,8 @@ The Design tab, OrcaSlicer's optional CAD component, adds 88 commands of its own on. They run on the same server and keep the same rule for menu items, but are named and grouped as CAD programs name theirs, so they have a section of their own at the end, The Design tab's commands. -Each place's commands are written in its family's file, `src/slic3r/GUI/Mcp/McpTools*.cpp`, and gathered by -`register_all_commands()`. A menu item's function is in namespace `MenuItems` (`NativeCommandMenuItems.hpp`), +Each place's commands are written in its own file, `src/slic3r/GUI/Mcp/Tools/Tools.cpp` (Objects and +Parts share `ObjectTools.cpp`), and gathered by `register_all_commands()`. A menu item's function is in namespace `MenuItems` (`NativeCommandMenuItems.hpp`), and what a command does that a dialog or another interface does too is an operation of `src/slic3r/GUI/Operations/`. What every command takes and replies is in its description and input schema, which `tools/list` gives a client and `tool_describe {tool}` gives for any command, as its manual. @@ -768,7 +768,10 @@ How the server holds them (the catalog with the CAD feature on, the gate) is in [design-tab.md](design-tab.md). One table defines them all: `scripts/CAD/tool_atlas.json`. `scripts/CAD/gen_offer_table.py` writes -`src/slic3r/GUI/CAD/DesignOffer.hpp` from it, and the commands' code is `src/slic3r/GUI/Mcp/McpToolsCad.cpp`. +`src/slic3r/GUI/CAD/DesignOffer.hpp` from it, and the commands' code is in `src/slic3r/GUI/Mcp/Tools/`: +one file per Design heading: `DesignTools.cpp` (the gate, the registration and the Document heading), +`DesignSketchTools.cpp`, `DesignSolidTools.cpp`, `DesignSurfaceTools.cpp`, `DesignConstructTools.cpp`, +`DesignInspectTools.cpp`, `DesignBodyTools.cpp` and `DesignHistoryTools.cpp`. What every command takes and replies is in its entry's tool block, which the agent reads through `tool_describe {tool}`; `tests/data/command_catalog.json` holds every command's schema, actions and examples as an agent sees them. @@ -1079,7 +1082,7 @@ nothing, or names an object whose kind or geometry the operation does not take), right but the state is not: no body yet, a body hidden, no sketch open, a tool open), `rebuild_failed`, `kernel_failure`, `export_failed`, or one of the gate's (`design_unavailable`, `design_busy`, `stale_ids`) and the menu items' (`wrong_mode`, `wrong_selection`), and `no_silent_form` for an entry with no silent form called as one -(only by `run_cad_tool()` called directly); the server's design (mcp-server.md) draws the line between geometry and +(only by `run_design_tool()` called directly); the server's design (mcp-server.md) draws the line between geometry and state. It leaves the design as it was, so `replay_export` leaves it out. That holds for argument errors and for a rebuild the engine rejects alike. Twenty-one commands instead report a rejected rebuild in their reply, `ok` false or `error` not empty, after the same rollback, diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index 542099a79a..0f105ed8b5 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -155,24 +155,26 @@ src/slic3r/GUI/ConnectPrinter.cpp src/slic3r/GUI/HMSPanel.cpp src/slic3r/GUI/MainFrame.cpp src/slic3r/GUI/Mcp/McpPersonContext.cpp -src/slic3r/GUI/Mcp/McpToolsActions.cpp -src/slic3r/GUI/Mcp/McpToolsApi.cpp -src/slic3r/GUI/Mcp/McpToolsApp.cpp -src/slic3r/GUI/Mcp/McpToolsCad.cpp -src/slic3r/GUI/Mcp/McpToolsConfig.cpp -src/slic3r/GUI/Mcp/McpToolsGizmos.cpp -src/slic3r/GUI/Mcp/McpToolsInstall.cpp -src/slic3r/GUI/Mcp/McpToolsLayers.cpp -src/slic3r/GUI/Mcp/McpToolsPlugins.cpp -src/slic3r/GUI/Mcp/McpToolsPreferences.cpp -src/slic3r/GUI/Mcp/McpToolsPrinter.cpp -src/slic3r/GUI/Mcp/McpToolsProject.cpp -src/slic3r/GUI/Mcp/McpToolsPython.cpp -src/slic3r/GUI/Mcp/McpToolsRecord.cpp -src/slic3r/GUI/Mcp/McpToolsReplay.cpp -src/slic3r/GUI/Mcp/McpToolsScene.cpp -src/slic3r/GUI/Mcp/McpToolsUi.cpp -src/slic3r/GUI/Mcp/McpToolsView.cpp +src/slic3r/GUI/Mcp/Tools/AppTools.cpp +src/slic3r/GUI/Mcp/Tools/CatalogTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp +src/slic3r/GUI/Mcp/Tools/DesignTools.cpp +src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp +src/slic3r/GUI/Mcp/Tools/GuiTools.cpp +src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp +src/slic3r/GUI/Mcp/Tools/PlateTools.cpp +src/slic3r/GUI/Mcp/Tools/PluginTools.cpp +src/slic3r/GUI/Mcp/Tools/PresetTools.cpp +src/slic3r/GUI/Mcp/Tools/PrinterTools.cpp +src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp +src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp +src/slic3r/GUI/Mcp/Tools/ViewTools.cpp src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp src/slic3r/GUI/Mcp/RecordingSettings.cpp src/slic3r/GUI/RecordingDialog.cpp diff --git a/scripts/CAD/README.md b/scripts/CAD/README.md index 4bfa107ad4..0d907dd55b 100644 --- a/scripts/CAD/README.md +++ b/scripts/CAD/README.md @@ -62,8 +62,8 @@ in its reply), a `summary` of one sentence, null, unless `nullable` is false, which marks a param whose function reads a null as given), one to three `examples` and `ids` (it takes or gives face and edge ids). Entries with no `slot` and no handler are commands only, and -`modal` marks a verb whose handler opens a dialog. `src/slic3r/GUI/Mcp/McpToolsCad.cpp` binds each block -to the function that runs it (`kSilentForms`), and a unit test fails when a block has no function or a +`modal` marks a verb whose handler opens a dialog. `src/slic3r/GUI/Mcp/Tools/Design*.cpp` bind each block +to the function that runs it (`silent_forms()`), and a unit test fails when a block has no function or a function no block. The generator refuses an entry with neither a handler nor a block, but `align`. `python3 scripts/CAD/gen_offer_table.py` rewrites the header and `--check` proves the diff --git a/scripts/CAD/gen_offer_table.py b/scripts/CAD/gen_offer_table.py index 1076655cdf..38c63ae599 100644 --- a/scripts/CAD/gen_offer_table.py +++ b/scripts/CAD/gen_offer_table.py @@ -243,7 +243,7 @@ def main(): "// not apply are shown disabled in place with their reason rather than removed. Row order was", "// ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory.", "// An entry with a handler or a tool block, and no fold_into, is a command of the catalog's group Design", - "// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_list's index. A", + "// (Mcp::register_design_tools(), Mcp::is_design_command()), under its section in tool_list's index. A", "// call whose arguments are exactly those that choose one of its items opens that item's tool for a person", "// (Mcp::opened_item()): none choose the entry's own item where it has a handler, else the items folded into it", "// with {}; a folded item's args, or the entry's own, choose that item. Any other call runs its tool block's", diff --git a/scripts/CAD/tool_atlas.json b/scripts/CAD/tool_atlas.json index ce8469c6e5..a5ac725a67 100644 --- a/scripts/CAD/tool_atlas.json +++ b/scripts/CAD/tool_atlas.json @@ -8,7 +8,7 @@ " call sites at 524/662/734/790/874/904, sk_key table at 369-400, m_keys_feature)", " kernel coverage -> src/libslic3r/CAD/CadDocument.hpp (enum CadFeatureType)", " Design commands -> a verb's `tool` block, and the entries with no slot (commands only):", - " the silent form's access, params and examples; McpToolsCad.cpp binds each block to its function", + " the silent form's access, params and examples; Mcp/Tools/Design*.cpp bind each block to its function", " selection kinds -> src/slic3r/GUI/CAD/DesignCanvas.hpp (the on_*_selected callbacks)", "gen_offer_table.py emits src/slic3r/GUI/CAD/DesignOffer.hpp from this file, so the map", "exists once. Edit the atlas and regenerate; never hand-edit the header." diff --git a/scripts/check_operation_calls.py b/scripts/check_operation_calls.py index 252f971d56..1b7f9eb11c 100644 --- a/scripts/check_operation_calls.py +++ b/scripts/check_operation_calls.py @@ -27,10 +27,10 @@ import sys REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASELINE = "scripts/operation_calls_baseline.txt" -# The callers: the command runners, the tools (the Design commands, whose functions are the Design tab's own -# entry points, are not among them) and the plugin API. -CALLERS = ["src/slic3r/GUI/NativeCommands.cpp", "src/slic3r/GUI/Mcp/McpTools*.cpp", "src/slic3r/plugin/host/*.cpp"] -NOT_CALLERS = {"src/slic3r/GUI/Mcp/McpToolsCad.cpp"} +# The callers: the command runners, the tools of every place and the plugin API. The Design commands +# (Tools/Design*.cpp), whose functions are the Design tab's own entry points, are not among them. +CALLERS = ["src/slic3r/GUI/NativeCommands.cpp", "src/slic3r/GUI/Mcp/Tools/*.cpp", "src/slic3r/plugin/host/*.cpp"] +NOT_CALLERS = ["src/slic3r/GUI/Mcp/Tools/Design*.cpp"] # Owner methods an operation calls, by the operation that stands for them. BANNED = { @@ -109,12 +109,15 @@ CALL = re.compile(r"(?:\.|->)\s*(" + "|".join(sorted({m for names in BANNED.valu def caller_files(): - files = set() - for pattern in CALLERS: - for path in glob.glob(os.path.join(REPO, pattern)): - rel = os.path.relpath(path, REPO).replace(os.sep, "/") - if rel not in NOT_CALLERS: - files.add(rel) + def matches(pattern, name): + paths = glob.glob(os.path.join(REPO, pattern)) + # A pattern that matches nothing would pass every check unseen, as after its files move. + if not paths: + sys.exit(f"{pattern} matches no file: correct {name} in {os.path.basename(__file__)}") + return {os.path.relpath(path, REPO).replace(os.sep, "/") for path in paths} + + files = set().union(*(matches(pattern, "CALLERS") for pattern in CALLERS)) + files -= set().union(*(matches(pattern, "NOT_CALLERS") for pattern in NOT_CALLERS)) return sorted(files) diff --git a/scripts/operation_calls_baseline.txt b/scripts/operation_calls_baseline.txt index 58fe8f9949..8865430bc4 100644 --- a/scripts/operation_calls_baseline.txt +++ b/scripts/operation_calls_baseline.txt @@ -23,39 +23,40 @@ plater->export_stl(false, false, true); plater->export_stl(false, false, false, FT_DRC); plater->export_stl(false, false, true, FT_DRC); -[src/slic3r/GUI/Mcp/McpToolsConfig.cpp] -# The undo step of a tool whose function has one automation entry point (settings_set's object and part -# targets, plate_set_settings and project_set_settings). -plater.take_snapshot("Move object"); +[src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp] +# The asking path of a command, its person's form: object_rename {} and object_set_instances {} call the owner's +# method on the target they resolved from the selection, which asks the person what an operation would be told. +list->rename_item(); +plater.set_number_of_copies(); +# The undo step of a tool whose function has one automation entry point (object_transform and +# object_set_height_ranges). +plater.take_snapshot("Transform object"); +plater.take_snapshot("Transform part", UndoRedo::SnapshotType::GizmoAction); +plater.take_snapshot("Edit height ranges"); + +[src/slic3r/GUI/Mcp/Tools/PlateTools.cpp] +# The undo step of a tool whose function has one automation entry point (plate_set_settings). plater.take_snapshot("Plate Settings"); -plater.take_snapshot("Change object settings"); # A tool selecting the plate it was given before its own work, as the plate's settings icon does. plater.select_plate(index); + +[src/slic3r/GUI/Mcp/Tools/PresetTools.cpp] +# The undo step of a tool whose function has one automation entry point (settings_set's object and part +# targets, and project_set_settings, whose settings this file writes). +plater.take_snapshot("Move object"); +plater.take_snapshot("Change object settings"); # Another function that uses the same owner method: settings_set makes the filament tab edit a slot's # preset, and preset_delete selects the preset, deletes it and selects back. if (!tab->select_preset(name)) if (!tab->select_preset(name)) tab->select_preset(selected); -[src/slic3r/GUI/Mcp/McpToolsLayers.cpp] -# The undo step of a tool whose function has one automation entry point (object_set_height_ranges). -plater.take_snapshot("Edit height ranges"); - -[src/slic3r/GUI/Mcp/McpToolsProject.cpp] +[src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp] # The asking path of a command, its person's form: project_new and project_save called with no arguments # call the owner's method, which asks the person what an operation would be told. plater->new_project(); return NativeCommands::project_save_result(plater->save_project(false)); -[src/slic3r/GUI/Mcp/McpToolsScene.cpp] -# The asking path of a command, its person's form: object_rename {} and object_set_instances {} call the owner's -# method on the target they resolved from the selection, which asks the person what an operation would be told. -list->rename_item(); -plater.set_number_of_copies(); -# The undo step of a tool whose function has one automation entry point (object_transform). -plater.take_snapshot("Transform object"); -plater.take_snapshot("Transform part", UndoRedo::SnapshotType::GizmoAction); - [src/slic3r/plugin/host/PluginHostPresets.cpp] # The plugin API's own step between resolving a filament and assigning it: its transaction edits the # preset, so the filament tab is made to edit it first, and a declined prompt ends the call there. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 0e4eef8f03..55c6509d20 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -198,24 +198,19 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpTools.hpp GUI/Mcp/McpPluginCaller.cpp GUI/Mcp/McpPluginCaller.hpp - GUI/Mcp/McpToolsActions.cpp - GUI/Mcp/McpToolsApi.cpp - GUI/Mcp/McpToolsApp.cpp - GUI/Mcp/McpToolsCommon.cpp - GUI/Mcp/McpToolsConfig.cpp - GUI/Mcp/McpToolsGizmos.cpp - GUI/Mcp/McpToolsInstall.cpp - GUI/Mcp/McpToolsLayers.cpp - GUI/Mcp/McpToolsPlugins.cpp - GUI/Mcp/McpToolsPreferences.cpp - GUI/Mcp/McpToolsPrinter.cpp - GUI/Mcp/McpToolsProject.cpp - GUI/Mcp/McpToolsPython.cpp - GUI/Mcp/McpToolsRecord.cpp - GUI/Mcp/McpToolsReplay.cpp - GUI/Mcp/McpToolsScene.cpp - GUI/Mcp/McpToolsUi.cpp - GUI/Mcp/McpToolsView.cpp + GUI/Mcp/Tools/AppTools.cpp + GUI/Mcp/Tools/CatalogTools.cpp + GUI/Mcp/Tools/FilamentTools.cpp + GUI/Mcp/Tools/GuiTools.cpp + GUI/Mcp/Tools/ObjectTools.cpp + GUI/Mcp/Tools/PlateTools.cpp + GUI/Mcp/Tools/PluginTools.cpp + GUI/Mcp/Tools/PresetTools.cpp + GUI/Mcp/Tools/PrinterTools.cpp + GUI/Mcp/Tools/ProjectTools.cpp + GUI/Mcp/Tools/RecordingTools.cpp + GUI/Mcp/Tools/ToolsCommon.cpp + GUI/Mcp/Tools/ViewTools.cpp GUI/Mcp/ScreenCapture.cpp GUI/Mcp/ScreenCapture.hpp GUI/Mcp/PythonScriptsDialog.cpp @@ -993,8 +988,16 @@ if (SLIC3R_CAD) GUI/CAD/DesignInteraction.hpp GUI/CAD/SketchInlineEditor.cpp GUI/CAD/SketchInlineEditor.hpp - GUI/Mcp/McpToolsCad.cpp - GUI/Mcp/McpToolsCad.hpp + GUI/Mcp/McpToolsDesign.hpp + GUI/Mcp/Tools/DesignCommon.hpp + GUI/Mcp/Tools/DesignBodyTools.cpp + GUI/Mcp/Tools/DesignConstructTools.cpp + GUI/Mcp/Tools/DesignHistoryTools.cpp + GUI/Mcp/Tools/DesignInspectTools.cpp + GUI/Mcp/Tools/DesignSketchTools.cpp + GUI/Mcp/Tools/DesignSolidTools.cpp + GUI/Mcp/Tools/DesignSurfaceTools.cpp + GUI/Mcp/Tools/DesignTools.cpp ) endif () diff --git a/src/slic3r/GUI/ActionRegistry.cpp b/src/slic3r/GUI/ActionRegistry.cpp index 5415d50630..b761db7c21 100644 --- a/src/slic3r/GUI/ActionRegistry.cpp +++ b/src/slic3r/GUI/ActionRegistry.cpp @@ -20,7 +20,7 @@ #ifdef SLIC3R_CAD #include "CAD/DesignOffer.hpp" #include "CAD/DesignPanel.hpp" -#include "Mcp/McpToolsCad.hpp" +#include "Mcp/McpToolsDesign.hpp" #endif #include diff --git a/src/slic3r/GUI/CAD/DesignOffer.hpp b/src/slic3r/GUI/CAD/DesignOffer.hpp index fc7c6f1fe6..853d65c13c 100644 --- a/src/slic3r/GUI/CAD/DesignOffer.hpp +++ b/src/slic3r/GUI/CAD/DesignOffer.hpp @@ -6,7 +6,7 @@ // not apply are shown disabled in place with their reason rather than removed. Row order was // ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory. // An entry with a handler or a tool block, and no fold_into, is a command of the catalog's group Design -// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_list's index. A +// (Mcp::register_design_tools(), Mcp::is_design_command()), under its section in tool_list's index. A // call whose arguments are exactly those that choose one of its items opens that item's tool for a person // (Mcp::opened_item()): none choose the entry's own item where it has a handler, else the items folded into it // with {}; a folded item's args, or the entry's own, choose that item. Any other call runs its tool block's diff --git a/src/slic3r/GUI/CAD/DesignPanel.cpp b/src/slic3r/GUI/CAD/DesignPanel.cpp index f6a76e74ea..489de4c8b4 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.cpp +++ b/src/slic3r/GUI/CAD/DesignPanel.cpp @@ -7,7 +7,7 @@ #include "slic3r/GUI/CAD/DesignOffer.hpp" // generated offer table — see scripts/CAD/tool_atlas.json #include "slic3r/GUI/GLToolbar.hpp" #include "slic3r/GUI/GUI_Utils.hpp" -#include "slic3r/GUI/Mcp/McpToolsCad.hpp" // cad_body_vertices: a vertex id as body_describe numbers it +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" // cad_body_vertices: a vertex id as body_describe numbers it #include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "libslic3r/CAD/GeometryEngine.hpp" // face_by_index for face-extrude gizmo anchor diff --git a/src/slic3r/GUI/CAD/DesignPanel.hpp b/src/slic3r/GUI/CAD/DesignPanel.hpp index e6b7f992f7..7b17c53c85 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.hpp +++ b/src/slic3r/GUI/CAD/DesignPanel.hpp @@ -139,7 +139,7 @@ public: void set_body_color(int b, const ColorRGBA& color); void show_body(int b, bool shown); - // MCP hooks: let the MCP server's Design commands (Mcp/McpToolsCad.cpp) drive and + // MCP hooks: let the MCP server's Design commands (Mcp/Tools/Design*.cpp) drive and // perceive the SAME kernel the GUI uses. Called only on the wx main thread. CadDocument& mcp_doc() { return m_doc; } // live document (read + mutate) // Refresh tree + viewport + status after a change; `ok` false says "Edit rejected: ". @@ -258,7 +258,7 @@ public: // Mcp::CadPrecondition, as a view not built throws Mcp::no_design_view(). Otherwise whatever is selected goes first, of every // kind (the solid and loop picks, the Feature list's and Bodies list's rows, the picked reference plane), so that // one form never leaves another's behind, and a feature's highlight is in place when this returns. For the model - // at rest: cad_gate() refuses the call while a card or anything else a click would feed is open. + // at rest: design_gate() refuses the call while a card or anything else a click would feed is open. bool mcp_select(const DesignSelection& s, std::string& why); // The selected row of the Feature list, a feature index, or -1. int mcp_feature_row() const; diff --git a/src/slic3r/GUI/CommandCatalog.hpp b/src/slic3r/GUI/CommandCatalog.hpp index 972330c8a5..1f0c59d7c7 100644 --- a/src/slic3r/GUI/CommandCatalog.hpp +++ b/src/slic3r/GUI/CommandCatalog.hpp @@ -16,7 +16,7 @@ // libslic3r_automation, which is built without wx. namespace Slic3r { namespace GUI { -// The group of the Design tab's commands (Mcp::register_cad_commands()), an untranslated msgid as every +// The group of the Design tab's commands (Mcp::register_design_tools()), an untranslated msgid as every // group is. Their actions are the Speed Dial's only while the Design tab is shown. inline constexpr const char* kDesignGroup = "Design"; diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 42d23f21bb..7a4215f089 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -25,6 +25,11 @@ #include #include +namespace libvgcode { +enum class EGCodeExtrusionRole : std::uint8_t; +enum class EOptionType : std::uint8_t; +} // namespace libvgcode + namespace Slic3r { class AppConfig; @@ -46,6 +51,8 @@ namespace GUI { struct AppAction; struct AppActionRunResult; +struct Camera; +class GCodeViewer; class IMSlider; class PartPlate; class PartPlateList; @@ -65,78 +72,32 @@ class AutomationRuntime; struct Replay; struct ReplayContext; -// Each tool family adds its commands to the catalog (NativeCommands::register_all_commands(), which gives each the -// group of its place), and so do the Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function +// Each place's commands are in a file of their own (Tools/Tools.cpp), whose function adds them to the catalog +// in the order its place lists them (NativeCommands::register_all_commands(), which gives each command the group of +// its place); the Design tab's commands are added by register_design_tools() (McpToolsDesign.hpp). A command's function // reaches the automation runtime through its call's context (ToolContext::runtime()), so the catalog is built // without one. -// `cad`: the catalog holds the Design tab's commands, which undo's and redo's examples call. +// Tools and actions: tool_list, tool_describe, tool_call, action_list and action_run. `design_index` ends tool_list's +// description: what it says of the Design commands (design_command_index(), McpToolsDesign.hpp) in a catalog that holds +// them, and nothing in one that does not. +void register_catalog_tools(CommandCatalog& catalog, const std::string& design_index); +// The app. `cad`: the catalog holds the Design tab's commands, which undo's and redo's examples call. void register_app_tools(CommandCatalog& catalog, bool cad); -void register_action_tools(CommandCatalog& catalog); void register_project_tools(CommandCatalog& catalog); -void register_config_tools(CommandCatalog& catalog); -// The printer models and system filaments a person installs (McpToolsInstall.cpp). -void register_install_tools(CommandCatalog& catalog); -// The Preferences dialog's preferences, read and written (McpToolsPreferences.cpp). -void register_preference_tools(CommandCatalog& catalog); -void register_scene_tools(CommandCatalog& catalog); -// The commands that open a gizmo on a named target, and act from arguments where its gizmo has an entry point that asks -// nothing (McpToolsGizmos.cpp). -void register_gizmo_tools(CommandCatalog& catalog); -// A gizmo command's acting arguments: a call with any of them does the job and opens no gizmo; a call with none opens -// it. Empty for a command that only opens, and for any other command. -const std::vector& gizmo_acting_args(const std::string& command); -// print_start, printer_send, printer_test_host, printer_status, print_pause, print_resume and print_stop -// (McpToolsPrinter.cpp). -void register_printer_tools(CommandCatalog& catalog); -// printer_status's reply: {"connected": false} with no printer, else the status's fields, a name the Device tab would -// not give being null. -nlohmann::json printer_status_reply(const std::optional& status); -// The plates argument of print_start and printer_send, as project_export takes it: a plate's index into `plate`, -// "all" as `all`, or "current" (also when left out) as neither. Returns what is wrong with it, else empty. -std::string read_print_plates(const nlohmann::json& args, std::optional& plate, bool& all); -void register_view_tools(CommandCatalog& catalog); +void register_object_tools(CommandCatalog& catalog); // Objects and Parts +void register_plate_tools(CommandCatalog& catalog); +void register_preset_tools(CommandCatalog& catalog); // Presets and settings +void register_filament_tools(CommandCatalog& catalog); +void register_printer_tools(CommandCatalog& catalog); // Printers and prints void register_plugin_tools(CommandCatalog& catalog); -// The error of a plugin command refused by `refusal` (McpToolsPlugins.cpp), the plugin's row (plugin_list's) being -// `before` the call and `after` it, null where it is not listed. Where the call changed how the plugin stands (installed, -// enabled or its error: a cloud plugin downloaded before the refusal, or its download's error recorded), the error says -// how it is left and carries its row under "plugin"; else it is the refusal alone. -ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const nlohmann::json& before, const nlohmann::json& after); -// plugin_enable's reply once the call has ended (McpToolsPlugins.cpp), `row` being the plugin's row then, null where it is -// not listed: {plugin, changed}, with a note while the load the call started (`load_started`) goes on (`still_loading`), or -// where the plugin is no longer listed. A load that ended with the plugin not enabled, or no longer listed, is an error -// (not_loaded) that says how the plugin is left and carries its row. -nlohmann::json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading, - const nlohmann::json& row); -void register_ui_tools(CommandCatalog& catalog); -void register_replay_tools(CommandCatalog& catalog); -void register_record_tools(CommandCatalog& catalog); -void register_python_tools(CommandCatalog& catalog); -// `design_index` ends tool_list's description: what it says of the Design commands (design_command_index(), -// McpToolsCad.hpp) in a catalog that holds them, and nothing in one that does not. -void register_api_tools(CommandCatalog& catalog, const std::string& design_index); +void register_view_tools(CommandCatalog& catalog); // View and windows +void register_recording_tools(CommandCatalog& catalog); // Recordings, replays and scripts +void register_gui_tools(CommandCatalog& catalog); // Driving the GUI // Adds the source of the operations the loaded plugins offer (plugin..), which come and go with their // plugins, in group Plugins: tool_call runs one by name and tool_list lists it; tools/list does not show them. void register_plugin_operations(CommandCatalog& catalog); -// How run_replay_job() runs a replay beyond what the replay says. -struct ReplayRunOptions -{ - std::optional only_step; // 1-based; the whole replay when empty - bool write_result = true; // result.json in the output folder - // Called on the job thread as each step starts and ends (see ReplayHost). - std::function step_started; - std::function step_finished; -}; - -// Runs a parsed replay as the calling job, as replay_run does: steps are child calls, dialog rules -// the replay registers end with it, and result.json goes to sctx.out_dir (created if missing). It -// stops before the next step, and stops waiting on a step's job, once the call is cancelled: the -// runtime stops, or a stop was asked for any job in the call's lineage (JobRegistry::request_stop), so -// a nested replay_run stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file). -nlohmann::json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, - const ReplayRunOptions& options); - -// ---- schema helpers -------------------------------------------------------------------------- +// ---- schema helpers (ToolsCommon.cpp) -------------------------------------------------------- using Property = std::pair; @@ -161,13 +122,17 @@ NativeCommand mutate_tool(std::string name, std::string title, std::string descr // with no argument form is no command of the tool list: its declaration sets listed false. NativeCommand menu_command(std::string name, std::string title, std::string description, nlohmann::json schema, nlohmann::json actions, std::function fn); +// `command`, named as its menu item, as that item's own action, in the Speed Dial's section `section` with `icon`. +NativeCommand own_action(NativeCommand command, std::string section, std::string icon); +// A GUI input command: mutate_tool() under the recover guard, so it can act in the topmost modal dialog. +NativeCommand recover_input_tool(std::string name, std::string title, std::string description, nlohmann::json schema, CommandFn handler); // What a command made from menu items replies to a call, which a pick does not show: `reply`. AppActionRunResult menu_reply(const nlohmann::json& reply); // What a command made from menu items answers for a refusal after a dialog the person answered or read, which told them why: // a pick shows nothing more, and a call learns the refusal. AppActionRunResult quiet_refusal(const Ops::Refusal& refusal); -// ---- object, part and instance ids ----------------------------------------------------------- +// ---- object, part and instance ids (ToolsCommon.cpp) ----------------------------------------- // The schema of an id argument: the id object_list reports for an object, part or instance (`of`), which orca.host // shows too, so a script addresses what it read. Its description only names what it is: that an id names its target @@ -185,12 +150,21 @@ NativeCommand with_target_ids(NativeCommand command); void check_expected_ids(const ModelObject& object, const ModelVolume* volume, const ModelInstance* instance, const nlohmann::json& args); -// ---- handler helpers ------------------------------------------------------------------------- +// ---- handler helpers (ToolsCommon.cpp) ------------------------------------------------------- // One more UI round trip after a mutation, so events it queued are handled before the reply, and // any 3D view it showed has its GL surface (on Wayland, a moment after it is shown). void settle(ToolContext& ctx); +// Journals `args` with `locator` as the target a ref named: the journal replays locators, never refs, which mean +// nothing in another session. +void journal_with_locator(ToolContext& ctx, const nlohmann::json& args, const nlohmann::json& locator); + +// A height as messages show it: 15, 12.5, 0.08. +std::string mm(double z); +// `value` rounded to 1/`scale` for a reply, which reads like the legend rather than the raw floats. +double rounded(double value, double scale); + // The plater, or ToolFailure while the main window is not up yet (startup, language change). // UI thread only. Plater& ui_plater(); @@ -220,7 +194,31 @@ int arg_int(const nlohmann::json& args, const char* key, int fallback); double arg_double(const nlohmann::json& args, const char* key, double fallback); bool arg_bool(const nlohmann::json& args, const char* key, bool fallback); -// ---- tool_list and tool_describe --------------------------------------------------------------- +// Page a JSON array: {total, offset, items:[...]}. +nlohmann::json page(const nlohmann::json& items, const nlohmann::json& args, std::size_t default_limit = 100); + +// Polls `poll` on the UI thread every 200 ms until it returns a non-null value or `timeout` +// passes; throws ToolFailure on timeout or cancellation. +nlohmann::json poll_ui(ToolContext& ctx, + const std::function& poll, + std::chrono::milliseconds timeout, + const std::string& what); +// Polls `poll` on the UI thread, under the inspect guard, every `interval` until it returns a non-null +// value, which it returns, or until `timeout` passes or the call is cancelled, when it returns null: for +// a wait that replies with what it got rather than failing. +nlohmann::json poll_until(ToolContext& ctx, + const std::function& poll, + std::chrono::milliseconds timeout, + std::chrono::milliseconds interval); + +// Why the UI can't change when OrcaSlicer's window is not being drawn, or empty when it is drawn or +// can't tell. A compositor stops drawing a window while the display is off, and GTK then neither lays +// it out nor paints it: waits for the UI time out, lists can't scroll to a row and the 3D views capture +// blank. Asks for a frame and waits up to half a second for it, so only for a call that failed. Tool +// thread. +std::string undrawn_window(ToolContext& ctx); + +// ---- tools and actions (CatalogTools.cpp) ---------------------------------------------------- // tool_list's answer from `catalog`: {items: [{name, group, heading?, does}], use, note?}, the commands it holds and // those its sources hold now that tools/list does not show, in that order; does is the whole description up to 300 @@ -277,13 +275,11 @@ nlohmann::json action_journal_args(const AppAction& action, const nlohmann::json // folded item's action), as wrong_mode. For any other, where an action or a command is found (invalid_argument). ToolFailure unknown_action(const std::string& id, const CommandCatalog& catalog, bool cad_on); -// A setting value from JSON in the serialized form set_deserialize accepts: "3", "0.2", "1"/"0" -// for booleans, "a,b" for arrays. A list of strings (`key` names a coStrings option, such as -// post_process) is quoted and separated by semicolons, as ConfigOptionStrings writes it, since its -// entries may contain commas. Throws ToolFailure for values with no such form. -std::string to_config_string(const nlohmann::json& value, const std::string& key = {}); +// What an editor suggests for each listed command: [{name, title (translated), args: {name: {type?, enum?}}}]. The +// argument descriptions are written for agents, in English, and stay out. +nlohmann::json editor_tool_catalog(const CommandCatalog& catalog); -// ---- Python (McpToolsPython.cpp) ------------------------------------------------------------- +// ---- Python (RecordingTools.cpp) ------------------------------------------------------------- // The Python API reference script_list_api and script_describe_api read: every public module, class, function, method, property, named instance (such // as orca.host.preset.process) and constant (such as orca.host.ui.PD_CAN_ABORT) of the orca package, in @@ -326,18 +322,66 @@ ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, std::shared_ptr start_python_session(AutomationRuntime& runtime, std::shared_ptr session, const boost::filesystem::path& file, PersonRun::Events events); -// What an editor suggests for each listed command: [{name, title (translated), args: {name: {type?, enum?}}}]. The -// argument descriptions are written for agents, in English, and stay out. -nlohmann::json editor_tool_catalog(const CommandCatalog& catalog); - -// ---- recording (McpToolsRecord.cpp) ---------------------------------------------------------- +// ---- recording (RecordingTools.cpp) ---------------------------------------------------------- // Starts recording_encode with `args` as an unjournaled job of its own and returns at once: the job's envelope, or // the error that refused it. For a recording's encode that recording_stop starts, which a replay of the recording // asks for again; the Agent Activity pane lists it with the stop, whose job is `stop_job`. Any thread. ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args, const std::string& stop_job); -// ---- settings (McpToolsConfig.cpp) ----------------------------------------------------------- +// How run_replay_job() runs a replay beyond what the replay says. +struct ReplayRunOptions +{ + std::optional only_step; // 1-based; the whole replay when empty + bool write_result = true; // result.json in the output folder + // Called on the job thread as each step starts and ends (see ReplayHost). + std::function step_started; + std::function step_finished; +}; + +// Runs a parsed replay as the calling job, as replay_run does: steps are child calls, dialog rules +// the replay registers end with it, and result.json goes to sctx.out_dir (created if missing). It +// stops before the next step, and stops waiting on a step's job, once the call is cancelled: the +// runtime stops, or a stop was asked for any job in the call's lineage (JobRegistry::request_stop), so +// a nested replay_run stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file). +nlohmann::json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, + const ReplayRunOptions& options); + +// ---- settings (PresetTools.cpp) -------------------------------------------------------------- + +// A setting value from JSON in the serialized form set_deserialize accepts: "3", "0.2", "1"/"0" +// for booleans, "a,b" for arrays. A list of strings (`key` names a coStrings option, such as +// post_process) is quoted and separated by semicolons, as ConfigOptionStrings writes it, since its +// entries may contain commas. Throws ToolFailure for values with no such form. +std::string to_config_string(const nlohmann::json& value, const std::string& key = {}); + +// Per filament slot, in config order, whether it is a mixed filament. UI thread. +std::vector mixed_slots(); + +// Sets unknown_keys to the keys a read named that its settings, `within`, lack; type_of to where each of those is a +// setting elsewhere, so the agent can ask there; and similar to the keys of `within` like each of the others, as +// settings_set's refusal gives them. UI thread. +void add_unknown_keys(nlohmann::json& out, const nlohmann::json& unknown, const std::vector& within); + +// The refusal of a key that the settings `where` names (a type, "project" or "plate") lack: it says where the key is a +// setting when it is one elsewhere, since the usual cause is a key passed with the wrong type or to none (the +// process). Its code is invalid_argument. UI thread. +ToolFailure unknown_setting(const std::string& key, const std::string& where, nlohmann::json details); + +// The project's settings and the filament list's flushing: project_config's, with the wipe tower position one entry +// per plate, since a project can store fewer. UI thread. +DynamicPrintConfig project_settings(); + +// The values a project setting's control offers this printer; empty while the control is hidden. UI thread. +std::vector project_offered(const std::string& key); + +// project_set_settings, with the project's keys, and filament_set_flushing, with the filament list's flushing +// (`flushing`). Every key is written by the code its control runs: the plate type selector, the Flushing volumes and +// Purge mode dialogs' OK, a wipe tower drag. Everything is checked before anything changes. +ToolResult set_project_values(const nlohmann::json& values_in, ToolContext& ctx, bool flushing); +// project_get_settings' reply: the project's own settings that `args` asks for, read as settings_get reads a target's. +// UI thread. +nlohmann::json read_project_settings(const nlohmann::json& args); // Why settings_get (or, with `writes`, settings_set) refuses `args` before reading anything, or empty when it does // not: a target the type has not (an object's, a part's and a height range's settings are the process's), an object, @@ -400,7 +444,6 @@ nlohmann::json option_meta(const ConfigOptionDef& def); // alphabetical order, each group's settings being how many of `keys` it holds. Any thread. nlohmann::json settings_pages(const std::map& places, const std::vector& keys); - // For a per-variant or per-extruder vector `key` of a preset's `config` that has more than one entry: // {"variants": [what each entry is for], "active": [the entry each extruder prints with, extruder 1 // first]}; a per-extruder key has no "active", since each extruder uses its own entry. `extruder_types` @@ -475,21 +518,6 @@ std::vector check_flush_multipliers(std::vector multipliers, std std::vector check_flush_matrix(std::vector matrix, std::size_t slots, const std::vector& multipliers, const std::vector& current, const std::vector& mixed); -// The keys of a plate's own settings, which plate_get_settings reads and plate_set_settings writes: what the Plate -// Settings dialog sets on one plate, and the filament grouping its filament map icon opens (filament_map_mode, -// filament_map). Its name and its lock are set by its icons, as plate_rename and plate_lock set them. -const std::vector& plate_setting_keys(); - -// plate_list's place of a plate on the bed: {origin, size}, the [x, y] of its front left corner and its [width, depth] -// in mm, in the bed coordinates object positions are given in, read from the plate's rectangle on the bed. -nlohmann::json plate_place(PartPlate& plate); - -// Why plate_set_settings refuses `map` as a plate's filament_map (the 1-based extruder of each filament), or empty -// when it does not: the map is the plate's own grouping, "Manual" as its `mode` (filament_map_mode, "" where the plate -// follows the project's grouping), with one extruder per filament of the `filaments` and each of the printer's -// `extruders`. -std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders); - // preset_list's filters over `items`, one per preset as preset_list builds them: query (part of the name or alias), // vendor and filament_type (in either case), source (system, user or project; a preset kept in the project is no user // one), and the items marked compatible: false or installed: false only with include_incompatible or @@ -510,6 +538,29 @@ std::size_t extruders_count_value(const nlohmann::json& value, bool single_extru std::string nozzle_diameter_variant(const std::vector& diameters, const std::vector& variants, const std::string& current); +// Points the filament tab at the preset of filament slot `slot` (1-based, in range), as opening that slot's +// settings does, through the tab's switch, which asks about its unsaved changes. Returns the preset the tab +// edited before, or empty when it already edited that one. Throws ToolFailure when the switch is cancelled. +// UI thread. +std::string edit_filament_slot(int slot); + +// ---- plates (PlateTools.cpp) ----------------------------------------------------------------- + +// The keys of a plate's own settings, which plate_get_settings reads and plate_set_settings writes: what the Plate +// Settings dialog sets on one plate, and the filament grouping its filament map icon opens (filament_map_mode, +// filament_map). Its name and its lock are set by its icons, as plate_rename and plate_lock set them. +const std::vector& plate_setting_keys(); + +// plate_list's place of a plate on the bed: {origin, size}, the [x, y] of its front left corner and its [width, depth] +// in mm, in the bed coordinates object positions are given in, read from the plate's rectangle on the bed. +nlohmann::json plate_place(PartPlate& plate); + +// Why plate_set_settings refuses `map` as a plate's filament_map (the 1-based extruder of each filament), or empty +// when it does not: the map is the plate's own grouping, "Manual" as its `mode` (filament_map_mode, "" where the plate +// follows the project's grouping), with one extruder per filament of the `filaments` and each of the printer's +// `extruders`. +std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders); + // A plate's filament order as the Plate Settings dialog's drag canvas gives it: every slot 1..`slots` once. // Throws ToolFailure otherwise. std::vector filament_order(const nlohmann::json& order, int slots); @@ -534,22 +585,58 @@ std::vector gcode_layer_zs(const GCodeProcessorResult& result); // change, gcode for custom G-code. nlohmann::json layer_gcode_json(const CustomGCode::Info& codes, const std::vector& layer_zs); -// preferences_get's reply: {total, items}, an item for each preference of `shown` (the rows the Preferences dialog shows, -// Ops::shown_preferences()) that `args`' keys, tab and query leave (query: each of its words in the key, the label or -// the section, in any case), with its value typed by its kind: the text `shown_texts` gives for its key, which is what -// the dialog shows where that is not the stored value (Ops::shown_texts()), else the one in `config`'s app section; then -// {key, value} as stored for each named key outside `shown` that the section holds, and unknown_keys, with a note, for -// the named keys it lacks. The section also holds account and device state, so nothing outside `shown` is listed unasked. -nlohmann::json preferences_settings(const AppConfig& config, const std::vector& shown, const nlohmann::json& args, - const std::map& shown_texts = {}); +// The names plate_set_custom_gcode and plate_list give the types of layer codes: pause, custom, template, +// change_filament, and color_change for an old project's colour change. +const char* custom_gcode_type_name(CustomGCode::Type type); +// The type plate_set_custom_gcode adds for a name; CustomGCode::Unknown for any other, color_change included, +// since the layer slider adds none. +CustomGCode::Type custom_gcode_type_from_name(const std::string& name); +// plate_set_custom_gcode's clear, remove and add, in that order, on a layer slider that holds a plate's layers +// and codes. Everything is checked against the slider's layers and codes before it changes, with the +// rules of its menus: one code per layer, a template only when the printer has one (`has_template`), a +// filament change only with two or more filaments, as many as the slider has (`filaments`, the slots now), +// and while the slider offers it (else `no_filament_change` says why). Then the slider's own edits run: +// delete, add, and on a layer with a code of the same type Edit Custom G-code or Change Filament. Returns +// whether the codes changed; the slider then has their hand-over to the plater pending. Throws ToolFailure. +bool edit_layer_gcode(IMSlider& slider, const nlohmann::json& args, int filaments, bool has_template, + const std::string& no_filament_change); -// Points the filament tab at the preset of filament slot `slot` (1-based, in range), as opening that slot's -// settings does, through the tab's switch, which asks about its unsaved changes. Returns the preset the tab -// edited before, or empty when it already edited that one. Throws ToolFailure when the switch is cancelled. -// UI thread. -std::string edit_filament_slot(int slot); +// ---- project (ProjectTools.cpp) -------------------------------------------------------------- -// ---- calibration (McpToolsProject.cpp) ------------------------------------------------------- +// What a command that replaces the project replies of it afterwards: its objects, their names and its plates. UI thread. +nlohmann::json objects_summary(Plater& plater); +// Fails, as a command that replaces the project refuses, when the project has unsaved changes the caller did not say +// to drop (`discard`). +void require_project_discardable(bool discard); +// Waits for a G-code export started between Plater export sequence numbers `before` and `after` +// (unchanged = it never started: `rejection` explains why) and reports how it ended; `revision` is +// the project revision when it started. +ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket); + +// ---- printers (PrinterTools.cpp) ------------------------------------------------------------- + +// printer_status's reply: {"connected": false} with no printer, else the status's fields, a name the Device tab would not +// give being null. +nlohmann::json printer_status_reply(const std::optional& status); +// The plates argument of print_start and printer_send, as project_export takes it: a plate's index into `plate`, +// "all" as `all`, or "current" (also when left out) as neither. Returns what is wrong with it, else empty. +std::string read_print_plates(const nlohmann::json& args, std::optional& plate, bool& all); + +// ---- plugins (PluginTools.cpp) --------------------------------------------------------------- + +// The error of a plugin command refused by `refusal`, the plugin's row (plugin_list's) being `before` the call and +// `after` it, null where it is not listed. Where the call changed how the plugin stands (installed, enabled or its error: +// a cloud plugin downloaded before the refusal, or its download's error recorded), the error says how it is left and +// carries its row under "plugin"; else it is the refusal alone. +ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const nlohmann::json& before, const nlohmann::json& after); +// plugin_enable's reply once the call has ended, `row` being the plugin's row then, null where it is not listed: +// {plugin, changed}, with a note while the load the call started (`load_started`) goes on (`still_loading`), or where the +// plugin is no longer listed. A load that ended with the plugin not enabled, or no longer listed, is an error +// (not_loaded) that says how the plugin is left and carries its row. +nlohmann::json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading, + const nlohmann::json& row); + +// ---- calibration (PlateTools.cpp) ------------------------------------------------------------ // calibration_generate_test's arguments as the test's dialog takes them on `printer`: its defaults for what is left out (the // pressure advance ones by the printer's extruder type, an input shaping Y range or frequency by the X one), @@ -562,42 +649,22 @@ Calib_Params calib_params_from_args(const nlohmann::json& args, const DynamicPri // reports and records in the journal, so a replay does not depend on the dialogs' defaults. nlohmann::json calib_params_json(const nlohmann::json& args, const Calib_Params& params, const DynamicPrintConfig& printer); -// Page a JSON array: {total, offset, items:[...]}. -nlohmann::json page(const nlohmann::json& items, const nlohmann::json& args, std::size_t default_limit = 100); - -// Waits for a G-code export started between Plater export sequence numbers `before` and `after` -// (unchanged = it never started: `rejection` explains why) and reports how it ended; `revision` is -// the project revision when it started. -ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket); - -// Polls `poll` on the UI thread every 200 ms until it returns a non-null value or `timeout` -// passes; throws ToolFailure on timeout or cancellation. -nlohmann::json poll_ui(ToolContext& ctx, - const std::function& poll, - std::chrono::milliseconds timeout, - const std::string& what); -// Polls `poll` on the UI thread, under the inspect guard, every `interval` until it returns a non-null -// value, which it returns, or until `timeout` passes or the call is cancelled, when it returns null: for -// a wait that replies with what it got rather than failing. -nlohmann::json poll_until(ToolContext& ctx, - const std::function& poll, - std::chrono::milliseconds timeout, - std::chrono::milliseconds interval); - -// Why the UI can't change when OrcaSlicer's window is not being drawn, or empty when it is drawn or -// can't tell. A compositor stops drawing a window while the display is off, and GTK then neither lays -// it out nor paints it: waits for the UI time out, lists can't scroll to a row and the 3D views capture -// blank. Asks for a frame and waits up to half a second for it, so only for a call that failed. Tool -// thread. -std::string undrawn_window(ToolContext& ctx); - -// ---- app (McpToolsApp.cpp) ------------------------------------------------------------------- +// ---- app (AppTools.cpp) ---------------------------------------------------------------------- // app_log's lines of the log read from `in`: the last `lines` of those at or above `min_level` (trace, debug, info, // warning, error, fatal). std::vector log_tail(std::istream& in, const std::string& min_level, std::size_t lines); -// ---- view (McpToolsView.cpp) ----------------------------------------------------------------- +// preferences_get's reply: {total, items}, an item for each preference of `shown` (the rows the Preferences dialog shows, +// Ops::shown_preferences()) that `args`' keys, tab and query leave (query: each of its words in the key, the label or +// the section, in any case), with its value typed by its kind: the text `shown_texts` gives for its key, which is what +// the dialog shows where that is not the stored value (Ops::shown_texts()), else the one in `config`'s app section; then +// {key, value} as stored for each named key outside `shown` that the section holds, and unknown_keys, with a note, for +// the named keys it lacks. The section also holds account and device state, so nothing outside `shown` is listed unasked. +nlohmann::json preferences_settings(const AppConfig& config, const std::vector& shown, const nlohmann::json& args, + const std::map& shown_texts = {}); + +// ---- view (ViewTools.cpp) -------------------------------------------------------------------- // What view_set sets outside the Design tab, as app_state's view gives it, under the names of view_set's arguments so // that it can be passed back: sidebar_collapsed and sidebar_width (pixels), legend_collapsed and gcode_window, the 3D @@ -610,7 +677,18 @@ nlohmann::json view_state(Plater& plater); // when no word names that page (a plugin's page, the web Device page); else nothing. std::optional view_tab_page(const std::string& tab, const std::vector& pages); -// ---- windows (McpToolsUi.cpp) ---------------------------------------------------------------- +// The camera view_set leaves, as its reply's camera_state and app_state.camera give it: type ("ortho" +// or "perspective"), look_at, the point it looks at, and position ([x, y, z] in mm, to 0.001), zoom (viewport +// pixels per mm at look_at's depth) and click_px_per_mm (the zoom in the logical pixels the input tools take, the zoom over +// `canvas_scale`), both to 0.0001, and the elevation and azimuth orbit uses, in whole degrees. +nlohmann::json camera_state(Camera& camera, double canvas_scale); + +// The names plate_slice_stats and view_set give the legend's rows: a feature type by the English name of +// its ;FEATURE: tag, an option by a key; null for the options that are markers, not rows. +std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role); +const char* legend_option_key(libvgcode::EOptionType type); + +// ---- windows (ViewTools.cpp) ----------------------------------------------------------------- // What a window's title bar offers and where it runs, for window_request_refusal(). struct WindowAbilities @@ -638,19 +716,12 @@ struct WindowSettling // adjusted, the fields of `args` the window differs from, and a note on why: a size limit, the window // manager, a compositor that refused to activate a minimized window, or a 3D view that didn't draw. void add_window_notes(const nlohmann::json& args, const WindowSettling& settling, nlohmann::json& reply); -// Whether the shown 3D view has drawn at its canvas's size, asking for a frame when it hasn't: until it -// has, the camera's viewport is the old size, which a fit or a screen_rect would use. True when no 3D -// view is shown. UI thread. -bool view_drawn_at_size(); // {index, x, y, width, height}: the work area of display `index` (the screen less the taskbar or the // dock and menu bar), in the units window_list reports. UI thread. nlohmann::json display_area(unsigned index); -// ---- scene ----------------------------------------------------------------------------------- +// ---- objects (ObjectTools.cpp) --------------------------------------------------------------- -// The Prepare canvas, for edits made through the object list and the canvas selection as a person makes -// them: switches to it from another tab; ToolFailure in the assemble view or while a gizmo is open. UI thread. -GLCanvas3D& require_prepare_scene(Plater& plater); // Selects an object's row, or with `volume` a part's, in the object list and nothing else, as clicking // it does. UI thread. void select_rows(ModelObject* object, ModelVolume* volume); @@ -712,10 +783,11 @@ ModelVolumeType precise_seam_subtype(const std::string& name); // per field of the Primitive size dialog, in its order. Empty when size is null (the built-in size). // Throws ToolFailure naming the fields. std::vector part_shape_size(const std::string& shape, const nlohmann::json& size); +// A gizmo command's acting arguments: a call with any of them does the job and opens no gizmo; a call with none opens +// it. Empty for a command that only opens, and for any other command. +const std::vector& gizmo_acting_args(const std::string& command); -// ---- layers (McpToolsLayers.cpp) ------------------------------------------------------------- - -void register_layer_tools(CommandCatalog& catalog); +// ---- height ranges (ObjectTools.cpp) --------------------------------------------------------- // The settings a height range modifier takes: layer_height, the per-region process settings the object // list offers a part or a range (with `filaments` filament slots), and extruder, the range's filament. @@ -733,55 +805,12 @@ t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges // range editor checks what a person types. Throws ToolFailure otherwise. void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range, const std::function(int extruder)>& layer_height_bounds); -// An object's height range modifiers as object_list and object_set_height_ranges report them: -// [{min_z, max_z, values: {key: value serialized as settings_get returns it}}], lowest first. -nlohmann::json layer_config_ranges_json(const t_layer_config_ranges& ranges); // An object's layer_height_profile ([z0, h0, z1, h1, ...]) as object_list and object_set_variable_layer_height // report it: {points, min_height, max_height}, heights to 0.001 mm; null unless the object list marks the // object's layer height as variable (more than 4 entries). nlohmann::json layer_height_profile_json(const std::vector& profile); -// The names plate_set_custom_gcode and plate_list give the types of layer codes: pause, custom, template, -// change_filament, and color_change for an old project's colour change. -const char* custom_gcode_type_name(CustomGCode::Type type); -// The type plate_set_custom_gcode adds for a name; CustomGCode::Unknown for any other, color_change included, -// since the layer slider adds none. -CustomGCode::Type custom_gcode_type_from_name(const std::string& name); -// plate_set_custom_gcode's clear, remove and add, in that order, on a layer slider that holds a plate's layers -// and codes. Everything is checked against the slider's layers and codes before it changes, with the -// rules of its menus: one code per layer, a template only when the printer has one (`has_template`), a -// filament change only with two or more filaments, as many as the slider has (`filaments`, the slots now), -// and while the slider offers it (else `no_filament_change` says why). Then the slider's own edits run: -// delete, add, and on a layer with a code of the same type Edit Custom G-code or Change Filament. Returns -// whether the codes changed; the slider then has their hand-over to the plater pending. Throws ToolFailure. -bool edit_layer_gcode(IMSlider& slider, const nlohmann::json& args, int filaments, bool has_template, - const std::string& no_filament_change); - -}}} // namespace Slic3r::GUI::Mcp - -// ---- slice results --------------------------------------------------------------------------- - -namespace libvgcode { -enum class EGCodeExtrusionRole : std::uint8_t; -enum class EOptionType : std::uint8_t; -} // namespace libvgcode - -namespace Slic3r { - -struct GCodeProcessorResult; - -namespace GUI { - -struct Camera; -class GCodeViewer; - -namespace Mcp { - -// The camera view_set leaves, as its reply's camera_state and app_state.camera give it: type ("ortho" -// or "perspective"), look_at, the point it looks at, and position ([x, y, z] in mm, to 0.001), zoom (viewport -// pixels per mm at look_at's depth) and click_px_per_mm (the zoom in the logical pixels the input tools take, the zoom over -// `canvas_scale`), both to 0.0001, and the elevation and azimuth orbit uses, in whole degrees. -nlohmann::json camera_state(Camera& camera, double canvas_scale); +// ---- slice results (PlateTools.cpp) ---------------------------------------------------------- // What a sliced plate reports in plate_slice's reply: print time, filament totals with the flush, cost, // layer count, max Z, filament changes, and every filament slot of the project (zeros for slots the @@ -811,10 +840,5 @@ nlohmann::json preview_state(GCodeViewer& viewer); // Whether the Preview's toolpaths are `result`'s. It loads a plate's only while it is shown, so after // another plate is selected it keeps the last one's. UI thread. bool viewer_holds(const GCodeViewer& viewer, const GCodeProcessorResult* result); -// The names plate_slice_stats and view_set give the legend's rows: a feature type by the English name of -// its ;FEATURE: tag, an option by a key; null for the options that are markers, not rows. -std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role); -const char* legend_option_key(libvgcode::EOptionType type); -}} // namespace GUI::Mcp -} // namespace Slic3r +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsActions.cpp b/src/slic3r/GUI/Mcp/McpToolsActions.cpp deleted file mode 100644 index 12b3b40445..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsActions.cpp +++ /dev/null @@ -1,298 +0,0 @@ -// action_list and action_run: every Speed Dial action - built-in commands, plates, recent projects, -// plugin scripts and pages, and (on request) settings - is listed and run through these two tools. - -#include "slic3r/GUI/I18N.hpp" -#include "McpArguments.hpp" -#include "McpPersonContext.hpp" -#include "McpTools.hpp" -#include "slic3r/GUI/ActionIds.hpp" -#include "slic3r/GUI/ActionRegistry.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Operations/ExportOps.hpp" -#include "slic3r/GUI/Operations/RunStatus.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; - -namespace { - -ActionRegistry& registry_or_fail() -{ - ActionRegistry* reg = wxGetApp().m_action_registry.get(); - if (reg == nullptr) - throw ToolFailure("The action catalog is not available yet; app_wait {for:\"ready\"} first"); - return *reg; -} - -// The name inside a "::" id (view_front in orca_command:view_front:orca), which -// is what agents and the tools' own messages call an action. -std::string short_id(const std::string& id) -{ - const std::size_t first = id.find(':'), last = id.rfind(':'); - return first == std::string::npos || first == last ? id : id.substr(first + 1, last - first - 1); -} - -// The action `id` names: its full id, or a name only one action has, among the actions of the app's state now -// (find_live(): the call before may have opened a sketch, added a plate or switched the tab). Otherwise -// ToolFailure with the ids closest to it, scored against both forms, a name containing it (delete_all in -// obj_delete_all) counting as closest. -const AppAction& find_action(ActionRegistry& actions, std::string& id) -{ - if (const AppAction* action = actions.find_live(id)) - return *action; - ActionRegistry::Query q; - q.limit = 100000; - std::vector named; - std::vector> scored; - const json all = actions.describe(q); - for (const json& a : all["items"]) { - const std::string candidate = a["id"]; - const std::string name = short_id(candidate); - if (name == id) - named.push_back(candidate); - const bool contains = id.size() >= 3 && name.find(id) != std::string::npos; - scored.emplace_back(contains ? 0 : std::min(edit_distance(id, candidate), edit_distance(id, name)), candidate); - } - if (named.size() == 1) { - id = named.front(); - return *actions.by_id(id); - } - std::sort(scored.begin(), scored.end()); - json similar = json::array(); - for (std::size_t i = 0; i < scored.size() && similar.size() < 3 && scored[i].first <= id.size() / 3 + 2; ++i) - similar.push_back(scored[i].second); -#ifdef SLIC3R_CAD - const bool cad_on = wxGetApp().is_enable_cad_feature(); -#else - const bool cad_on = false; -#endif - ToolFailure refused = unknown_action(id, NativeCommands::instance(), cad_on); - refused.details["similar"] = std::move(similar); - throw refused; -} - -} // namespace - -std::string action_args_error(const AppAction& action, const json& args) -{ - // An action that collects a value takes that value alone, as the Speed Dial's second phase gives it. - if (!action.input.empty()) - return args.is_object() && args.size() == 1 && args.contains(action.input) ? - std::string() : - "The action " + action.id() + " takes exactly its " + action.input + ": run it with args {\"" + action.input + - "\": ...} (its input_schema)"; - if (person_form(args)) - return {}; - // A command's action runs its command with the action's arguments, which it takes as well as none; other arguments - // are the command's to take. - if (!action.preset.is_null()) { - if (args == action.preset) - return {}; - if (action.preset.empty()) - return "The action " + action.id() + " takes no arguments: run it without args, or call " + action.command + - " with them"; - return "The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() + - ": run it without args or with exactly those, or call " + action.command + " with other arguments"; - } - // A Design command's own action takes the command's arguments, which the command checks. - if (!action.command.empty()) - return {}; - return "The action " + action.id() + " takes no arguments: run it without args"; -} - -json action_journal_args(const AppAction& action, const json& args) -{ - if (action.preset.is_null()) - return nullptr; - return action.input.empty() ? action.preset : args; -} - -ToolFailure unknown_action(const std::string& id, const CommandCatalog& catalog, bool cad_on) -{ - // A Design tab action is in the registry only while it is live (ActionRegistry::materialize_design_actions()), which - // none is while the CAD feature is off; its command is in the catalog, unless the catalog was built without the - // Design commands. Its id is right then, and the code says what keeps it from running. - const std::string action_id = id.find(':') != std::string::npos ? id : AppAction::compose_id(kCommandPrefix, id, kOrcaSourceKey); - if (is_design_action_id(action_id)) { - const std::string key = short_id(action_id); - if (const std::string* why = catalog.left_out(key)) - return ToolFailure(id + " is a Design tab action, and " + *why, {{"code", catalog.unknown_command_code(key)}}); - if (!cad_on) - return ToolFailure(id + " is a Design tab action, and the CAD feature is off: a person enables it in Preferences > " - "Features and restarts OrcaSlicer", - {{"code", "design_unavailable"}}); - // A folded item's action is a call of the command it is folded into with the item's arguments, written as the - // rest of the call is, a space after each colon and comma. - const auto [command, folded] = find_command_action(catalog, short_id(action_id)); - std::string call = "{\"tool\": \"" + (command != nullptr ? command->key : short_id(action_id)) + "\""; - if (folded != nullptr && !folded->at("args").empty()) { - std::string args; - for (const auto& [name, value] : folded->at("args").items()) - args += (args.empty() ? "" : ", ") + json(name).dump() + ": " + value.dump(); - call += ", \"args\": {" + args + "}"; - } - return ToolFailure(id + " is a Design tab action, there only while the Design tab is shown in its mode (a sketch's or " - "the model's) with the CAD feature on; tool_call " + call + "} runs its command from any tab", - {{"code", "wrong_mode"}}); - } - // The name may be a command's that has no action, which tool_call runs. - return ToolFailure("Unknown action id " + id + "; find an action with action_list, or a command in tools/list or with tool_list", - {{"code", "invalid_argument"}}); -} - -ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket) -{ - json done = poll_ui( - ctx, - [&ticket]() -> json { - ui_plater(); - std::string error; - const Ops::ExportStatus status = Ops::gcode_export_state(ticket, &error); - if (status == Ops::ExportStatus::Pending) - return json(); - json out{{"export", Ops::to_string(status)}, {"path", ticket.path}}; - if (!error.empty()) - out["error"] = error; - return out; - }, - std::chrono::minutes(10), "the export to finish"); - const std::string status = done["export"]; - if (status == "ok") - return ToolResult::ok(done); - if (status == "superseded") { - done["note"] = "The project changed while exporting; the file reflects the project as it was when the export started."; - return ToolResult::ok(done); - } - return ToolResult::error("The export ended " + status, done); -} - -namespace { - -// What `actions` lists for `q`. A section no action is in now is a name to correct, refused with the sections there -// are, as tool_list refuses a group. Recent Projects and Design hold actions only while there are recent projects -// and while the Design tab is shown, so either one empty is an answer, not a wrong name. -json described(ActionRegistry& actions, const ActionRegistry::Query& q) -{ - json listed = actions.describe(q); - if (q.section.empty() || listed.value("total", 0) != 0) - return listed; - for (const char* comes_and_goes : {"Recent Projects", kDesignGroup}) - if (boost::algorithm::iequals(q.section, comes_and_goes)) - return listed; - ActionRegistry::Query every; - every.include_settings = q.include_settings; - every.limit = 100000; - const json all = actions.describe(every); - json sections = json::array(); - std::string names; - for (const json& item : all["items"]) - if (std::find(sections.begin(), sections.end(), item["section"]) == sections.end()) { - sections.push_back(item["section"]); - names += (names.empty() ? "" : ", ") + item["section"].get(); - } - throw ToolFailure("Unknown section: " + q.section + "; the Speed Dial's sections now are " + names, - {{"code", "invalid_argument"}, {"sections", std::move(sections)}}); -} - -} // namespace - -void register_action_tools(CommandCatalog& catalog) -{ - catalog.add(inspect_tool( - "action_list", L("List Speed Dial actions"), - "List everything the Speed Dial can run, by section and title: built-in commands (slice, export, views, object " - "operations, plates, calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an `id` for " - "`action_run`, its `section` (where the Speed Dial lists it), a `description`, the `command` of a built-in " - "command, and, when it takes arguments, their `input_schema`. `section` keeps them to one of the Speed Dial's sections, which are not " - "`tool_list`'s groups; one no action is in is refused with the sections there are, but Recent Projects and Design " - "list nothing while there are no recent projects or the Design tab is not shown. `include_settings` also lists " - "settings (each jumps to that setting in the sidebar; use `settings_get` / `settings_set` to read or change values).", - object_schema({{"section", prop("string", "Only this Speed Dial section, in any case, as an entry's `section` names it, " - "e.g. \"Object\", \"View\", \"Slice & Export\".")}, - {"include_settings", prop("boolean", "Also list settings (thousands). Default false.")}, - {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 50."}}}, - {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [](const json& args, ToolContext& ctx) { - ActionRegistry::Query q; - q.section = arg_string(args, "section"); - q.include_settings = arg_bool(args, "include_settings", false); - q.limit = std::size_t(arg_int(args, "limit", 50)); - q.offset = std::size_t(arg_int(args, "offset", 0)); - return ToolResult::ok(ctx.run_ui([q] { return described(registry_or_fail(), q); })); - })); - - NativeCommand run = mutate_tool( - "action_run", L("Run a Speed Dial action"), - "Run one action by the id `action_list` returned (`orca_command:view_front:orca`, or the name inside it, `view_front`), " - "with `args`, the command's arguments, when it takes some (its `input_schema`). A command's action (`action_list` names " - "the command) runs the command as a call with the action's arguments does: an action that asks in a dialog asks, " - "and the call returns `blocked_by_dialog`; answer it with `dialog_answer`, or, for a native one it can't press (a file " - "picker), register `dialog_auto_answer` before the call. Such an action takes no `args`, or exactly its own; to run a " - "command without asking, call it with its arguments (an absolute path skips a file dialog). Go to layer and Go to " - "tab take their value alone (`{\"percent\": 50}`, `{\"tab\": \"preview\"}`), and a Design command's own action takes " - "the command's arguments. An action that starts a background job (`obj_arrange`, `obj_orient`) completes when the job " - "ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply " - "(the order `object_order` leaves, the object `object_assemble` made). The other actions (plates, recent projects, " - "plugin scripts and pages, settings) run only here.", - object_schema({{"id", prop("string", "Action id from `action_list`, or the name inside it.")}, - {"args", {{"type", "object"}, {"description", "The command's arguments, as its `input_schema` gives them."}}}}, - {"id"}), - [](const json& args, ToolContext& ctx) { - std::string id = arg_string(args, "id"); - json command_args = args.contains("args") ? args["args"] : json::object(); - std::string key; // the command of a command's action - json action_args; // what its journal step keeps for an action of fixed arguments - AppActionRunResult result; // of any other action - ctx.run_ui([&]() -> json { - ActionRegistry& actions = registry_or_fail(); - const AppAction& action = find_action(actions, id); - if (const std::string err = action_args_error(action, command_args); !err.empty()) - throw ToolFailure(err, {{"code", "invalid_argument"}}); - key = action.command; - action_args = action_journal_args(action, command_args); - if (key.empty()) { - result = actions.run(id, command_args, /*record_stats=*/false); - } else { - // What a person's pick of the action runs its command with, which the journal records. - const json* command_action = find_command_action(NativeCommands::instance(), short_id(id)).second; - command_args = action_call_args(command_action, command_args); - } - return json(); - }); - if (key.empty()) { - settle(ctx); - return NativeCommands::from_run_result(id, result); - } - // A command's action runs the command's own function, as a call of the command does, inside action_run's - // journal entry. - const NativeCommand* command = NativeCommands::find(key); - if (command == nullptr) - throw ToolFailure("Unknown command " + key); - if (const std::string err = argument_error(*command, command_args); !err.empty()) - throw argument_refusal(key, err); - ActionContext action_ctx(ctx, id, action_args); - ToolResult reply = command->run(command_args, action_ctx); - if (!reply.is_error && reply.data.is_object()) - reply.data["ran"] = id; - return reply; - }); - // Its actions send G-code to a printer or its print host (printer_send) and sync presets with the cloud account - // (preset_sync). - run.open_world = true; - catalog.add(run); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp deleted file mode 100644 index c7799b1c33..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ /dev/null @@ -1,6191 +0,0 @@ -// The Design tab's commands. The Design table (kDesignTools, generated from scripts/CAD/tool_atlas.json) -// declares every one, its menu item, handler, access, tool block and the items folded into it; kSilentForms binds a -// block to the function that runs it. register_cad_commands() makes a command of each entry that is one -// (is_design_command()): a call with the arguments that choose one of its items does what that menu item does -// (opened_item(), open_tool()), and any other has run_cad_tool() run its silent form on the UI thread, through the -// GUI's own CadDocument and DesignPanel's mcp_* hooks, behind the Design tab's busy and stale-id checks -// (cad_gate()). - -#include "McpToolsCad.hpp" -#include "libslic3r/Point.hpp" -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include // OCCT base error - -#include "slic3r/GUI/GUI.hpp" // into_u8 -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/MainFrame.hpp" -#include "slic3r/GUI/Plater.hpp" -#include "slic3r/GUI/GUI_ObjectList.hpp" -#include "slic3r/GUI/ObjectDataViewModel.hpp" // itObject -#include "slic3r/GUI/GLCanvas3D.hpp" -#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "McpArguments.hpp" -#include "McpTools.hpp" -#include "McpPaths.hpp" -#include "UiInspector.hpp" // gizmo_name: the name app_state reports -#include "slic3r/GUI/CAD/DesignPanel.hpp" -#include "slic3r/GUI/CAD/DesignCanvas.hpp" -#include "slic3r/GUI/CAD/DesignSketchTool.hpp" -#include "slic3r/GUI/CAD/DesignOffer.hpp" // the Design table: every command's menu item, handler and tool block - -#include "libslic3r/CAD/CadDocument.hpp" -#include "libslic3r/CAD/SketchEngine.hpp" -#include "libslic3r/CAD/SketchSolver.hpp" -#include "libslic3r/CAD/GeometryEngine.hpp" -#include "libslic3r/CAD/SketchImport.hpp" // svg_to_regions, transform_regions -#include "libslic3r/CAD/ThreadStandards.hpp" -#include "libslic3r/TriangleMesh.hpp" -#include "libslic3r/Model.hpp" -#include "libslic3r/Color.hpp" -#include "libslic3r/format.hpp" -#include "libslic3r/Format/OBJ.hpp" -#include "libslic3r_version.h" -#include -#include -#include -#include -#include "libslic3r/BoundingBox.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace Slic3r { namespace GUI { namespace Mcp { - -namespace { - -const char* feature_type_name(CadFeatureType t) -{ - switch (t) { - case CadFeatureType::Sketch: return "Sketch"; - case CadFeatureType::Extrude: return "Extrude"; - case CadFeatureType::Fillet: return "Fillet"; - case CadFeatureType::Chamfer: return "Chamfer"; - case CadFeatureType::Hole: return "Hole"; - case CadFeatureType::Thread: return "Thread"; - case CadFeatureType::Shell: return "Shell"; - case CadFeatureType::Revolve: return "Revolve"; - case CadFeatureType::Sweep: return "Sweep"; - case CadFeatureType::Pattern: return "Pattern"; - case CadFeatureType::Plane: return "Plane"; - case CadFeatureType::Loft: return "Loft"; - case CadFeatureType::Draft: return "Draft"; - case CadFeatureType::Import: return "Import"; - case CadFeatureType::Boolean: return "Boolean"; - case CadFeatureType::Cut: return "Cut"; - case CadFeatureType::Mirror: return "Mirror"; - case CadFeatureType::Axis: return "Axis"; - case CadFeatureType::CoordSys: return "CoordSys"; - case CadFeatureType::Helix: return "Helix"; - case CadFeatureType::Transform: return "Transform"; - case CadFeatureType::Thicken: return "Thicken"; - case CadFeatureType::Project: return "Project"; - case CadFeatureType::DeleteFace: return "DeleteFace"; - case CadFeatureType::Rib: return "Rib"; - case CadFeatureType::SurfaceExtrude: return "SurfaceExtrude"; - case CadFeatureType::SurfaceRevolve: return "SurfaceRevolve"; - case CadFeatureType::ThickenSurface: return "ThickenSurface"; - case CadFeatureType::SurfaceOffset: return "SurfaceOffset"; - case CadFeatureType::SurfaceLoft: return "SurfaceLoft"; - case CadFeatureType::SurfaceFill: return "SurfaceFill"; - case CadFeatureType::Mate: return "Mate"; - } - return "Unknown"; -} - -// --- What the commands' descriptions and schemas add to the Design table --------------- - -// The `generation` property of every Design command with a silent form: how face and edge ids expire, and -// how a call keeps from acting on a stale one. -const char* const kGenerationNote = - "The generation (describe_design, body_describe) the face and edge ids this call passes were read at. Ids " - "expire when a feature rebuilds the model, and a stale id still names a real face or edge: with the " - "generation, a call whose ids were read before the model changed is refused."; - -// How a silent form whose entry has ok_false reports a rebuild the kernel rejects. -const char* const kFailureNote = "A rejected rebuild is reported in the reply: ok is false or error is not empty."; - -// The rest of the description of a command whose entry has a handler and no silent form, after its hint and -// before mode_note(). -const char* const kOpensToolNote = - "It takes no arguments and does what the Design tab's right-click menu item does, as a person's pick does: open " - "a tool, start a sketch tool, act at once, or tell the person why it cannot. The reply's status is what the " - "tab's status line shows then."; - -// The `silent` property of a command whose call with no arguments opens a tool, before mode_note() of that tool's -// item. -const char* const kSilentNote = - "true runs the tool with the other arguments and opens nothing. A call with no arguments does what the Design " - "tab's menu item does, as a person's pick does."; - -// The mode an entry with a handler runs in, as the Design tab's right-click menu offers it (offered_in_mode()). -// A sketch being constrained counts as open, and refuses sketch_finish and sketch_cancel: the tab's own Confirm -// and Cancel buttons end it. A call that takes no arguments runs only there; `no_arguments` words it for the call -// with no arguments of a command that also runs from arguments, whose argument form may run in the other mode -// (sketch_text, sketch_project). -std::string mode_note(const DesignTool& t, bool no_arguments = false) -{ - return std::string(no_arguments ? "Called with no arguments, it runs only " : "It runs only ") + - (t.sketch_mode ? "in an open sketch (sketch_create opens one)." - : "outside a sketch (sketch_finish or sketch_cancel ends one; while the tab constrains a sketch, " - "its Confirm or Cancel button ends that)."); -} - -// cad_note()'s text, given while the feature is off and while it is on but was off at startup. The -// catalog holds the Design commands only when the feature was on at startup (the preference, or the command -// line's --cad), and the main window creates the Design page only then too (its panel is built on first use), -// so turning the feature on takes a restart. -const char* const kCadOffNote = "tool_call runs no Design command now: they need the CAD feature on when OrcaSlicer " - "started, in Preferences > Features or with --cad. A person turns it on there if it is " - "off and restarts OrcaSlicer, or starts it with --cad."; - -// Why a catalog built without the Design commands leaves them out, after "Unknown tool: ; " or an action's -// " is a Design tab action, and " (unknown_action()): in the editor the CAD feature was off at startup; the -// G-code viewer has no Design tab whatever the preference says. -const char* const kCadOffAtStartup = "the CAD feature was off when OrcaSlicer started: a person turns it on in " - "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"; -const char* const kNoDesignInViewer = "the G-code viewer has no Design tab: a person opens the project in OrcaSlicer's editor"; -// cad_gate()'s refusal while the CAD feature is off in a run that started with it on. -const char* const kCadOffNow = "The CAD feature is off; enable it in Preferences > Features and restart OrcaSlicer"; - -// The details of a ToolFailure a silent form passes on, with invalid_argument as their code where they name no cause, -// as a plain exception a silent form throws reads (run_guarded(), add_feature()). -json with_code(json details) -{ - if (!details.is_object()) - details = json::object(); - if (!details.contains("code")) - details["code"] = "invalid_argument"; - return details; -} - -// What describe_design and select_geometry say is selected. The selection: what the right-click menu would be built -// for, its kind (an OfferSel) and its id in the atlas, which the entries' accepts name. -json selection_json(const DesignPanel& panel) -{ - const int kind = panel.mcp_offer_selection_kind(); - return json{{"kind", kind}, {"id", kDesignSelectionIds[kind]}}; -} - -// The reference plane picked in the view, which the next Sketch opens on: "XY", "XZ", "YZ" or null. -json picked_plane_json(const DesignPanel& panel) -{ - static const char* const names[] = {"XY", "XZ", "YZ"}; - const int plane = panel.mcp_picked_plane(); - return plane >= 0 ? json(names[plane]) : json(); -} - -// The selected row of the Feature list, a feature index, which the menu items that act on it take while nothing is picked -// in the view; or null. -json feature_row_json(const DesignPanel& panel) -{ - const int row = panel.mcp_feature_row(); - return row >= 0 ? json(row) : json(); -} - -// Where body `b` stands for Commit to Plate and Export STEP (body_place, the Move gizmo, Place on Face): null where the -// model has it, else three rows of four numbers, the rotation and the translation in mm, in the world frame. -json placement_json(const DesignPanel& panel, int b) -{ - const Transform3d t = panel.mcp_body_placement(b); - if (t.isApprox(Transform3d::Identity())) return json(); - json rows = json::array(); - for (int r = 0; r < 3; ++r) - rows.push_back(json::array({t(r, 0), t(r, 1), t(r, 2), t(r, 3)})); - return rows; -} - -json describe_design(DesignPanel* panel) -{ - CadDocument& doc = panel->mcp_doc(); - - json features = json::array(); - for (size_t i = 0; i < doc.features.size(); ++i) { - const CadFeature& f = doc.features[i]; - json jf{{"index", int(i)}, {"type", feature_type_name(f.type)}, {"name", f.name}, {"suppressed", !f.enabled}}; - // The fields an expression drives: feature_edit refuses them, feature_describe has the expressions. - if (!f.expr.empty()) { - json bound = json::array(); - for (const auto& kv : f.expr) bound.push_back(kv.first); - jf["bound"] = std::move(bound); - } - features.push_back(std::move(jf)); - } - - // A variable that does not evaluate leaves every value null; the error says why. - std::string var_error; - const std::map values = doc.variable_values(var_error); - json variables = json::array(); - for (const auto& [name, expr] : doc.variables) { - const auto v = values.find(name); - variables.push_back(json{{"name", name}, {"expr", expr}, {"value", v != values.end() ? json(v->second) : json()}}); - } - - const DesignCanvas* vp = panel->mcp_viewport(); - json bodies = json::array(); - for (size_t i = 0; i < doc.bodies.size(); ++i) { - // The user's name when the body has one, the derived maker name otherwise — the same - // rule the Bodies row shows, so a driver and a person read the same thing. - json b{{"index", int(i)}, - {"name", doc.bodies[i].has_user_name ? doc.bodies[i].user_name : doc.bodies[i].name}, - {"user_name", doc.bodies[i].has_user_name}, - {"has_color", doc.bodies[i].has_color}, - {"source_feature", doc.bodies[i].source_feature}, - {"visible", panel->mcp_body_shown(int(i))}, - // Where it stands (body_place, the Move gizmo, Place on Face), which bbox, the recipe's body, does not - // include. - {"moved", panel->mcp_body_moved(int(i))}, - {"placement", placement_json(*panel, int(i))}}; - // The colour the canvas draws: the override when has_color, else the automatic one. - if (vp != nullptr) b["color"] = encode_color(vp->body_color(int(i))); - // Per-body bbox/centre from the already-tessellated display meshes. - if (i < doc.display_body_meshes.size() && !doc.display_body_meshes[i].empty()) { - BoundingBoxf3 bb = doc.display_body_meshes[i].bounding_box(); - b["bbox"] = json{{"min", {bb.min.x(), bb.min.y(), bb.min.z()}}, - {"max", {bb.max.x(), bb.max.y(), bb.max.z()}}}; - Vec3d c = bb.center(); - b["center"] = {c.x(), c.y(), c.z()}; - } - bodies.push_back(std::move(b)); - } - - json out{ - {"modeling_origin", {doc.modeling_origin.x(), doc.modeling_origin.y(), doc.modeling_origin.z()}}, - {"features", std::move(features)}, - {"variables", std::move(variables)}, - {"bodies", std::move(bodies)}, - {"error", doc.error}, - // Pass this back as "generation" on any call that takes a face or edge id and the call - // is refused if the topology has moved on. See the stale-id guard in cad_gate(). - {"generation", doc.topo_generation}, - {"undo_depth", doc.undo_depth()}, - {"redo_depth", doc.redo_depth()}, - // Whether sketch endpoints that nearly meet are welded: the document's rule, which changes - // the loops sketch_draw's entities make. - {"auto_close_loops", doc.auto_close_loops}, - }; - out["selection"] = selection_json(*panel); - out["picked_plane"] = picked_plane_json(*panel); - out["feature_row"] = feature_row_json(*panel); - // The Commit button's mode, which commit_to_plate uses when given none. - out["commit_mode"] = panel->commit_mode() == DesignPanel::CommitMode::Bodies ? "bodies" : "assembly"; - if (!var_error.empty()) out["variables_error"] = var_error; - // The aligns (Mate features) that cannot hold with those before them. - if (!doc.mate_conflicts.empty()) { - json conflicts = json::array(); - for (const auto& [feature, reason] : doc.mate_conflicts) - conflicts.push_back(json{{"feature", feature}, {"reason", reason}}); - out["align_conflicts"] = std::move(conflicts); - } - return out; -} - -// --- Measure layer (read-only "evidence" half of the RE loop) ------------------ -inline json vec3(const Vec3d& v) { return json::array({v.x(), v.y(), v.z()}); } - -// Shared Build helpers. - -// The kinds body_describe gives faces, in GeomAbs_SurfaceType order, and edges. -const char* const kFaceKinds[] = {"planar", "cylindrical", "conical", "spherical", "toroidal", "bezier", - "bspline", "revolution", "extrusion", "offset", "other"}; -static_assert(std::size(kFaceKinds) == size_t(GeomAbs_OtherSurface) + 1, "every surface type needs a kind"); -const char* const kEdgeKinds[] = {"line", "circle", "ellipse", "bspline", "bezier", "other"}; - -int edge_kind(GeomAbs_CurveType t) -{ - switch (t) { - case GeomAbs_Line: return 0; - case GeomAbs_Circle: return 1; - case GeomAbs_Ellipse: return 2; - case GeomAbs_BSplineCurve: return 3; - case GeomAbs_BezierCurve: return 4; - default: return 5; - } -} - -// What kind of surface a face is, for the messages that refuse one. -const char* face_kind_name(const TopoDS_Face& f) { return kFaceKinds[BRepAdaptor_Surface(f).GetType()]; } -const char* edge_kind_name(const TopoDS_Edge& e) { return kEdgeKinds[edge_kind(BRepAdaptor_Curve(e).GetType())]; } - -// A shown Plane feature's place among the datum planes: the kernel lists the enabled Plane features -// in order, and a datum reference holds 3 + that position. -int datum_ordinal(const CadDocument& doc, int fi) -{ - int ordinal = 0; - for (int i = 0; i < fi; ++i) - if (doc.features[i].type == CadFeatureType::Plane && doc.features[i].enabled) ++ordinal; - return ordinal; -} - -// Every reply that used a plane says where it was: a face plane's x axis is not something a caller -// can guess, and the XZ base plane is left-handed (x cross y is -normal), as the GUI stores it. -json frame_json(const SketchPlane& p) -{ - return json{{"origin", vec3(p.origin)}, {"normal", vec3(p.normal)}, - {"x_axis", vec3(p.x_axis)}, {"y_axis", vec3(p.y_axis)}}; -} - -// A plane's frame, with `base` when it is the XY, XZ or YZ plane through the modeling origin -// (whatever its origin within that plane): the name the plane list gives it. -json plane_json(const SketchPlane& p, const Vec3d& modeling_origin) -{ - json j = frame_json(p); - const std::pair bases[] = {{"XY", SketchPlane::XY()}, {"XZ", SketchPlane::XZ()}, {"YZ", SketchPlane::YZ()}}; - for (const auto& [name, b] : bases) - if ((p.normal - b.normal).norm() < 1e-9 && (p.x_axis - b.x_axis).norm() < 1e-9 && - (p.y_axis - b.y_axis).norm() < 1e-9 && std::abs((p.origin - modeling_origin).dot(b.normal)) < 1e-6) - j["base"] = name; - return j; -} - -// Adds features as a card's Confirm does: one undo step, a rebuild, the tree and status refreshed. -// `add` creates them and returns the index reported under `index_key`. A rebuild that fails, or an -// `add` that throws, leaves the document as it was with nothing to redo, puts "Edit rejected" on -// the status line as a refused GUI edit does, and fails the call with the kernel's reason, so the -// failed call can be left out of an exported replay. The error's code tells the causes apart, as -// run_guarded() does: rebuild_failed for a rebuild that reports failure, kernel_failure, precondition or -// invalid_argument, or the code of a ToolFailure `add` throws. -// `slow` rebuilds as the cards do, off the UI thread behind the progress dialog (recompute_guarded), -// for features whose helical pipes and skins can take seconds: the window keeps painting and -// inspection calls keep answering meanwhile, while the rebuild refuses every Design call. -json add_feature(DesignPanel* panel, const char* index_key, const std::function& add, bool slow = false) -{ - CadDocument& doc = panel->mcp_doc(); - doc.checkpoint(); - int idx = -1; - std::string why; - json details = {{"code", "rebuild_failed"}}; - try { - idx = add(); - if (!(slow ? panel->recompute_guarded(_L("Rebuilding model…")) : doc.recompute())) - why = doc.error.empty() ? "the model could not be rebuilt" : doc.error; - } catch (const ToolFailure& ex) { // a refusal with its own code, such as no_design_view() - why = ex.what(); - details = with_code(ex.details); - } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it - why = std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"); - details = {{"code", "kernel_failure"}}; - } catch (const CadKernelFailure& ex) { - why = std::string("OCCT: ") + ex.what(); - details = {{"code", "kernel_failure"}}; - } catch (const CadPrecondition& ex) { - why = ex.what(); - details = {{"code", "precondition"}}; - } catch (const std::exception& ex) { - why = *ex.what() ? ex.what() : "the feature could not be added"; - details = {{"code", "invalid_argument"}}; - } - if (!why.empty()) { - doc.rollback(); - doc.error = why; // the rollback's rebuild cleared it; the status line reads it - panel->mcp_after_change(false); - throw ToolFailure(why, std::move(details)); - } - panel->mcp_after_change(); - return json{{"ok", true}, {index_key, idx}, {"bodies", int(doc.bodies.size())}}; -} - -// What a feature's result does to the bodies already there, in BooleanMode order: the commands' `operation`, in the -// words of Fusion's dialogs and the Extrude card. -const char* const kOperations[] = {"new_body", "join", "cut", "intersect"}; - -// The operations each command takes (operation_arg()): extrude's, auto among them; revolve's, sweep's and loft's; -// boolean's, which combines two bodies there and makes none; mirror's, which keeps its image apart or joins it. -const std::vector kExtrudeOperations = {"auto", "new_body", "join", "cut", "intersect"}; -const std::vector kSolidOperations = {"new_body", "join", "cut", "intersect"}; -const std::vector kBooleanOperations = {"join", "cut", "intersect"}; -const std::vector kMirrorOperations = {"new_body", "join"}; - -// The `operation` argument: one of the words `takes` lists, "auto" coming back empty; `def` when the call leaves it -// out or gives null, and with no `def` the call must give one. -std::optional operation_arg(const json& params, const char* def, const std::vector& takes) -{ - json v = params.value("operation", json()); - if (v.is_null() && def != nullptr) v = def; - const std::string word = v.is_string() ? v.get() : std::string(); - if (std::find(takes.begin(), takes.end(), word) != takes.end()) { - if (word == "auto") return std::nullopt; - for (size_t i = 0; i < std::size(kOperations); ++i) - if (word == kOperations[i]) return BooleanMode(i); - } - std::string list; - for (size_t i = 0; i < takes.size(); ++i) - list += (i == 0 ? "" : i + 1 == takes.size() ? " or " : ", ") + takes[i]; - throw std::runtime_error("operation must be " + list); -} - -// Optional explicit closed profile: params["profile"] = [[x,y],...] in plane mm. -// This is the Measure->Build bridge — feed a measured contour straight back. -// An empty array is the row's default and means no profile. -bool profile_from(const json& params, SketchProfile& out) -{ - if (!params.contains("profile") || params["profile"].empty()) return false; - out.points.clear(); - for (const auto& p : params["profile"]) out.points.emplace_back(p[0].get(), p[1].get()); - out.closed = true; - if (out.points.size() < 3) throw std::runtime_error("profile needs at least 3 points [x, y]"); - return true; -} - -// Resolve body index -> shape, throwing a clear error if out of range / null. -const TopoDS_Shape& body_shape(const CadDocument& doc, const json& params) -{ - int idx = params.value("body", 0); - if (idx < 0 || idx >= int(doc.bodies.size())) - throw std::runtime_error("body index out of range (have " + std::to_string(doc.bodies.size()) + ")"); - if (doc.bodies[idx].shape.IsNull()) - throw CadPrecondition("body has no shape"); - return doc.bodies[idx].shape; -} - -json body_describe(DesignPanel* panel, const json& params) { return cad_body_describe(panel->mcp_doc(), params); } - -json measure(DesignPanel* panel, const json& params) { return cad_measure(panel->mcp_doc(), params); } - -json body_mass_properties(DesignPanel* panel, const json& params) -{ - const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); - auto mp = GeometryEngine::mass_properties(shape); - if (!mp.valid) throw CadKernelFailure("mass properties could not be computed"); - // A sheet body has no volume and no inertia. Report the area and say so, rather than - // returning numbers a caller would reasonably treat as a material check. - if (!mp.is_solid) - return json{ - {"surface_area", mp.surface_area}, - {"volume", 0.0}, - {"is_solid", false}, - {"valid", mp.valid}, - {"note", "sheet body (open shell): it encloses no material, so volume and inertia " - "are not defined; surface_area is exact"}, - }; - return json{ - {"volume", mp.volume}, - {"surface_area", mp.surface_area}, - {"center_of_mass", json::array({mp.center_of_mass.x(), mp.center_of_mass.y(), mp.center_of_mass.z()})}, - {"inertia", mp.inertia}, - {"is_solid", true}, - {"valid", mp.valid}, - }; -} - -// Chain raw section segments (each a sampled-edge polyline) into ordered contours by joining -// endpoints within tol. Grows the tail; when the tail is stuck, reverses the contour and grows -// the other end. A contour is closed when its two ends meet. OCCT section vertices are exact, -// so a small absolute tol suffices. -std::vector, bool>> -chain_segments(std::vector> segs, double tol) -{ - std::vector, bool>> contours; - std::vector used(segs.size(), 0); - auto meets = [&](const Vec3d& a, const Vec3d& b) { return (a - b).norm() <= tol; }; - for (size_t i = 0; i < segs.size(); ++i) { - if (used[i] || segs[i].size() < 2) continue; - used[i] = 1; - std::vector c = segs[i]; - for (int side = 0; side < 2; ) { // grow tail; reverse once when stuck - bool grew = false; - for (size_t j = 0; j < segs.size(); ++j) { - if (used[j] || segs[j].size() < 2) continue; - if (meets(c.back(), segs[j].front())) { - c.insert(c.end(), segs[j].begin() + 1, segs[j].end()); used[j] = 1; grew = true; - } else if (meets(c.back(), segs[j].back())) { - for (auto it = segs[j].rbegin() + 1; it != segs[j].rend(); ++it) c.push_back(*it); - used[j] = 1; grew = true; - } - } - if (grew) { side = 0; continue; } - std::reverse(c.begin(), c.end()); ++side; // try the other end - } - bool closed = c.size() > 2 && meets(c.front(), c.back()); - contours.emplace_back(std::move(c), closed); - } - return contours; -} - -// sections-as-evidence: cross-section of a body by a named base plane at an offset. -json body_section(DesignPanel* panel, const json& params) -{ - const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); - const std::string plane_name = params.value("plane", std::string("XY")); - const double offset = params.value("offset", 0.0); - // Base plane normal; offset shifts the plane along it. - gp_Dir n = plane_name == "XZ" ? gp_Dir(0, 1, 0) - : plane_name == "YZ" ? gp_Dir(1, 0, 0) - : gp_Dir(0, 0, 1); - gp_Pnt o(n.X() * offset, n.Y() * offset, n.Z() * offset); - BRepAlgoAPI_Section sect(shape, gp_Pln(o, n), false); - sect.ComputePCurveOn1(false); - sect.Approximation(true); - sect.Build(); - if (!sect.IsDone()) throw CadKernelFailure("section failed"); - std::vector> segs; - for (TopExp_Explorer ex(sect.Shape(), TopAbs_EDGE); ex.More(); ex.Next()) { - std::vector pts = GeometryEngine::sample_edge_world(TopoDS::Edge(ex.Current())); - if (pts.size() >= 2) segs.push_back(std::move(pts)); - } - const int raw = int(segs.size()); - auto contours = chain_segments(std::move(segs), 1e-3); - json jcont = json::array(); - int closed_n = 0; - for (auto& pc : contours) { - if (pc.second) ++closed_n; - json pts = json::array(); - for (const Vec3d& p : pc.first) pts.push_back(vec3(p)); - jcont.push_back(json{{"closed", pc.second}, {"points", std::move(pts)}}); - } - return json{{"body", params.value("body", 0)}, {"plane", plane_name}, {"offset", offset}, - {"segment_count", raw}, {"contour_count", int(contours.size())}, - {"closed_count", closed_n}, {"contours", std::move(jcont)}}; -} - -// A file the call reads, checked as every path the MCP server takes: absolute UTF-8 (a relative -// one would resolve against the GUI's working directory) and existing. Returns its UTF-8 form. -std::string input_path(const json& value, const std::string& what) -{ - if (!value.is_string()) throw std::runtime_error(what + " must be an absolute path"); - std::string err; - const auto path = Mcp::resolve_input_path(value.get(), err); - if (!path) throw std::runtime_error(err); - return Mcp::path_to_utf8(*path); -} - -// --- Build: bring a reference part in (Import STEP as native B-rep bodies) ------ -json import_step(DesignPanel* panel, const json& params) -{ - if (!params.contains("path")) throw std::runtime_error("import_step needs 'path'"); - const std::string path = input_path(params["path"], "path"); - std::string err; - std::vector solids = GeometryEngine::read_step_solids(path, err); - if (solids.empty()) throw std::runtime_error(err.empty() ? "no solids in STEP" : err); - - CadDocument& doc = panel->mcp_doc(); - doc.checkpoint(); - int first = int(doc.features.size()); - for (const TopoDS_Shape& s : solids) { - CadFeature f; - f.type = CadFeatureType::Import; - f.name = panel->mcp_feature_name("STEP"); - f.imported_solid = s; - f.mode = BooleanMode::New; // each solid = its own coexisting body - doc.features.push_back(f); - } - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"imported", int(solids.size())}, {"first_feature", first}, - {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -// --- Import a triangle mesh as a B-rep body (GeometryEngine::mesh_to_brep) --- -// Same destination as import_step: a CadFeatureType::Import body every feature tool can edit. -// The full conversion stats come back so a caller can tell an honest solid from an open shell -// instead of discovering it later when a boolean silently fails. -json import_mesh(DesignPanel* panel, const json& params) -{ - if (!params.contains("path")) throw std::runtime_error("import_mesh needs 'path'"); - const std::string path = input_path(params["path"], "path"); - const double tolerance = params.value("tolerance", 0.01); - const double merge_angle_deg = params.value("merge_angle_deg", 5.0); - - TriangleMesh mesh; - const std::string ext = boost::algorithm::to_lower_copy( - boost::filesystem::path(path).extension().string()); - if (ext == ".stl") { - if (!mesh.ReadSTLFile(path.c_str())) throw std::runtime_error("could not read STL: " + path); - } else if (ext == ".obj") { - ObjInfo obj_info; std::string obj_err; - if (!load_obj(path.c_str(), &mesh, obj_info, obj_err)) - throw std::runtime_error("could not read OBJ: " + obj_err); - } else { - throw std::runtime_error("unsupported mesh format (want .stl or .obj): " + ext); - } - - GeometryEngine::MeshBrepStats st; - const TopoDS_Shape shape = GeometryEngine::mesh_to_brep(mesh.its, tolerance, merge_angle_deg, st); - if (shape.IsNull()) throw std::runtime_error("mesh conversion produced no geometry"); - - CadDocument& doc = panel->mcp_doc(); - doc.checkpoint(); - const int first = int(doc.features.size()); - CadFeature f; - f.type = CadFeatureType::Import; - f.name = panel->mcp_feature_name(_L("Mesh")); - f.imported_solid = shape; - f.mode = BooleanMode::New; - doc.features.push_back(f); - - const bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"first_feature", first}, {"bodies", int(doc.bodies.size())}, - {"input_triangles", st.input_tris}, {"kept_triangles", st.kept_tris}, - {"degenerate_collapsed", st.degenerate_collapsed}, - {"degenerate_sliver", st.degenerate_sliver}, - {"faces_built", st.faces_built}, {"faces_failed", st.faces_failed}, - {"faces_final", st.faces_final}, {"unique_edges", st.unique_edges}, - {"boundary_edges", st.boundary_edges}, - {"nonmanifold_edges", st.nonmanifold_edges}, - {"watertight", st.watertight}, {"is_solid", st.is_solid}, - {"volume", st.volume}, {"error", doc.error}}; -} - -// --- Validate: volume + bbox deviation of a body vs a reference (the "scarto %") -- -// ponytail: volume delta + bbox/centroid offset (the RE skill's actual acceptance metric). -// Surface-deviation heat-map is the upgrade path (per-vertex BRepExtrema), add when needed. -struct ShapeMetrics { double volume; Vec3d centroid, bmin, bmax; }; -ShapeMetrics shape_metrics(const TopoDS_Shape& s) -{ - GProp_GProps vp; BRepGProp::VolumeProperties(s, vp); - gp_Pnt c = vp.CentreOfMass(); - Bnd_Box bb; BRepBndLib::Add(s, bb); - double x0, y0, z0, x1, y1, z1; bb.Get(x0, y0, z0, x1, y1, z1); - return {vp.Mass(), Vec3d(c.X(), c.Y(), c.Z()), Vec3d(x0, y0, z0), Vec3d(x1, y1, z1)}; -} - -json body_compare(DesignPanel* panel, const json& params) -{ - const TopoDS_Shape& cand = body_shape(panel->mcp_doc(), params); // candidate = the reconstruction - if (!params.contains("reference")) throw std::runtime_error("body_compare needs 'reference' {step|body}"); - const json& r = params["reference"]; - - TopoDS_Shape ref; - if (r.contains("step")) { - std::string err; - std::vector solids = GeometryEngine::read_step_solids(input_path(r["step"], "reference.step"), err); - if (solids.empty()) throw std::runtime_error(err.empty() ? "reference STEP has no solids" : err); - BRep_Builder b; TopoDS_Compound comp; b.MakeCompound(comp); - for (const TopoDS_Shape& s : solids) if (!s.IsNull()) b.Add(comp, s); - ref = comp; - } else if (r.contains("body")) { - CadDocument& doc = panel->mcp_doc(); - int idx = r["body"].get(); - if (idx < 0 || idx >= int(doc.bodies.size()) || doc.bodies[idx].shape.IsNull()) - throw std::runtime_error("reference body index out of range / null"); - ref = doc.bodies[idx].shape; - } else { - throw std::runtime_error("reference must be {\"step\": path} or {\"body\": id}"); - } - - ShapeMetrics a = shape_metrics(cand), b = shape_metrics(ref); - double dv = b.volume > 0 ? (a.volume - b.volume) / b.volume * 100.0 : 0.0; - Vec3d coff = a.centroid - b.centroid; - Vec3d dmin = a.bmin - b.bmin, dmax = a.bmax - b.bmax; - // Surface-level deviation (one-sided Hausdorff, candidate vertices -> reference solid): - // catches local shape error that matching volume + bbox can hide. - GeometryEngine::Deviation dev = GeometryEngine::surface_deviation(cand, ref); - return json{ - {"volume", a.volume}, {"volume_reference", b.volume}, {"volume_delta_pct", dv}, - {"centroid_offset", vec3(coff)}, {"centroid_offset_mm", coff.norm()}, - {"bbox", json{{"min", vec3(a.bmin)}, {"max", vec3(a.bmax)}}}, - {"bbox_reference", json{{"min", vec3(b.bmin)}, {"max", vec3(b.bmax)}}}, - {"bbox_delta", json{{"min", vec3(dmin)}, {"max", vec3(dmax)}}}, - {"surface_deviation", json{{"max_mm", dev.max_mm}, {"mean_mm", dev.mean_mm}, - {"rms_mm", dev.rms_mm}, {"samples", dev.sample_count}}}, - }; -} - -// Resolve an optional explicit body target. Default (no `body`, or <0) = last body, which is -// what the kernel picks anyway. Validated BEFORE any checkpoint so a bad index throws clean. -int target_body_arg(const json& params, const CadDocument& doc) -{ - int bi = params.value("body", -1); - if (bi >= int(doc.bodies.size())) - throw std::runtime_error("body index out of range (have " + std::to_string(doc.bodies.size()) + ")"); - return bi; // <0 -> kernel uses the last body -} - -// `edges` is one id or an array of ids; an array becomes ONE feature, every id resolved -// against the same body (a chain of single-edge features would see the ids drift). -std::vector edge_ids_arg(const json& params, const char* verb) -{ - if (!params.contains("edges")) - throw std::runtime_error(std::string(verb) + " needs 'edges' (an id or array of ids from body_describe)"); - const json& e = params["edges"]; - std::vector ids; - if (e.is_array()) for (const json& v : e) ids.push_back(v.get()); - else ids.push_back(e.get()); - if (ids.empty()) throw std::runtime_error(std::string(verb) + ": 'edges' is an empty array"); - return ids; -} - -// fillet and chamfer: the Fillet and Chamfer cards' Confirm on picked edges. -json action_dressup(DesignPanel* panel, const json& params, bool chamfer) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_dressup(doc, params, chamfer); - const char* key = chamfer ? "chamfer_index" : "fillet_index"; - json r = add_feature(panel, key, [&] { return add(panel->mcp_feature_name(chamfer ? _L("Chamfer") : _L("Fillet"))); }); - const int target = doc.features[r.at(key).get()].target_body; - r["body"] = target >= 0 ? target : int(doc.bodies.size()) - 1; - return r; -} - -json action_fillet(DesignPanel* panel, const json& params) { return action_dressup(panel, params, false); } -json action_chamfer(DesignPanel* panel, const json& params) { return action_dressup(panel, params, true); } - -// The Hole card's Confirm; the reply says where the hole went (cad_hole_placement) and the frame of its plane. -json action_hole(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - json resolved; - const auto add = cad_hole(doc, params, resolved); - json r = add_feature(panel, "hole_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Hole", "Design"))); }); - r.update(resolved); - return r; -} - -json action_boolean(DesignPanel* panel, const json& params) -{ - const BooleanMode m = *operation_arg(params, nullptr, kBooleanOperations); - const int target = params.value("target", 0); - const int tool = params.value("tool", 1); - const bool keep = params.value("keep_tool", false); - const double tol = params.value("tolerance", 0.0); - CadDocument& doc = panel->mcp_doc(); - int n = int(doc.bodies.size()); - if (target < 0 || target >= n || tool < 0 || tool >= n) - throw std::runtime_error("target/tool body index out of range (have " + std::to_string(n) + ")"); - if (target == tool) throw std::runtime_error("target and tool must differ"); - doc.checkpoint(); - int b = doc.add_boolean(m, target, tool, keep, tol, -1, -1, panel->mcp_feature_name(_L("Boolean"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"boolean_index", b}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -// The Pattern card's Confirm: a linear or circular pattern replies with the frame of its plane. -json action_pattern(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_pattern(doc, params); - json r = add_feature(panel, "pattern_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Pattern", "Design"))); }); - const CadFeature& f = doc.features[r.at("pattern_index").get()]; - if (f.pattern_curve_sketch < 0) r["frame"] = frame_json(f.plane); - return r; -} - -json action_shell(DesignPanel* panel, const json& params) -{ - const double thickness = params.value("thickness", 1.0); - if (thickness <= 0) throw std::runtime_error("thickness must be > 0"); - const int face = params.value("face", -1); // face id to leave open (-1 = closed hollow) - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to shell"); - int bi = target_body_arg(params, doc); - doc.checkpoint(); - int s = doc.add_shell(thickness, face, bi, panel->mcp_feature_name(_L_CONTEXT("Shell", "Design"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"shell_index", s}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_rib(DesignPanel* panel, const json& params) -{ - if (!params.contains("sketch")) throw std::runtime_error("rib needs 'sketch' (feature index)"); - if (!params.contains("entity")) throw std::runtime_error("rib needs 'entity' (entity index)"); - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to rib"); - int sketch = params["sketch"].get(); - int entity = params["entity"].get(); - double thickness = params.value("thickness", 2.0); - double depth = params.value("depth", 10.0); - int bi = target_body_arg(params, doc); - doc.checkpoint(); - int idx = doc.add_rib(sketch, entity, thickness, depth, bi, panel->mcp_feature_name(_L_CONTEXT("Rib", "Design"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"rib_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_surface_extrude(DesignPanel* panel, const json& params) -{ - if (!params.contains("sketch")) throw std::runtime_error("surface_extrude needs 'sketch' (feature index)"); - CadDocument& doc = panel->mcp_doc(); - int sketch = params["sketch"].get(); - double distance = params.value("distance", 10.0); - doc.checkpoint(); - int idx = doc.add_surface_extrude(sketch, distance, panel->mcp_feature_name(_L("Surface Extrude"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_surface_revolve(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_surface_revolve(doc, params); - doc.checkpoint(); - int idx = add(panel->mcp_feature_name(_L("Surface Revolve"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_surface_offset(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no sheet body to offset"); - int bi = target_body_arg(params, doc); - double offset = params.value("offset", 1.0); - doc.checkpoint(); - int idx = doc.add_surface_offset(bi, offset, panel->mcp_feature_name(_L("Surface Offset"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_surface_loft(DesignPanel* panel, const json& params) -{ - if (!params.contains("profiles") || !params["profiles"].is_array()) - throw std::runtime_error("surface_loft needs 'profiles' (array of int feature indices)"); - CadDocument& doc = panel->mcp_doc(); - std::vector profiles; - for (const json& j : params["profiles"]) profiles.push_back(j.get()); - bool ruled = params.value("ruled", false); - doc.checkpoint(); - int idx = doc.add_surface_loft(profiles, ruled, panel->mcp_feature_name(_L("Surface Loft"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_surface_patch(DesignPanel* panel, const json& params) -{ - if (!params.contains("sketch")) throw std::runtime_error("surface_patch needs 'sketch' (feature index)"); - CadDocument& doc = panel->mcp_doc(); - int sketch = params["sketch"].get(); - doc.checkpoint(); - int idx = doc.add_surface_fill(sketch, panel->mcp_feature_name(_L("Surface Fill"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_draft(DesignPanel* panel, const json& params) -{ - if (!params.contains("face")) throw std::runtime_error("draft needs 'face' (id from body_describe)"); - const double angle = params.value("angle", 5.0); - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to draft"); - int bi = target_body_arg(params, doc); - doc.checkpoint(); - int d = doc.add_draft(angle, params["face"].get(), bi, panel->mcp_feature_name(_L("Draft"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"draft_index", d}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -// ---- 2D sketch verbs -------------------------------------------------------------------- -// -// The model is FreeCAD's Sketcher, adapted to this tab's right-click world. Three ideas are -// taken over deliberately: -// -// * GEOMETRY IS SEPARATE FROM CONSTRAINTS. You add curves, then you constrain them; the -// solver reports degrees of freedom and whether it is consistent. `sketch_describe` returns -// both halves plus the DoF, which is the whole state a caller needs to reason about. -// * A SKETCH IS JUDGED BY ITS LOOPS, not by its coordinates. FreeCAD asks whether the profile -// is closed before it will build from it; `sketch_describe` answers that directly, listing -// each closed loop, the loops it encloses as VOIDS, and — the actionable part — the exact -// plane coordinates where a chain is still open. -// * VALIDATE, THEN FIX. FreeCAD's ValidateSketch finds vertices that overlap within a -// tolerance but carry no coincidence, and adds the missing ones. `sketch_validate` reports -// them, `sketch_repair` welds and constrains them. That is what turns a loop that is closed by -// floating-point luck into one that is closed by construction and stays closed through -// every later solve. -// -// What is NOT taken over: FreeCAD's Sketcher is a modal dialog with its own toolbars. Here the -// vocabulary is the right-click offer, so these verbs are named after what the menu offers on a -// selection, and every one of them drives the SAME DesignSketchTool the mouse drives. - -DesignSketchTool& mcp_sketch(DesignPanel* panel) -{ - DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - if (!vp->is_sketching()) - throw CadPrecondition("no sketch is open — call sketch_create first"); - return vp->mcp_sketch_tool(); -} - -// An [x, y] point in the sketch plane, named `what` in the error. -Vec2d point_of(const json& v, const std::string& what) -{ - if (!v.is_array() || v.size() != 2 || !v[0].is_number() || !v[1].is_number()) - throw std::runtime_error(what + " must be [x, y]"); - return Vec2d(v[0].get(), v[1].get()); -} - -Vec2d point_arg(const json& j, const char* key) { return point_of(j.value(key, json()), key); } - -// A required finite number. -double number_arg(const json& j, const char* key) -{ - const json v = j.value(key, json()); - if (!v.is_number() || !std::isfinite(v.get())) throw std::runtime_error(std::string(key) + " must be a number"); - return v.get(); -} - -// An angle in radians as `key`, or in degrees as `key`_deg; `def` (radians) when neither is given. -double angle_arg(const json& j, const std::string& key, double def) -{ - const std::string deg = key + "_deg"; - if (j.contains(key) && j.contains(deg)) throw std::runtime_error("give " + key + " or " + deg + ", not both"); - if (j.contains(deg)) return number_arg(j, deg.c_str()) * M_PI / 180.0; - return j.contains(key) ? number_arg(j, key.c_str()) : def; -} - -SketchEntity sketch_entity_from(const json& j) -{ - const std::string t = j.value("type", std::string("")); - SketchEntity e; - auto p = [&](const char* k, double dx, double dy) { - if (!j.contains(k)) return Vec2d(dx, dy); - const json& a = j.at(k); - if (!a.is_array() || a.size() < 2) throw std::runtime_error(std::string(k) + " must be [x, y]"); - return Vec2d(a[0].get(), a[1].get()); - }; - e.construction = j.value("construction", false); - // A circle and an arc are defined BY their centre, so a request that does not carry one is - // incomplete, not a request for a circle at the origin. Defaulting it silently put geometry - // somewhere the caller never asked for and then reported perfectly consistent loops, areas - // and hole attribution ABOUT THAT WRONG GEOMETRY — which is far more expensive to disbelieve - // than an error would have been. A point is its position, for the same reason. - auto centre_of = [&](const char* what) { - if (j.contains("center")) return p("center", 0, 0); - throw std::runtime_error(std::string(what) + " needs a 'center'"); - }; - if (t == "line") { - // Its two ends are the line, so one left out is a mistake (often the key spelled another - // way, start/end), not the origin: a line ending there closes no loop the caller drew. - if (!j.contains("p0") || !j.contains("p1")) - throw std::runtime_error("line needs 'p0' and 'p1' as [x, y]"); - e.type = SketchEntity::Type::Line; - e.p0 = p("p0", 0, 0); e.p1 = p("p1", 0, 0); - } else if (t == "circle_center") { - e.type = SketchEntity::Type::Circle; - e.center = centre_of("circle_center"); - e.radius = j.value("radius", 0.0); - e.p0 = e.center; - if (e.radius <= 0.0) throw std::runtime_error("circle_center needs a positive 'radius'"); - } else if (t == "arc_center") { - e.type = SketchEntity::Type::Arc; - e.center = centre_of("arc_center"); - e.radius = j.value("radius", 0.0); - e.start_angle = angle_arg(j, "start_angle", 0.0); - e.end_angle = angle_arg(j, "end_angle", 0.0); - if (e.radius <= 0.0) throw std::runtime_error("arc_center needs a positive 'radius'"); - e.p0 = e.center + e.radius * Vec2d(std::cos(e.start_angle), std::sin(e.start_angle)); - e.p1 = e.center + e.radius * Vec2d(std::cos(e.end_angle), std::sin(e.end_angle)); - } else if (t == "point") { - e.type = SketchEntity::Type::Point; - e.p0 = point_arg(j, "p"); - } else { - throw std::logic_error("sketch_entity_from takes a line, circle_center, arc_center or point, not " + t); - } - return e; -} - -json sketch_entity_to(const SketchEntity& e, int index) -{ - json j{{"index", index}, {"construction", e.construction}}; - switch (e.type) { - case SketchEntity::Type::Line: - j["type"] = "line"; - j["p0"] = json::array({e.p0.x(), e.p0.y()}); - j["p1"] = json::array({e.p1.x(), e.p1.y()}); - j["length"] = (e.p1 - e.p0).norm(); - break; - case SketchEntity::Type::Circle: - j["type"] = "circle"; - j["center"] = json::array({e.center.x(), e.center.y()}); - j["radius"] = e.radius; - break; - case SketchEntity::Type::Arc: - j["type"] = "arc"; - j["center"] = json::array({e.center.x(), e.center.y()}); - j["radius"] = e.radius; - j["start_angle"] = e.start_angle; - j["end_angle"] = e.end_angle; - j["p0"] = json::array({e.p0.x(), e.p0.y()}); - j["p1"] = json::array({e.p1.x(), e.p1.y()}); - break; - case SketchEntity::Type::Point: - j["type"] = "point"; - j["p"] = json::array({e.p0.x(), e.p0.y()}); - break; - // Ellipses and splines serialise every parameter they have, not just a type name: this is - // the only read-back the project has, and from a bare type name a caller could only count - // them and grade the faceted area of the loop they close (2e-2, the faceting error), never - // check a single axis, angle or pole. A precise definition of every aspect cannot be - // asserted about an entity whose aspects the read-back does not show. - case SketchEntity::Type::Ellipse: - j["type"] = "ellipse"; - j["center"] = json::array({e.center.x(), e.center.y()}); - j["radius"] = e.radius; // semi-major (a) - j["rminor"] = e.rminor; // semi-minor (b) - j["rotation"] = e.rotation; // major-axis angle, radians - break; - case SketchEntity::Type::EllipseArc: - j["type"] = "ellipse_arc"; - j["center"] = json::array({e.center.x(), e.center.y()}); - j["radius"] = e.radius; - j["rminor"] = e.rminor; - j["rotation"] = e.rotation; - j["start_angle"] = e.start_angle; - j["end_angle"] = e.end_angle; - j["p0"] = json::array({e.p0.x(), e.p0.y()}); - j["p1"] = json::array({e.p1.x(), e.p1.y()}); - break; - case SketchEntity::Type::BSpline: { - j["type"] = "spline"; - json poles = json::array(); - for (const Vec2d& c : e.ctrl) poles.push_back(json::array({c.x(), c.y()})); - j["ctrl"] = poles; - j["p0"] = json::array({e.p0.x(), e.p0.y()}); - j["p1"] = json::array({e.p1.x(), e.p1.y()}); - break; - } - } - return j; -} - -// --- A feature as its card shows it: feature_describe and feature_edit ------------------------ - -// Names in the Design commands' vocabulary, in enum order (BooleanMode's are kOperations). -const char* const kShapes[] = {"rectangle", "circle"}; // SketchShape -const char* const kExtrudeEnds[] = {"blind", "symmetric", "two_sided", "through_all", "up_to_face", "up_to_vertex"}; -const char* const kFaceGroups[] = {"top", "bottom", "lateral", "all"}; -const char* const kPlaneTypes[] = {"offset", "angle", "midplane", "tangent", "two_edges", "coincident"}; -const char* const kAxisTypes[] = {"two_points", "face_normal", "cylinder", "plane_intersection", "along_edge"}; -const char* const kCoordSysTypes[] = {"point_world", "face_and_direction"}; -const char* const kHoleTypes[] = {"simple", "counterbore", "countersink"}; // CadFeature::hole_style -const char* const kAlignTypes[] = {"fastened", "planar", "revolute", "slider", "cylindrical"}; // CadFeature::mate_kind -const char* const kPatternTypes[] = {"linear", "circular", "curve"}; // a Pattern's layout -const char* const kPointRoles[] = {"p0", "p1", "center"}; // SketchPointRole -// SketchConstraintType is append-only (recipes store it by position), and so is this list. -const char* const kConstraintTypes[] = { - "fix", "coincident", "horizontal", "vertical", "distance", "lock_x", "lock_y", "equal_length", "parallel", - "perpendicular", "concentric", "tangent", "midpoint", "symmetric", "angle", "radius", "diameter", "point_on_line", - "point_on_object", "equal_radius", "collinear", "distance_x", "distance_y", "symmetric_about_y", "symmetric_about_x"}; -static_assert(std::size(kConstraintTypes) == size_t(SketchConstraintType::SymmetricAboutX) + 1, - "every constraint type needs a name"); - -// A recipe is read from a file, so an enum value may be one this build has no name for. -template const char* enum_name(const char* const (&names)[N], int i) -{ - return i >= 0 && i < int(N) ? names[i] : "unknown"; -} - -// The position of `v` in `names`, or an error naming the choices. -template int enum_index(const std::string& key, const json& v, const char* const (&names)[N]) -{ - for (size_t i = 0; i < N; ++i) - if (v.is_string() && v.get() == names[i]) return int(i); - std::string list; - for (const char* n : names) list += (list.empty() ? "" : ", ") + std::string(n); - throw std::runtime_error(key + " must be one of " + list); -} - -// The edge group a word names, the Fillet and Chamfer cards' Edges choice, or nothing for any other value. -std::optional face_group_named(const json& v) -{ - for (size_t i = 0; i < std::size(kFaceGroups); ++i) - if (v.is_string() && v.get() == kFaceGroups[i]) return FaceGroup(i); - return std::nullopt; -} -const std::string kFaceGroupWords = "top, bottom, lateral or all"; - -// A constraint's value as the Design commands state it: an angle in degrees (the recipe holds radians), a -// length in mm. Null for the types that carry none. -json constraint_value(SketchConstraintType t, double v) -{ - using T = SketchConstraintType; - switch (t) { - case T::Angle: return v * 180.0 / M_PI; - case T::Distance: case T::DistanceX: case T::DistanceY: case T::LockX: case T::LockY: - case T::Radius: case T::Diameter: case T::PointOnLine: return v; - default: return json(); - } -} - -json constraint_ref(int entity, SketchPointRole role, bool point) -{ - if (entity == kSketchRefOrigin) return json{{"entity", "origin"}}; - if (entity == kSketchRefAxisX) return json{{"entity", "x_axis"}}; - if (entity == kSketchRefAxisY) return json{{"entity", "y_axis"}}; - json r{{"entity", entity}}; - if (point) r["role"] = enum_name(kPointRoles, int(role)); - return r; -} - -// An entity constraint's references, as the solver reads them: a point names its entity and role, -// a whole entity (a line's direction, a circle's radius) only the entity. -json entity_constraint_json(const SketchEntityConstraintDef& c, int index) -{ - using T = SketchConstraintType; - json refs = json::array(); - auto pt = [&](int e, SketchPointRole r) { refs.push_back(constraint_ref(e, r, true)); }; - auto ent = [&](int e) { refs.push_back(constraint_ref(e, SketchPointRole::P0, false)); }; - switch (c.type) { - case T::Fix: case T::LockX: case T::LockY: - pt(c.ea, c.ra); break; - case T::Coincident: case T::Horizontal: case T::Vertical: case T::Distance: case T::DistanceX: - case T::DistanceY: case T::SymmetricAboutY: case T::SymmetricAboutX: - pt(c.ea, c.ra); pt(c.eb, c.rb); break; - case T::Radius: case T::Diameter: - ent(c.ea); break; - case T::Concentric: case T::EqualLength: case T::Parallel: case T::Perpendicular: case T::Angle: - case T::Tangent: case T::EqualRadius: case T::Collinear: - ent(c.ea); ent(c.eb); break; - case T::Midpoint: case T::PointOnLine: case T::PointOnObject: - pt(c.ea, c.ra); ent(c.eb); break; - case T::Symmetric: - pt(c.ea, c.ra); pt(c.eb, c.rb); ent(c.ec); break; - } - json j{{"index", index}, {"type", enum_name(kConstraintTypes, int(c.type))}, {"refs", std::move(refs)}}; - if (json v = constraint_value(c.type, c.value); !v.is_null()) j["value"] = std::move(v); - return j; -} - -// A profile sketch's constraint, on the profile's point indices. -json profile_constraint_json(const SketchConstraintDef& c, int index) -{ - json points = json::array(); - for (int p : {c.a, c.b, c.c, c.d}) - if (p >= 0) points.push_back(p); - json j{{"index", index}, {"type", enum_name(kConstraintTypes, int(c.type))}, {"points", std::move(points)}}; - if (json v = constraint_value(c.type, c.value); !v.is_null()) j["value"] = std::move(v); - return j; -} - -// A feature's card as data. `params` is what the card shows; `editable` the fields its Confirm -// writes, named as the CadFeature members (the names feature_set_expression binds), but for the -// members that hold a variant, read and written under their command's argument in its words: mode -// as `operation` (kOperations), and hole_style, mate_kind and pattern_circular as `type`; `ranges` the limits -// its spin controls set on the numeric ones; `refs` what it refers to (feature and body indices, face -// and edge ids, read in the model before it but for a datum's), which feature_edit's refs re-points -// (cad_apply_feature_refs()); `expr` the bindings. -// feature_describe shows it and feature_edit checks against it, so the two cannot disagree. -json feature_card(const CadFeature& f) -{ - json params = json::object(), ranges = json::object(), refs = json::object(), editable = json::array(); - auto show = [&](const char* k, json v) { params[k] = std::move(v); }; - auto edit = [&](const char* k, json v) { params[k] = std::move(v); editable.push_back(k); }; - auto num = [&](const char* k, double v, double lo, double hi) { edit(k, v); ranges[k] = json::array({lo, hi}); }; - auto ref = [&](const char* k, json v) { refs[k] = std::move(v); }; - using T = CadFeatureType; - switch (f.type) { - case T::Sketch: - if (!f.imported_regions.empty()) { - // Text or SVG art, vectorised once: its placement edits, and a Text feature's words, font and height, - // which feature_edit outlines again. - if (f.is_text()) { - edit("text_string", f.text_string); - edit("text_font", f.text_font); - edit("text_height", f.text_height); - } - show("regions", int(f.imported_regions.size())); - // Per region, its closed loops and the area it fills as placed, in mm². A region keeps its - // outer loop first and its holes after it, so it has 1 + holes loops, and it fills the - // outer loop's area less its holes', times the placement's scale. A glyph or path that - // vectorised into a sliver or with a stray hole shows here, where the region count alone - // does not. - json loops = json::array(), areas = json::array(); - for (const auto& region : f.imported_regions) { - loops.push_back(int(region.size())); - double filled = 0.0; - for (size_t c = 0; c < region.size(); ++c) { - const std::vector& loop = region[c]; - double twice = 0.0; // the shoelace sum: twice the signed area - for (size_t i = 0; i < loop.size(); ++i) { - const Vec2d& a = loop[i]; - const Vec2d& b = loop[(i + 1) % loop.size()]; - twice += a.x() * b.y() - b.x() * a.y(); - } - filled += (c == 0 ? 0.5 : -0.5) * std::abs(twice); - } - areas.push_back(filled * std::abs(f.import_scale_x * f.import_scale_y)); - } - show("region_loops", std::move(loops)); - show("region_areas", std::move(areas)); - edit("import_offset", json::array({f.import_offset.x(), f.import_offset.y()})); - num("import_scale_x", f.import_scale_x, 0.001, 1000); - num("import_scale_y", f.import_scale_y, 0.001, 1000); - if (f.import_on_face) ref("import_face_body", f.import_face_body); - } else if (f.entities.empty() && f.profile.points.empty()) { // the Sketch card's shape - edit("shape", enum_name(kShapes, int(f.shape))); - num("width", f.width, 0.1, 1000); - num("height", f.height, 0.1, 1000); - num("radius", f.radius, 0.1, 1000); - } - break; - case T::Extrude: - num("distance", f.distance, -1000, 1000); - num("distance2", f.distance2, 0, 100000); - num("taper_deg", f.taper_deg, -89, 89); - edit("extrude_end", enum_name(kExtrudeEnds, int(f.extrude_end))); - edit("flip", f.flip); - edit("operation", enum_name(kOperations, int(f.mode))); - ref("sketch_ref", f.sketch_ref); - ref("target_body", f.target_body); - ref("up_to_face", f.up_to_face); - ref("extrude_src_face", f.extrude_src_face); - break; - case T::Revolve: - num("revolve_angle", f.revolve_angle, 1, 360); - edit("revolve_axis", f.revolve_axis); - edit("flip", f.flip); - edit("operation", enum_name(kOperations, int(f.mode))); - ref("sketch_ref", f.sketch_ref); - ref("revolve_axis_entity", f.revolve_axis_entity); - ref("target_body", f.target_body); - break; - case T::Sweep: - edit("operation", enum_name(kOperations, int(f.mode))); - ref("sketch_ref", f.sketch_ref); - ref("sweep_path_ref", f.sweep_path_ref); - ref("target_body", f.target_body); - break; - case T::Loft: - edit("operation", enum_name(kOperations, int(f.mode))); - edit("loft_ruled", f.loft_ruled); - ref("loft_profile_refs", f.loft_profile_refs); - ref("target_body", f.target_body); - break; - case T::Fillet: - case T::Chamfer: - num("dressup_size", f.dressup_size, 0.1, 1000); - ref("edges", f.dressup_edge_ids()); - ref("face_group", enum_name(kFaceGroups, int(f.face_group))); - ref("target_body", f.target_body); - break; - case T::Hole: - num("hole_diameter", f.hole_diameter, 0.1, 1000); - num("hole_depth", f.hole_depth, 0.1, 1000); - edit("hole_through", f.hole_through); - num("hole_x", f.hole_x, -1000, 1000); - num("hole_y", f.hole_y, -1000, 1000); - // The seat, which the card does not show; hole's type and designation set it. - edit("type", enum_name(kHoleTypes, f.hole_style)); - num("hole_cbore_diameter", f.hole_cbore_diameter, 0, 1000); - num("hole_cbore_depth", f.hole_cbore_depth, 0, 1000); - num("hole_csink_diameter", f.hole_csink_diameter, 0, 1000); - num("hole_csink_angle", f.hole_csink_angle, 1, 179); - show("hole_standard", f.hole_standard); - ref("target_body", f.target_body); - break; - case T::Thread: - // The card shows the diameter, the size a thread is named by; either one may be set. - num("thread_diameter", 2.0 * f.thread_radius, 0.1, 1000); - num("thread_radius", f.thread_radius, 0.05, 500); - num("thread_pitch", f.thread_pitch, 0.1, 1000); - num("thread_height", f.thread_height, 0.1, 1000); - num("thread_depth", f.thread_depth, 0.1, 1000); - edit("thread_internal", f.thread_internal); - num("thread_x", f.thread_x, -1000, 1000); - num("thread_y", f.thread_y, -1000, 1000); - ref("target_body", f.target_body); - break; - case T::Shell: - num("shell_thickness", f.shell_thickness, 0.01, 100000); - ref("shell_face", f.shell_face); - ref("target_body", f.target_body); - break; - case T::Draft: - num("draft_angle", f.draft_angle, -89, 89); - ref("draft_face", f.draft_face); - ref("target_body", f.target_body); - break; - case T::Thicken: - num("thicken_thickness", f.thicken_thickness, 0.01, 100000); - edit("thicken_flip", f.thicken_flip); - ref("thicken_face", f.thicken_face); - ref("target_body", f.target_body); - break; - case T::ThickenSurface: - num("thicken_thickness", f.thicken_thickness, 0.01, 100000); - edit("thicken_flip", f.thicken_flip); - ref("target_body", f.target_body); - break; - case T::Pattern: - // A pattern along a curve follows its sketch's entity, which no field changes. - if (f.pattern_curve_sketch >= 0) - show("type", enum_name(kPatternTypes, 2)); - else - edit("type", enum_name(kPatternTypes, f.pattern_circular ? 1 : 0)); - num("pattern_count", f.pattern_count, 1, 999); - num("pattern_spacing", f.pattern_spacing, 0.01, 100000); - edit("pattern_dir", f.pattern_dir); - num("pattern_angle", f.pattern_angle, 1, 360); - ref("pattern_curve_sketch", f.pattern_curve_sketch); - ref("pattern_curve_entity", f.pattern_curve_entity); - ref("target_body", f.target_body); - break; - case T::Boolean: - edit("operation", enum_name(kOperations, int(f.mode))); - edit("bool_keep_tool", f.bool_keep_tool); - num("bool_tolerance", f.bool_tolerance, 0, 100); - ref("target_body", f.target_body); - ref("bool_tool_body", f.bool_tool_body); - ref("bool_target_face", f.bool_target_face); - ref("bool_tool_face", f.bool_tool_face); - break; - case T::Cut: - num("cut_offset", f.cut_offset, -10000, 10000); - edit("cut_flip", f.cut_flip); - edit("cut_keep_upper", f.cut_keep_upper); - edit("cut_keep_lower", f.cut_keep_lower); - ref("cut_face_body", f.cut_face_body); - ref("cut_face", f.cut_face); - ref("target_body", f.target_body); - break; - case T::Mirror: - edit("mirror_keep_original", f.mirror_keep_original); - edit("operation", enum_name(kOperations, int(f.mode))); - ref("target_body", f.target_body); - break; - case T::Transform: - edit("xf_translate", vec3(f.xf_translate)); - edit("xf_axis", vec3(f.xf_axis)); - edit("xf_pivot", vec3(f.xf_pivot)); - num("xf_angle_deg", f.xf_angle_deg, -360, 360); - edit("xf_copy", f.xf_copy); - ref("target_body", f.target_body); - break; - case T::Plane: - num("plane_offset", f.plane_offset, -100000, 100000); - num("plane_angle_tilt", f.plane_angle_tilt, -180, 180); - num("plane_u_size", f.plane_u_size, 1, 100000); - num("plane_v_size", f.plane_v_size, 1, 100000); - ref("plane_type", enum_name(kPlaneTypes, int(f.plane_type))); - ref("plane_base", f.plane_base); - ref("plane_axis", f.plane_axis); - ref("plane_face_body", f.plane_face_body); - ref("plane_face", f.plane_face); - ref("plane_face2_body", f.plane_face2_body); - ref("plane_face2", f.plane_face2); - ref("plane_edge_body", f.plane_edge_body); - ref("plane_edge", f.plane_edge); - ref("plane_edge2_body", f.plane_edge2_body); - ref("plane_edge2", f.plane_edge2); - break; - case T::Helix: - num("helix_radius", f.helix_radius, 0.01, 10000); - num("helix_pitch", f.helix_pitch, 0.01, 10000); - num("helix_height", f.helix_height, 0.01, 10000); - num("helix_taper_deg", f.helix_taper_deg, -89, 89); - edit("helix_left_handed", f.helix_left_handed); - break; - case T::Rib: - num("rib_thickness", f.rib_thickness, 0.01, 100000); - num("rib_depth", f.rib_depth, 0.01, 100000); - ref("rib_sketch_ref", f.rib_sketch_ref); - ref("rib_entity", f.rib_entity); - ref("target_body", f.target_body); - break; - case T::SurfaceExtrude: - num("distance", f.distance, 0.1, 1000); - ref("sketch_ref", f.sketch_ref); - break; - case T::SurfaceRevolve: - num("revolve_angle", f.revolve_angle, 1, 360); - edit("revolve_axis", f.revolve_axis); - edit("flip", f.flip); - ref("sketch_ref", f.sketch_ref); - ref("revolve_axis_entity", f.revolve_axis_entity); - break; - case T::SurfaceOffset: - num("plane_offset", f.plane_offset, -100000, 100000); - ref("target_body", f.target_body); - break; - case T::Mate: - edit("type", enum_name(kAlignTypes, f.mate_kind)); - num("mate_offset", f.mate_offset, -100000, 100000); - num("mate_angle", f.mate_angle, -360, 360); - edit("mate_flip", f.mate_flip); - ref("mate_cs_a", f.mate_cs_a); - ref("mate_cs_b", f.mate_cs_b); - break; - case T::Axis: - ref("axis_type", enum_name(kAxisTypes, int(f.axis_type))); - ref("axis_p1", vec3(f.axis_p1)); - ref("axis_p2", vec3(f.axis_p2)); - ref("axis_body", f.axis_body); - ref("axis_face", f.axis_face); - ref("axis_edge", f.axis_edge); - ref("axis_plane_a", f.axis_plane_a); - ref("axis_plane_b", f.axis_plane_b); - break; - case T::CoordSys: - ref("coordsys_type", enum_name(kCoordSysTypes, int(f.coordsys_type))); - ref("coordsys_point", vec3(f.coordsys_point)); - ref("coordsys_body", f.coordsys_body); - ref("coordsys_face", f.coordsys_face); - ref("coordsys_edge", f.coordsys_edge); - ref("coordsys_x_hint", vec3(f.coordsys_x_hint)); - break; - case T::Project: - ref("project_source_body", f.project_source_body); - ref("project_edges", f.project_edges); - ref("project_face", f.project_face); - break; - case T::DeleteFace: - ref("delete_faces", f.delete_faces); - ref("target_body", f.target_body); - break; - case T::SurfaceLoft: - show("loft_ruled", f.loft_ruled); - ref("loft_profile_refs", f.loft_profile_refs); - break; - case T::SurfaceFill: - ref("sketch_ref", f.sketch_ref); - break; - case T::Import: - break; - } - json expr = json::object(); - for (const auto& [field, e] : f.expr) expr[field] = e; - return json{{"params", std::move(params)}, {"editable", std::move(editable)}, {"ranges", std::move(ranges)}, - {"expr", std::move(expr)}, {"refs", std::move(refs)}}; -} - -// Writes one editable field that is not a bindable number: a card's check box, choice or vector. -// Throws for a value of the wrong type or one the card does not offer. -void set_card_choice(CadFeature& f, const std::string& k, const json& v) -{ - auto flag = [&](bool& field) { - if (!v.is_boolean()) throw std::runtime_error(k + " must be true or false"); - field = v.get(); - }; - auto choice = [&](int& field, int hi) { - if (!v.is_number_integer() || v.get() < 0 || v.get() > hi) - throw std::runtime_error(k + " must be an integer from 0 to " + std::to_string(hi)); - field = v.get(); - }; - auto point3 = [&](Vec3d& field, bool direction) { - if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) - throw std::runtime_error(k + " must be [x, y, z]"); - const Vec3d p(v[0].get(), v[1].get(), v[2].get()); - if (direction && !(p.norm() > 1e-9)) throw std::runtime_error(k + " must not be zero"); - if (!direction && !(p.cwiseAbs().maxCoeff() <= 100000)) - throw std::runtime_error(k + " must be between -100000 and 100000 on each axis"); - field = p; - }; - if (k == "flip") return flag(f.flip); - if (k == "hole_through") return flag(f.hole_through); - if (k == "thread_internal") return flag(f.thread_internal); - if (k == "loft_ruled") return flag(f.loft_ruled); - if (k == "bool_keep_tool") return flag(f.bool_keep_tool); - if (k == "cut_flip") return flag(f.cut_flip); - if (k == "cut_keep_upper") return flag(f.cut_keep_upper); - if (k == "cut_keep_lower") return flag(f.cut_keep_lower); - if (k == "mirror_keep_original") return flag(f.mirror_keep_original); - if (k == "thicken_flip") return flag(f.thicken_flip); - if (k == "helix_left_handed") return flag(f.helix_left_handed); - if (k == "xf_copy") return flag(f.xf_copy); - if (k == "mate_flip") return flag(f.mate_flip); - if (k == "pattern_dir") return choice(f.pattern_dir, 1); - if (k == "revolve_axis") { - // Choosing the plane's X or Y axis on the card drops a sketch line chosen as the axis. - choice(f.revolve_axis, 1); - f.revolve_axis_entity = -1; - return; - } - if (k == "xf_translate") return point3(f.xf_translate, false); - if (k == "xf_pivot") return point3(f.xf_pivot, false); - if (k == "xf_axis") return point3(f.xf_axis, true); - if (k == "import_offset") { - if (!v.is_array() || v.size() != 2 || !v[0].is_number() || !v[1].is_number()) - throw std::runtime_error(k + " must be [x, y]"); - const Vec2d p(v[0].get(), v[1].get()); - if (!(p.cwiseAbs().maxCoeff() <= 100000)) throw std::runtime_error(k + " must be between -100000 and 100000 on each axis"); - f.import_offset = p; - return; - } - // A Text feature's words, height and font, as sketch_text takes them. Written here only: the outline is the - // panel's (DesignPanel::mcp_outline_text()), which feature_edit runs on them. - if (k == "text_string") { - if (!v.is_string() || v.get().empty()) throw std::runtime_error("text_string must be the words to outline"); - f.text_string = v.get(); - return; - } - if (k == "text_height") { - if (!v.is_number() || !(v.get() >= 0.5 && v.get() <= 500.0)) - throw std::runtime_error("text_height must be 0.5 to 500 mm"); - f.text_height = v.get(); - return; - } - if (k == "text_font") { - if (!v.is_string() || v.get().empty()) - throw std::runtime_error("text_font must be a font's face name, or the stored value feature_describe reports"); - f.text_font = v.get(); - return; - } - if (k == "shape") { - f.shape = SketchShape(enum_index(k, v, kShapes)); - return; - } - if (k == "type") { - // A hole's seat, an align's kind and a pattern's layout, in their command's words. - if (f.type == CadFeatureType::Hole) { - f.hole_style = enum_index(k, v, kHoleTypes); - return; - } - if (f.type == CadFeatureType::Mate) { - f.mate_kind = enum_index(k, v, kAlignTypes); - return; - } - if (f.type == CadFeatureType::Pattern) { - const int layout = enum_index(k, v, kPatternTypes); - if (layout == 2) - throw std::runtime_error("a pattern's type is linear or circular; a curve pattern is made with pattern {type: \"curve\"}"); - f.pattern_circular = layout == 1; - return; - } - } - if (k == "operation") { - // The member mode, in the words the feature's card offers: a Boolean combines two bodies, so it makes no new - // one; a Mirror adds its mirrored body or joins it back. - const BooleanMode m = BooleanMode(enum_index(k, v, kOperations)); - if (f.type == CadFeatureType::Boolean && m == BooleanMode::New) - throw std::runtime_error("a Boolean's operation is join, cut or intersect"); - if (f.type == CadFeatureType::Mirror && m != BooleanMode::New && m != BooleanMode::Add) - throw std::runtime_error("a Mirror's operation is new_body or join"); - f.mode = m; - return; - } - if (k == "extrude_end") { - // The face or vertex an end goes up to is picked on the canvas; feature_edit keeps the - // feature's own pick and cannot make one. - const ExtrudeEnd e = ExtrudeEnd(enum_index(k, v, kExtrudeEnds)); - if (e == ExtrudeEnd::UpToFace && f.up_to_face < 0) - throw std::runtime_error("extrude_end up_to_face needs a target face, which only the Extrude card picks"); - if (e == ExtrudeEnd::UpToVertex && f.extrude_end != ExtrudeEnd::UpToVertex) - throw std::runtime_error("extrude_end up_to_vertex needs a target vertex, which only the Extrude card picks"); - f.extrude_end = e; - return; - } - throw std::runtime_error(k + " cannot be set"); -} - -void check_feature_index(int fi, const CadDocument& doc) -{ - if (fi < 0 || fi >= int(doc.features.size())) - throw std::runtime_error("feature " + std::to_string(fi) + " is out of range; the design has " + - std::to_string(doc.features.size()) + " features"); -} - -// The `feature` param (or `index`, as agents often call it): an index into describe_design's features. -int feature_arg(const json& params, const CadDocument& doc) -{ - const json v = !params.is_object() ? json() : params.contains("feature") ? params["feature"] : params.value("index", json()); - if (!v.is_number_integer()) throw std::runtime_error("feature must be a feature index (describe_design's features[].index)"); - check_feature_index(v.get(), doc); - return v.get(); -} - -json action_feature_describe(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - return cad_feature_json(doc, feature_arg(params, doc)); -} - -// A card's Confirm in edit mode (DesignPanel::confirm_tool): `fields`, then `refs`, written to a copy of the feature, -// a Text feature outlined again when its words, height or font change, then one undo step and replace_feature(), -// which rebuilds and puts the old features back if the rebuild fails. Every argument is checked before anything -// changes. -json action_feature_edit(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - // The card's values go in fields; params and values are what agents often call them. - const char* key = params.contains("fields") ? "fields" : params.contains("params") ? "params" : params.contains("values") ? "values" : nullptr; - json fields = key != nullptr ? params[key] : json::object(); - const json refs = params.value("refs", json::object()); - if (!fields.is_object()) throw std::runtime_error("fields must be an object, as {\"distance\": 15}"); - if (!refs.is_object()) throw std::runtime_error("refs must be an object, as {\"sweep_path_ref\": 2}"); - if (fields.empty() && refs.empty()) - throw std::runtime_error("feature_edit needs fields or refs, as {\"fields\": {\"distance\": 15}} or {\"refs\": {\"sweep_path_ref\": 2}}"); - const CadFeature was = doc.features[fi]; - CadFeature edited = was; - // A Text feature's Bold and Italic go with a face name in text_font, as the Text dialog's boxes go with its Font - // list: they are no field of the feature, whose stored font holds them. - bool bold = false, italic = false, styled = false; - if (was.is_text()) - for (const auto& [k, flag] : {std::pair{"text_bold", &bold}, {"text_italic", &italic}}) { - if (!fields.contains(k)) continue; - if (!fields[k].is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); - *flag = fields[k].get(); - styled = true; - fields.erase(k); - } - if (!fields.empty()) cad_apply_feature_fields(edited, fields); - if (was.is_text() && (styled || fields.contains("text_string") || fields.contains("text_height") || fields.contains("text_font"))) { - // A text_font that is the stored value keeps the feature's font; any other names a face. - const std::string face = fields.contains("text_font") && edited.text_font != was.text_font ? edited.text_font : std::string(); - if (styled && face.empty()) throw std::runtime_error("text_bold and text_italic go with text_font given as a face name"); - edited.text_font = was.text_font; - std::string why; - if (!panel->mcp_outline_text(edited, edited.text_string, face, bold, italic, edited.text_height, why)) - throw std::runtime_error(why); - } - if (!refs.empty()) cad_apply_feature_refs(edited, refs, cad_document_before(doc, fi), doc, fi); - const json described = cad_feature_json(doc, fi); - doc.checkpoint(); - if (!doc.replace_feature(fi, edited)) { - // The features are back already; rollback() also takes back the undo step and restores - // the redo branch, so the refused call leaves the history as it found it. - const std::string why = doc.error.empty() ? "the model could not be rebuilt" : doc.error; - doc.rollback(); - doc.error = why; - panel->mcp_after_change(false); - throw ToolFailure(why, {{"code", "rebuild_failed"}}); - } - panel->mcp_after_change(); - return json{{"ok", true}, - {"feature", fi}, - {"changed", cad_feature_changes(described, cad_feature_json(doc, fi))}, - {"bodies", int(doc.bodies.size())}, - {"generation", doc.topo_generation}, - {"error", doc.error}}; -} - -// Which entities a verb acts on in the open sketch (sketch_target_indices()). -std::vector sketch_targets(const json& params, DesignSketchTool& t, bool all_if_empty) -{ - return sketch_target_indices(params, t.selection(), int(t.entities().size()), all_if_empty); -} - -// The open sketch's degrees of freedom, as a reply's dof. The sketch tool keeps -1 while it has no -// constraints, since it runs no solve then and its own readout stays hidden; the count is still -// known, and it is the one a solve would give once a constraint arrives. -int sketch_dof(const DesignSketchTool& t) -{ - return t.constraints().empty() ? sketch_unconstrained_dof(t.entities()) : t.dof(); -} - -// A sketch's loops. Their indices are the ones extrude's `loop` takes: a region lists the loops -// inside it under `holes`, and each of those is a loop of its own. -json sketch_report(const DesignSketchTool::LoopReport& rep) -{ - json loops = json::array(); - for (size_t i = 0; i < rep.loops.size(); ++i) { - const auto& l = rep.loops[i]; - json holes = json::array(); - for (int h : l.holes) holes.push_back(h); - loops.push_back(json{{"index", int(i)}, {"entities", l.ents}, {"holes", holes}, - {"closed", l.closed}, {"area", l.area}}); - } - json open_ends = json::array(); - for (const Vec2d& p : rep.open_ends) open_ends.push_back(json::array({p.x(), p.y()})); - // A profile is buildable when at least one loop closed, nothing is left dangling and no loop - // crosses or folds back on itself. - json defects = json::array(); - for (const auto& l : rep.loops) - if (l.defect) defects.push_back(json::array({l.defect_at.x(), l.defect_at.y()})); - const bool buildable = !rep.loops.empty() && rep.open_ends.empty() && defects.empty(); - return json{{"closed_loops", loops}, {"open_ends", open_ends}, {"defects", defects}, {"buildable", buildable}}; -} - -// The session starts as a plane or face pick starts it, so the panel enters Sketch mode with the -// tool: key dispatch reads the panel's mode while the menu reads the viewport's, and a session the -// panel did not know of would leave every sketch key dead. -json action_sketch_create(DesignPanel* panel, const json& params) -{ - DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - if (vp->is_sketching()) throw CadPrecondition("a sketch is already open"); - const CadDocument& doc = panel->mcp_doc(); - const json pl = params.value("plane", json("XY")); - const SketchPlane plane = cad_resolve_plane(pl, doc, false); - // Named for the status line as the GUI names the plane: XY, a datum's name, or the face. - wxString on; - if (pl.is_string()) on = wxString::FromUTF8(pl.get()); - else if (pl.contains("datum")) on = wxString::FromUTF8(doc.features[pl["datum"].get()].name); - else on = wxString::Format(_L("Face %d"), pl["face"].get()); - panel->mcp_begin_sketch(plane, on); - return json{{"ok", true}, {"plane", pl}, {"frame", frame_json(plane)}}; -} - -// The sketch's Confirm. A failed call is left out of an exported replay, so a call that fails must -// leave the session as it was: a new empty sketch is refused before anything changes (where the -// GUI's commit drops it with a status line), and the session stays open for the replay's next -// sketch call. A re-opened sketch is committed as its Confirm commits it, which replaces it in -// place; a replace the rebuild refuses, or a re-opened sketch left empty, ends the edit with the -// design as it was. That changes the session, so it is a reply, ok false with the reason, which -// the replay keeps and runs to end the edit where the live run ended it. -json action_sketch_finish(DesignPanel* panel, const json& params) -{ - (void)params; - DesignSketchTool& t = mcp_sketch(panel); - const int edited = panel->mcp_edited_sketch(); - if (edited < 0 && t.entities().empty()) throw CadPrecondition("the sketch is empty; add entities or call sketch_cancel"); - const DesignPanel::SketchFinish done = panel->mcp_finish_sketch(); - if (!done.committed && edited >= 0) - return json{{"ok", false}, {"replaced", false}, {"sketch_index", edited}, - {"error", "the sketch was not replaced: " + done.error}}; - if (!done.committed) throw CadPrecondition("the sketch was not committed"); - panel->mcp_after_change(); - // Read back from the committed feature: solving its dimensions can move geometry, and extrude - // takes `loop` against these entities. - const CadDocument& doc = panel->mcp_doc(); - const CadFeature& f = doc.features[done.index]; - json out{{"ok", true}, {"sketch_index", done.index}, {"name", f.name}, {"features", int(doc.features.size())}}; - if (done.replaced) out["replaced"] = true; - out.update(sketch_report(t.loop_report(f.entities))); - return out; -} - -json action_sketch_cancel(DesignPanel* panel, const json& params) -{ - (void)params; - DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - if (!vp->is_sketching()) throw CadPrecondition("no sketch is open"); - panel->mcp_cancel_sketch(); - return json{{"ok", true}}; -} - -// Edit on a committed sketch's Feature tree row, for a sketch drawn from entities: the sketch -// commands then act on it, and sketch_finish puts it back in its place. -json action_sketch_edit(DesignPanel* panel, const json& params) -{ - const json v = params.is_object() ? params.value("sketch", json()) : json(); - if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_design's features[].index)"); - const int si = v.get(); - // The panel's own refusals of the view and an open sketch are the session's state; the others are the feature's. - const DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - if (vp->is_sketching()) throw CadPrecondition("a sketch is already open; finish or cancel it first"); - std::string why; - if (!panel->mcp_edit_sketch(si, why)) throw std::runtime_error(why); - const DesignSketchTool& t = mcp_sketch(panel); - const CadDocument& doc = panel->mcp_doc(); - return json{{"ok", true}, - {"sketch", si}, - {"entities", int(t.entities().size())}, - {"constraints", int(t.constraints().size())}, - {"plane", plane_json(doc.features[si].plane, doc.modeling_origin)}}; -} - -json action_sketch_select(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - std::vector idx; - if (params.contains("entities")) - for (const auto& v : params.at("entities")) idx.push_back(v.get()); - const bool any = t.select_indices(idx); - panel->mcp_viewport()->request_repaint(); - return json{{"ok", true}, {"selected", int(t.selection().size())}, {"any", any}}; -} - -json action_sketch_delete(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - const std::vector tgt = sketch_targets(params, t, false); - if (tgt.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); - const int before = int(t.entities().size()); - t.select_indices(tgt); - t.delete_selected(); - panel->mcp_viewport()->request_repaint(); - return json{{"ok", true}, {"removed", before - int(t.entities().size())}, - {"entities", int(t.entities().size())}}; -} - -json action_sketch_toggle_construction(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - const std::vector tgt = sketch_targets(params, t, false); - if (tgt.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); - t.select_indices(tgt); - const int n = t.toggle_selection_construction(); - panel->mcp_viewport()->request_repaint(); - return json{{"ok", n > 0}, {"changed", n}}; -} - -// The `sketch` a Design command reads or builds from: a Sketch feature, or a Project feature, whose -// entities the kernel builds as a sketch's. -int sketch_arg(const json& v, const CadDocument& doc) -{ - if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_design's features[].index)"); - const int si = v.get(); - check_feature_index(si, doc); - const CadFeature& f = doc.features[si]; - if (f.type != CadFeatureType::Sketch && f.type != CadFeatureType::Project) - throw std::runtime_error("feature " + std::to_string(si) + " (" + feature_type_name(f.type) + ") is not a sketch"); - return si; -} - -json action_sketch_describe(DesignPanel* panel, const json& params) -{ - // A committed sketch is read from the document, so no session is needed, nor disturbed. - const json sketch = params.is_object() ? params.value("sketch", json()) : json(); - if (!sketch.is_null()) { - const DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - const CadDocument& doc = panel->mcp_doc(); - return cad_sketch_describe(doc, vp->mcp_sketch_tool(), sketch_arg(sketch, doc)); - } - DesignSketchTool& t = mcp_sketch(panel); - json ents = json::array(); - for (int i = 0; i < int(t.entities().size()); ++i) - ents.push_back(sketch_entity_to(t.entities()[i], i)); - // The armed TOOL and its pending anchors. Without these the only way to tell which tool a - // menu item actually armed is to draw with it and infer from what came out — which is how a - // menu walk that lands one item off gets diagnosed as "the tool is broken". - static const char* const kModeNames[] = { - "select", "dimension", "polyline", "line", "rect_corner", "rect_center", "rect_oblique", - "rect_rounded", "circle_center", "circle_2pt", "point", - "circle_3pt", "arc_3pt", "arc_tangent", "arc_center", "slot", "slot_arc", "polygon", - "ellipse", "ellipse_arc", "spline", - "fillet", "chamfer", "offset", "mirror", - "trim", "extend", - "move", "rotate", "scale", "array", "array_polar", - "transform_art", - "constrain" }; - const int mi = int(t.mode()); - json out{{"ok", true}, - {"entities", ents}, - {"constraints", int(t.constraints().size())}, - {"dof", sketch_dof(t)}, - {"solve_ok", t.solve_ok()}, - {"tool", (mi >= 0 && mi < int(sizeof(kModeNames) / sizeof(kModeNames[0]))) - ? kModeNames[mi] : "unknown"}, - {"pending", t.pending_points()}, - {"editing", t.value_field_open()}, - {"selection", t.selection()}, - {"selected_constraint", t.selected_constraint() >= 0 ? json(t.selected_constraint()) : json(nullptr)}}; - out.update(sketch_report(t.loop_report())); - return out; -} - -json action_sketch_validate(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - const double tol = params.value("tolerance", 1e-3); - json out{{"ok", true}, {"tolerance", tol}, {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t.loop_report())); - return out; -} - -json action_sketch_repair(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - const double tol = params.value("tolerance", 1e-3); - const bool ic = params.value("ignore_construction", true); - const int welded = t.heal_coincidences(tol, ic); - panel->mcp_viewport()->request_repaint(); - json out{{"ok", true}, {"welded", welded}, {"tolerance", tol}, - {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t.loop_report())); - return out; -} - -// sketch_set_value commits a typed dimension by calling apply_dimension, the function the in-canvas -// value field calls, so what a typed value does to the geometry, constrained geometry included, can -// be asserted without a window manager giving that field keyboard focus. apply_dimension clears the -// selection. -json action_sketch_set_value(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - if (!params.contains("value")) throw std::runtime_error("sketch_set_value needs 'value'"); - const double value = params["value"].get(); - const DesignSketchTool::DimType kind = t.dimension_kind(); - if (kind == DesignSketchTool::DimType::None) - throw CadPrecondition("the selection has no value to set — pick a line, an arc, a circle, or two entities"); - - const char* kind_name = "none"; - switch (kind) { - case DesignSketchTool::DimType::Length: kind_name = "length"; break; - case DesignSketchTool::DimType::Radius: kind_name = "radius"; break; - case DesignSketchTool::DimType::Diameter: kind_name = "diameter"; break; - case DesignSketchTool::DimType::Angle: kind_name = "angle"; break; - case DesignSketchTool::DimType::Distance: kind_name = "distance"; break; - case DesignSketchTool::DimType::DistanceToLine: kind_name = "distance_to_line"; break; - default: break; - } - - // Validate BEFORE apply_dimension. The sketch tool refuses a value outside its thresholds - // itself, but only on its status line and without telling its caller, so this call would - // report the value as set. Fail loudly instead, with the reason. - if (!std::isfinite(value)) - throw std::runtime_error("dimension must be finite — NaN or infinity is not a dimension"); - switch (kind) { - case DesignSketchTool::DimType::Length: - case DesignSketchTool::DimType::Radius: - case DesignSketchTool::DimType::Diameter: - if (value <= 0.0) - throw std::runtime_error(std::string(kind_name) + " must be positive (got " + std::to_string(value) + ")"); - break; - case DesignSketchTool::DimType::Distance: - case DesignSketchTool::DimType::DistanceToLine: - if (value < 0.0) - throw std::runtime_error(std::string(kind_name) + " must be >= 0 (zero means coincident / on the line)"); - break; - case DesignSketchTool::DimType::Angle: - default: - break; // any finite angle is valid - } - - const double before = t.dimension_current(); - t.apply_dimension(value); - panel->mcp_viewport()->request_repaint(); - - json out{{"ok", true}, {"kind", kind_name}, {"before", before}, {"value", value}, - {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t.loop_report())); - return out; -} - -// --- Solids from a profile: extrude and revolve ------------------------------------------------ -// -// With `sketch` they are the Extrude and Revolve cards' Confirm on a committed sketch (or one loop -// of it); without, they draw their own sketch first, a `profile` or a rectangle on `plane`. - -// A join or cut needs something to work on, as the Revolve card says. -void check_has_body(BooleanMode mode, const CadDocument& doc) -{ - if (mode != BooleanMode::New && doc.bodies.empty()) - throw CadPrecondition("operation " + std::string(kOperations[int(mode)]) + " needs a body; add or import one first"); -} - -double distance_arg(const json& params) -{ - const double d = params.value("distance", 10.0); - if (!(d > 0)) throw std::runtime_error("distance must be > 0"); - return d; -} - -ExtrudeEnd extrude_end_arg(const json& params) -{ - const std::string end = params.value("end", std::string("blind")); - // up_to_vertex needs a picked vertex, which no param carries. - for (int i = 0; i < int(ExtrudeEnd::UpToVertex); ++i) - if (end == kExtrudeEnds[i]) return ExtrudeEnd(i); - throw std::runtime_error("end must be blind, symmetric, two_sided, through_all or up_to_face"); -} - -// The end condition and the options that go with it, as the card's Confirm carries them onto the -// new feature (on_add_extrude). apply_feature reads extrude_end, not the kernel's `symmetric` flag; -// up_to_face is a face id of the target body. -void set_extrude_options(CadFeature& fe, const json& params, ExtrudeEnd end, double d) -{ - fe.flip = params.value("flip", false); - fe.taper_deg = params.value("taper", 0.0); - fe.extrude_end = end; - if (end == ExtrudeEnd::TwoSided) fe.distance2 = params.value("distance2", d); - if (end == ExtrudeEnd::UpToFace) fe.up_to_face = params.value("up_to_face", -1); -} - -int revolve_axis_arg(const json& params) -{ - const int axis = params.value("axis", 0); - if (axis != 0 && axis != 1) throw std::runtime_error("axis must be 0 (plane X) or 1 (plane Y)"); - return axis; -} - -// Whether entity `e` of `ents`, a sketch's entities, is a line: what a revolve turns about and a rib grows from. -bool revolve_line(const std::vector& ents, int e) -{ - return e >= 0 && e < int(ents.size()) && ents[size_t(e)].type == SketchEntity::Type::Line; -} - -// The line of sketch `si` a revolve of it turns about, or -1 for the plane axis: params.axis_entity; without one, the -// sketch's only centerline, as a fresh card offers it, unless the caller chose a plane axis. -int revolve_axis_entity_arg(const json& params, const CadDocument& doc, int si) -{ - const json ae = params.value("axis_entity", json()); - if (ae.is_null()) return params.contains("axis") ? -1 : DesignPanel::default_revolve_axis_entity(doc.features[si].entities); - if (!ae.is_number_integer()) throw std::runtime_error("axis_entity must be an entity index of the sketch, or -1 for the plane axis"); - if (ae.get() != -1 && !revolve_line(doc.features[si].entities, ae.get())) - throw std::runtime_error("axis_entity " + std::to_string(ae.get()) + " is not a line of sketch " + std::to_string(si)); - return ae.get(); -} - -// The sketch is the profile and fixes its plane, so these would be ignored; refusing them shows the -// caller its mistake. An empty profile is the row's default, which means none. -void refuse_with_sketch(const json& params) -{ - for (const char* k : {"profile", "width", "height", "plane"}) - if (params.contains(k) && !(params.at(k).is_array() && params.at(k).empty())) - throw std::runtime_error(std::string(k) + " cannot be given with sketch: the sketch is the profile and fixes its plane"); -} - -// Loop `loop` of sketch `si`: the region's own entities followed by those of the loops inside it, -// the list a loop picked in the viewport hands the Extrude card (selected_loop_entities()). -std::vector loop_entities(const DesignSketchTool& tool, const CadDocument& doc, int si, const json& loop) -{ - const std::vector& ents = doc.features[si].entities; - if (!loop.is_number_integer()) throw std::runtime_error("loop must be a loop index (closed_loops[].index of the sketch)"); - if (ents.empty()) - throw std::runtime_error("sketch " + std::to_string(si) + " is not drawn from entities, so it has no loops to pick; extrude it whole"); - const std::vector> regions = tool.region_entity_indices_with_holes(ents); - const int li = loop.get(); - if (li < 0 || li >= int(regions.size())) - throw std::runtime_error("loop " + std::to_string(li) + " does not exist; sketch " + std::to_string(si) + " has " + - std::to_string(regions.size()) + (regions.size() == 1 ? " closed loop" : " closed loops")); - std::vector out; - for (int ei : regions[li]) - if (ei >= 0 && ei < int(ents.size())) out.push_back(ents[ei]); - return out; -} - -// How many separate regions a whole-sketch extrude would have to build: loops not inside another. -int separate_regions(const DesignSketchTool& tool, const std::vector& ents) -{ - const DesignSketchTool::LoopReport rep = tool.loop_report(ents); - std::vector inside(rep.loops.size(), false); - for (const auto& l : rep.loops) - for (int h : l.holes) - if (h >= 0 && h < int(inside.size())) inside[h] = true; - return int(std::count(inside.begin(), inside.end(), false)); -} - -// The body an extrude or revolve went into: the one it made, else the one it joined, cut or -// intersected (its target, or by default the last body). -int result_body(const CadDocument& doc, int feature) -{ - for (size_t b = 0; b < doc.bodies.size(); ++b) - if (doc.bodies[b].source_feature == feature) return int(b); - const int t = doc.features[feature].target_body; - return t >= 0 ? t : int(doc.bodies.size()) - 1; -} - -// The operation a solid feature was built with and the body it went into, as the defaults resolved. -json body_reply(json r, const CadDocument& doc, const char* index_key) -{ - const int f = r.at(index_key).get(); - r["operation"] = kOperations[int(doc.features[f].mode)]; - r["body"] = result_body(doc, f); - return r; -} - -// Both forms reply alike, so a caller need not know which it used: the sketch and the feature, and -// what the defaults resolved to. -json solid_reply(json r, const CadDocument& doc, const char* index_key, int sketch) -{ - r = body_reply(std::move(r), doc, index_key); - const int f = r.at(index_key).get(); - r["sketch_index"] = sketch; - r["frame"] = frame_json(sketch >= 0 ? doc.features[sketch].plane : doc.features[f].plane); - return r; -} - -json action_extrude(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const json sketch = params.value("sketch", json()); - const json loop = params.value("loop", json()); - const ExtrudeEnd end = extrude_end_arg(params); - if (!params.value("face", json()).is_null()) { - SketchPlane frame; - const auto add = cad_face_extrude(doc, params, frame); - json r = add_feature(panel, "extrude_index", - [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); }); - r = solid_reply(std::move(r), doc, "extrude_index", -1); - r["frame"] = frame_json(frame); // the face's, which the feature does not carry - r["face"] = params.at("face"); - r["end"] = kExtrudeEnds[int(end)]; - return r; - } - if (!sketch.is_null()) { - const DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr) throw no_design_view(); - const auto add = cad_sketch_extrude(doc, vp->mcp_sketch_tool(), params); - json r; - try { - r = add_feature(panel, "extrude_index", - [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); }); - } catch (const ToolFailure& e) { - // A whole sketch builds one region, with the loops inside it as holes. When the rebuild - // refused a sketch of several, name the way to take one; any other failure has another cause. - if (!loop.is_null() || e.details.value("code", std::string()) != "rebuild_failed" || - separate_regions(vp->mcp_sketch_tool(), doc.features[sketch.get()].entities) < 2) - throw; - throw ToolFailure(std::string(e.what()) + - "; pass \"loop\" to extrude one of its regions (closed_loops of sketch_describe {sketch})", - e.details); - } - r = solid_reply(std::move(r), doc, "extrude_index", sketch.get()); - r["end"] = kExtrudeEnds[int(end)]; - if (!loop.is_null()) r["loop"] = loop; - return r; - } - if (!loop.is_null()) throw std::runtime_error("loop picks a loop of a committed sketch; give sketch too"); - - const double d = distance_arg(params); - const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); - const auto mode = operation_arg(params, "new_body", kExtrudeOperations); - const int body = std::max(-1, target_body_arg(params, doc)); - if (mode) check_has_body(*mode, doc); - SketchProfile prof; - const bool has_prof = profile_from(params, prof); - double w = 0, h = 0; - if (!has_prof) { - w = params.value("width", 20.0); h = params.value("height", 20.0); - if (w <= 0 || h <= 0) throw std::runtime_error("width and height must be > 0"); - } - int s = -1; - json r = add_feature(panel, "extrude_index", [&] { - const std::string sketch_name = panel->mcp_feature_name(_L("Sketch")); - s = has_prof ? doc.add_sketch_profile(prof, pl, sketch_name) - : doc.add_sketch(SketchShape::Rectangle, pl, w, h, 0.0, sketch_name); - // "auto" decides as the card does for a sketch: join the body the profile touches. - const int touching = mode ? -1 : doc.body_touching_sketch(s); - const BooleanMode m = mode.value_or(touching >= 0 ? BooleanMode::Add : BooleanMode::New); - const int e = doc.add_extrude(s, d, /*symmetric*/false, m, panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); - set_extrude_options(doc.features[e], params, end, d); - doc.features[e].target_body = body >= 0 ? body : touching; - return e; - }); - r = solid_reply(std::move(r), doc, "extrude_index", s); - r["end"] = kExtrudeEnds[int(end)]; - return r; -} - -json action_revolve(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const json sketch = params.value("sketch", json()); - if (!sketch.is_null()) { - const auto add = cad_sketch_revolve(doc, params); - json r = add_feature(panel, "revolve_index", [&] { return add(panel->mcp_feature_name(_L("Revolve"))); }); - r = solid_reply(std::move(r), doc, "revolve_index", sketch.get()); - const CadFeature& f = doc.features[r.at("revolve_index").get()]; - r["axis"] = f.revolve_axis; - r["axis_entity"] = f.revolve_axis_entity; - return r; - } - if (!params.value("axis_entity", json()).is_null()) - throw std::runtime_error("axis_entity is a line of a committed sketch; give sketch too"); - - const double angle = params.value("angle", 360.0); - const int axis = revolve_axis_arg(params); - const bool flip = params.value("flip", false); - const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); - const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); - const int body = std::max(-1, target_body_arg(params, doc)); - check_has_body(mode, doc); - const SketchProfile prof = cad_revolve_profile(params); - int s = -1; - json r = add_feature(panel, "revolve_index", [&] { - s = doc.add_sketch_profile(prof, pl, panel->mcp_feature_name(_L("Sketch"))); - const int rv = doc.add_revolve(s, angle, axis, flip, mode, panel->mcp_feature_name(_L("Revolve"))); - doc.features[rv].target_body = body; - return rv; - }); - r = solid_reply(std::move(r), doc, "revolve_index", s); - r["axis"] = axis; - return r; -} - -json action_mirror(DesignPanel* panel, const json& params) -{ - const BooleanMode m = *operation_arg(params, "new_body", kMirrorOperations); - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to mirror"); - int bi = target_body_arg(params, doc); - bool keep = params.value("keep_original", true); - const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XZ")), doc, false); - doc.checkpoint(); - int idx = doc.add_mirror(pl, bi, m, panel->mcp_feature_name(_L_CONTEXT("Mirror", "Design"))); - doc.features[idx].mirror_keep_original = keep; - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"mirror_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, - {"frame", frame_json(pl)}}; -} - -json action_transform(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to transform"); - int bi = target_body_arg(params, doc); - Vec3d translate(params.value("dx", 0.0), params.value("dy", 0.0), params.value("dz", 0.0)); - Vec3d axis(params.value("axis_x", 0.0), params.value("axis_y", 0.0), params.value("axis_z", 1.0)); - Vec3d pivot(params.value("pivot_x", 0.0), params.value("pivot_y", 0.0), params.value("pivot_z", 0.0)); - double angle = params.value("angle", 0.0); - bool copy = params.value("copy", false); - doc.checkpoint(); - int idx = doc.add_transform(bi, translate, axis, pivot, angle, copy, panel->mcp_feature_name(_L("Transform"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"transform_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -// Whether a thicken call thickens a whole sheet body (type surface, or no type and no face) rather than a face. -bool thickens_surface(const json& params) -{ - const json type = params.value("type", json()); - return type.is_null() ? params.value("face", json()).is_null() : type == "surface"; -} - -// The Thicken and Thicken Surface cards' Confirm, each feature named as its card names it. -json action_thicken(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_thicken(doc, params); - const wxString name = thickens_surface(params) ? _L("Thicken Surface") : _L("Thicken"); - return add_feature(panel, "thicken_index", [&] { return add(panel->mcp_feature_name(name)); }); -} - -// With a plane, the Cut card's Confirm (on_add_cut); with a face, a split along that face's plane. -json action_split(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - json resolved; - const auto add = cad_split(doc, params, resolved); - const bool face = !params.value("face", json()).is_null(); - json r = add_feature(panel, "split_index", [&] { - return add(panel->mcp_feature_name(face ? _L_CONTEXT("Split", "Design") : _L_CONTEXT("Cut", "Design"))); - }); - r.update(resolved); - return r; -} - -// With a sketch open, new or re-opened, the edges go into it (cad_sketch_project()). Otherwise the Project card's -// Confirm: a new sketch on `plane`, XY when it is left out or null, whose entities follow the body. -json action_sketch_project(DesignPanel* panel, const json& params) -{ - if (DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr && vp->is_sketching()) { - json r = cad_sketch_project(panel->mcp_doc(), vp->mcp_sketch_tool(), params); - vp->request_repaint(); - return r; - } - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); - int source_body = params.value("source_body", -1); - int face = params.value("face", -1); - std::vector edges; - if (params.contains("edges") && params["edges"].is_array()) - for (const auto& v : params["edges"]) edges.push_back(v.get()); - const json plane = params.value("plane", json()); - const SketchPlane pl = cad_resolve_plane(plane.is_null() ? json("XY") : plane, doc, false); - doc.checkpoint(); - int idx = doc.add_project_edges(source_body, edges, face, pl, panel->mcp_feature_name(_L_CONTEXT("Project", "Design"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"scope", "feature"}, {"project_index", idx}, {"bodies", int(doc.bodies.size())}, - {"error", doc.error}, {"frame", frame_json(pl)}}; -} - -json action_delete_face(DesignPanel* panel, const json& params) -{ - if (!params.contains("faces")) throw std::runtime_error("delete_face needs 'faces' (array of face ids)"); - CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("no body to delete faces from"); - int bi = target_body_arg(params, doc); - std::vector faces; - if (params["faces"].is_array()) - for (const auto& v : params["faces"]) faces.push_back(v.get()); - doc.checkpoint(); - int idx = doc.add_delete_face(bi, faces, panel->mcp_feature_name(_L("Delete Face"))); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_sketch_blend_curve(DesignPanel* panel, const json& params) -{ - if (!params.contains("sketch")) throw std::runtime_error("sketch_blend_curve needs 'sketch' (feature index)"); - if (!params.contains("ent_a")) throw std::runtime_error("sketch_blend_curve needs 'ent_a' (entity index)"); - if (!params.contains("ent_b")) throw std::runtime_error("sketch_blend_curve needs 'ent_b' (entity index)"); - int sketch = params["sketch"].get(); - int ent_a = params["ent_a"].get(); - int ent_b = params["ent_b"].get(); - int end_a = params.value("end_a", 1); - int end_b = params.value("end_b", 0); - CadDocument& doc = panel->mcp_doc(); - doc.checkpoint(); - int ei = doc.add_bridge(sketch, ent_a, end_a, ent_b, end_b, "Bridge"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"sketch_index", sketch}, {"entity_index", ei}, - {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_construct_axis(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - std::string t = params.value("type", std::string("two_points")); - AxisType at = AxisType::TwoPoints; - if (t == "face_normal") at = AxisType::FaceNormal; - else if (t == "cylinder") at = AxisType::CylinderCenterline; - else if (t == "plane_intersection") at = AxisType::PlaneIntersection; - else if (t == "along_edge") at = AxisType::AlongEdge; - doc.checkpoint(); - int idx = doc.add_axis(at, panel->mcp_feature_name(_L("Axis"))); - CadFeature& f = doc.features[idx]; - if (params.contains("p1") && params["p1"].is_array() && params["p1"].size() >= 3) - f.axis_p1 = Vec3d(params["p1"][0].get(), params["p1"][1].get(), params["p1"][2].get()); - if (params.contains("p2") && params["p2"].is_array() && params["p2"].size() >= 3) - f.axis_p2 = Vec3d(params["p2"][0].get(), params["p2"][1].get(), params["p2"][2].get()); - f.axis_body = params.value("body", -1); - f.axis_face = params.value("face", -1); - f.axis_edge = params.value("edge", -1); - f.axis_plane_a = params.value("plane_a", -1); - f.axis_plane_b = params.value("plane_b", -1); - // Datum features don't produce a body; check for an error returned by resolve. - bool recompute_ok = doc.recompute(); - auto axes = doc.resolve_datum_axes(); - std::string err = doc.error; - if (recompute_ok && err.empty() && !axes.empty() && !axes.back().error.empty()) - err = axes.back().error; - panel->mcp_after_change(); - return json{{"ok", true}, {"axis_index", idx}, {"error", err}}; -} - -json action_construct_coordinate_system(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - std::string t = params.value("type", std::string("point_world")); - CoordSysType ct = CoordSysType::PointWorld; - if (t == "face_and_direction") ct = CoordSysType::FaceAndDirection; - Vec3d pt(0, 0, 0); - if (params.contains("point") && params["point"].is_array() && params["point"].size() >= 3) - pt = Vec3d(params["point"][0].get(), params["point"][1].get(), params["point"][2].get()); - doc.checkpoint(); - int idx = doc.add_coordsys(ct, pt, panel->mcp_feature_name(_L("Coordinate system"))); - CadFeature& f = doc.features[idx]; - f.coordsys_body = params.value("body", -1); - f.coordsys_face = params.value("face", -1); - f.coordsys_edge = params.value("edge", -1); - if (params.contains("x_hint") && params["x_hint"].is_array() && params["x_hint"].size() >= 3) - f.coordsys_x_hint = Vec3d(params["x_hint"][0].get(), params["x_hint"][1].get(), params["x_hint"][2].get()); - bool recompute_ok = doc.recompute(); - auto css = doc.resolve_datum_coordsys(); - std::string err = doc.error; - if (recompute_ok && err.empty() && !css.empty() && !css.back().error.empty()) - err = css.back().error; - panel->mcp_after_change(); - return json{{"ok", true}, {"coordsys_index", idx}, {"error", err}}; -} - -// The Plane card's Confirm (on_add_plane): one undo step, after the card's checks. -json action_construct_plane(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_datum_plane(doc, params); - json r = add_feature(panel, "plane_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Plane", "Design"))); }); - const int fi = r.at("plane_index").get(); - r["name"] = doc.features[fi].name; - r["frame"] = frame_json(doc.resolve_datum_planes().at(datum_ordinal(doc, fi)).second); - return r; -} - -json action_helix(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - CadFeature h; // what add_helix records, built first so a curve the kernel refuses adds nothing - h.type = CadFeatureType::Helix; - h.plane = cad_resolve_plane(params.value("plane", json("XY")), doc, false); - h.helix_radius = params.value("radius", 10.0); - h.helix_pitch = params.value("pitch", 5.0); - h.helix_height = params.value("height", 20.0); - h.helix_left_handed = params.value("left_handed", false); - h.helix_taper_deg = params.value("taper_deg", 0.0); - std::string err; - const TopoDS_Wire curve = doc.build_helix_wire(h, err); - if (curve.IsNull()) throw std::runtime_error("helix: " + (err.empty() ? std::string("the curve could not be built") : err)); - // Where the curve starts and which way it leaves: a sweep's profile is drawn across it there. - BRepAdaptor_CompCurve c(curve); - gp_Pnt start; - gp_Vec tangent; - c.D1(c.FirstParameter(), start, tangent); - doc.checkpoint(); - int idx = doc.add_helix(h.plane, h.helix_radius, h.helix_pitch, h.helix_height, h.helix_left_handed, h.helix_taper_deg, - panel->mcp_feature_name(_L("Helix"))); - panel->mcp_after_change(); - return json{{"ok", true}, {"helix_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, - {"frame", frame_json(h.plane)}, {"start", vec3(Vec3d(start.X(), start.Y(), start.Z()))}, - {"tangent", vec3(Vec3d(tangent.X(), tangent.Y(), tangent.Z()).normalized())}}; -} - -// Thread, sweep and loft: their cards' Confirm. They rebuild off the UI thread, as the cards do. -json action_thread(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - json resolved; - const auto add = cad_thread(doc, params, resolved); - json r = add_feature(panel, "thread_index", [&] { return add(panel->mcp_feature_name(_L("Thread"))); }, true); - r.update(resolved); - r["body"] = result_body(doc, r.at("thread_index").get()); // a rod threaded from nothing is a new body - return r; -} - -json action_sweep(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_sweep(doc, params); - json r = add_feature(panel, "sweep_index", [&] { return add(panel->mcp_feature_name(_L("Sweep"))); }, true); - return body_reply(std::move(r), doc, "sweep_index"); -} - -json action_loft(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_loft(doc, params); - json r = add_feature(panel, "loft_index", [&] { return add(panel->mcp_feature_name(_L("Loft"))); }, true); - return body_reply(std::move(r), doc, "loft_index"); -} - -// The Mate card's Confirm: the feature keeps the history's name for it, Mate. -json action_align(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const auto add = cad_align(doc, params); - return add_feature(panel, "align_index", [&] { return add(panel->mcp_feature_name(_L("Mate"))); }); -} - -json action_list_align_types(DesignPanel* panel, const json& params) { return cad_align_types(panel->mcp_doc(), params); } - -json action_check_interference(DesignPanel* panel, const json& params) -{ - const double min_volume = params.value("min_volume", 1e-6); - CadDocument& doc = panel->mcp_doc(); - // Read-only: no checkpoint(), no recompute(), no mcp_after_change(). - const auto hits = doc.check_interference(min_volume); - json arr = json::array(); - for (const auto& h : hits) { - arr.push_back(json{{"body_a", h.body_a}, {"body_b", h.body_b}, {"volume", h.volume}}); - } - return json{{"ok", true}, {"count", int(hits.size())}, {"interferences", arr}}; -} - -json action_set_variable(DesignPanel* panel, const json& params) -{ - if (!params.contains("name")) throw std::runtime_error("set_variable needs 'name'"); - if (!params.contains("expr")) throw std::runtime_error("set_variable needs 'expr'"); - CadDocument& doc = panel->mcp_doc(); - const std::string name = params["name"].get(); - const std::string expr = params["expr"].get(); - if (name.empty()) throw std::runtime_error("set_variable needs a non-empty 'name'"); - // An empty expression removes the variable, as Remove in the Variables list does. - const bool remove = expr.empty(); - if (remove && doc.variables.count(name) == 0) - throw std::runtime_error("there is no variable '" + name + "'"); - doc.checkpoint(); - if (remove) - doc.variables.erase(name); - else - doc.variables[name] = expr; - const bool ok = doc.recompute(); - if (!ok) { - // rollback() rebuilds, which succeeds and clears doc.error; the reply and the status line - // need the reason. A removal fails because a binding still names the variable, as the - // GUI's Remove says. - const std::string why = doc.error; - doc.rollback(); - doc.error = remove ? std::string(wxString::Format(_L("Variable '%s' could not be removed (likely still referenced " - "by a feature expression): %s"), - wxString::FromUTF8(name), wxString::FromUTF8(why)).ToUTF8().data()) - : why; - } - panel->mcp_after_change(ok); - json r{{"ok", ok}, {"name", name}, {"error", doc.error}}; - if (remove) r["removed"] = ok; - return r; -} - -json action_feature_set_expression(DesignPanel* panel, const json& params) -{ - CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - if (!params.contains("field")) throw std::runtime_error("feature_set_expression needs 'field' name"); - if (!params.contains("expr")) throw std::runtime_error("feature_set_expression needs 'expr' string"); - const std::string field = params["field"].get(); - const std::string expr = params["expr"].get(); - // A name the evaluator does not know would fail every later rebuild; the binding row refuses it too. - if (!CadDocument::is_bindable_field(field)) - throw std::runtime_error("\"" + field + "\" is not a value an expression can drive"); - // An empty expression removes the binding, as the binding row's Clear does; the field keeps - // the value the binding last gave it. - const bool clear = expr.empty(); - if (clear && doc.features[fi].expr.count(field) == 0) - throw std::runtime_error(field + " has no binding on feature " + std::to_string(fi)); - doc.checkpoint(); - if (clear) - doc.features[fi].expr.erase(field); - else - doc.features[fi].expr[field] = expr; - const bool ok = doc.recompute(); - // rollback() rebuilds, which succeeds and clears doc.error; carry the reason across so the - // reply says why the edit was rejected. - if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } - panel->mcp_after_change(ok); - return json{{"ok", ok}, {"feature", fi}, {"field", field}, {"error", doc.error}}; -} - -// --- The Design history, the Feature tree and the Bodies list ---------------------------- - -// Edit > Undo / Redo with the Design tab shown: the Design history, or inside a sketch session the -// sketch's own, which takes off or puts back the last drawn shape. The project's history is undo's -// with history "project". -json undo_redo(DesignPanel* panel, bool redo) -{ - DesignCanvas* vp = panel->mcp_viewport(); - const bool sketch = vp != nullptr && vp->is_sketching(); - if (!panel->menu_can_undo_redo(redo)) { - if (sketch) throw CadPrecondition(redo ? "Nothing to redo in the open sketch" : "Nothing to undo in the open sketch"); - throw CadPrecondition(redo ? "Nothing to redo in the Design history (history \"project\" redoes the project's)" - : "Nothing to undo in the Design history (history \"project\" undoes the project's)"); - } - panel->menu_undo_redo(redo); - if (sketch) return json{{"scope", "sketch"}, {"entities", vp->mcp_sketch_tool().entities().size()}}; - const CadDocument& doc = panel->mcp_doc(); - return json{{"scope", "design"}, - {"undo_depth", doc.undo_depth()}, - {"redo_depth", doc.redo_depth()}, - {"features", doc.features.size()}, - {"bodies", doc.bodies.size()}, - {"generation", doc.topo_generation}}; -} - -// The panel's tree edits put the features back, leave no undo step and say "Edit rejected" when the -// kernel refuses one; the call then fails with the kernel's reason. -[[noreturn]] void tree_edit_refused(const CadDocument& doc) -{ - throw ToolFailure(doc.error.empty() ? "the Design tab refused the edit" : doc.error, {{"code", "rebuild_failed"}}); -} - -json tree_edit_reply(const CadDocument& doc, json reply) -{ - reply["ok"] = true; - reply["features"] = doc.features.size(); - reply["bodies"] = doc.bodies.size(); - reply["generation"] = doc.topo_generation; - return reply; -} - -// params[key], or null when it is absent or params is not an object. -json param(const json& params, const char* key) -{ - return params.is_object() ? params.value(key, json()) : json(); -} - -// A `name` as the rows' rename editor takes it: trimmed, and never empty. -std::string name_arg(const json& params) -{ - const json v = param(params, "name"); - if (!v.is_string()) throw std::runtime_error("name must be a string"); - std::string name = v.get(); - name.erase(name.find_last_not_of(" \t\r\n") + 1); - name.erase(0, name.find_first_not_of(" \t\r\n")); - if (name.empty()) throw std::runtime_error("name must not be empty"); - return name; -} - -// The `body` param: an index into describe_design's bodies. -int body_arg(const json& params, const CadDocument& doc) -{ - const json v = param(params, "body"); - if (!v.is_number_integer()) throw std::runtime_error("body must be a body index (describe_design's bodies[].index)"); - const int b = v.get(); - if (b < 0 || b >= int(doc.bodies.size())) - throw std::runtime_error("body " + std::to_string(b) + " is out of range; the design has " + - std::to_string(doc.bodies.size()) + " bodies"); - return b; -} - -json action_feature_delete(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - const size_t before = doc.features.size(); - if (!panel->delete_feature(fi)) tree_edit_refused(doc); - return tree_edit_reply(doc, {{"removed", before - doc.features.size()}}); -} - -json action_feature_move(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - const json delta = param(params, "delta"); - if (!delta.is_number_integer() || std::abs(delta.get()) != 1) - throw std::runtime_error("delta must be -1 (up) or 1 (down)"); - const int to = fi + delta.get(); - if (to < 0 || to >= int(doc.features.size())) - throw CadPrecondition("feature " + std::to_string(fi) + " is already " + (to < 0 ? "first" : "last")); - if (!panel->move_feature(fi, delta.get())) tree_edit_refused(doc); - return tree_edit_reply(doc, {{"feature", to}, {"from", fi}}); -} - -// The row's eye: it shows a feature that is not suppressed and hides one that is. -json action_feature_suppress(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - const json suppressed = param(params, "suppressed"); - if (!suppressed.is_boolean()) throw std::runtime_error("suppressed must be true or false"); - const bool shown = !suppressed.get(); - const bool changed = doc.features[fi].enabled != shown; - if (!panel->show_feature(fi, shown)) tree_edit_refused(doc); - return tree_edit_reply(doc, {{"feature", fi}, {"suppressed", suppressed}, {"changed", changed}}); -} - -json action_feature_rename(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int fi = feature_arg(params, doc); - const std::string name = name_arg(params); - const bool changed = doc.features[fi].name != name; - panel->rename_feature(fi, name); - return json{{"ok", true}, {"feature", fi}, {"name", name}, {"changed", changed}, {"undo_depth", doc.undo_depth()}}; -} - -// The Bodies row's rename and eye and the Color button, in one call. Every argument is checked -// before anything changes. -json action_body_set(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int b = body_arg(params, doc); - std::optional name; - std::optional color; - std::optional visible; - if (!param(params, "name").is_null()) name = name_arg(params); - if (const json c = param(params, "color"); !c.is_null()) { - const std::string s = c.is_string() ? c.get() : std::string(); - ColorRGBA rgba; - if (s.size() != 7 || s[0] != '#' || - !std::all_of(s.begin() + 1, s.end(), [](unsigned char ch) { return std::isxdigit(ch) != 0; }) || - !decode_color(s, rgba)) - throw std::runtime_error("color must be \"#RRGGBB\""); - color = rgba; - } - if (const json v = param(params, "visible"); !v.is_null()) { - if (!v.is_boolean()) throw std::runtime_error("visible must be true or false"); - visible = v.get(); - } - if (!name && !color && !visible) throw std::runtime_error("body_set needs name, color or visible"); - if (name) panel->rename_body(b, *name); - if (color) panel->set_body_color(b, *color); - if (visible) panel->show_body(b, *visible); - - const CadBody& body = doc.bodies[b]; - json r{{"ok", true}, {"body", b}, {"name", body.has_user_name ? body.user_name : body.name}, - {"visible", panel->mcp_body_shown(b)}}; - if (const DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr) r["color"] = encode_color(vp->body_color(b)); - return r; -} - -json action_body_delete(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const int b = body_arg(params, doc); - const int src = doc.bodies[b].source_feature; - if (src < 0 || src >= int(doc.features.size())) - throw CadPrecondition("body " + std::to_string(b) + " has no feature to delete; use new_design to start over"); - const json deleted{{"index", src}, {"type", feature_type_name(doc.features[src].type)}, {"name", doc.features[src].name}}; - const size_t before = doc.features.size(); - if (!panel->delete_body(b)) tree_edit_refused(doc); - return tree_edit_reply(doc, {{"deleted_feature", deleted}, {"removed", before - doc.features.size()}}); -} - -// The Bodies row's Move and Place on Face from arguments: where a body stands, outside the history. Every argument is -// read before the body moves. -json action_body_place(DesignPanel* panel, const json& params) -{ - const int b = body_arg(params, panel->mcp_doc()); - const json move = param(params, "move"); - const json rotate = param(params, "rotate"); - const json face = param(params, "face"); - const json reset = param(params, "reset"); - if (!reset.is_null() && !reset.is_boolean()) throw std::runtime_error("reset must be true or false"); - const bool resets = reset.is_boolean() && reset.get(); - const int forms = int(!move.is_null() || !rotate.is_null()) + int(!face.is_null()) + int(resets); - if (forms == 0) throw std::runtime_error("body_place takes move and rotate, face, or reset: true"); - if (forms > 1) throw std::runtime_error("move and rotate, face and reset are three forms: give one of them"); - - std::string why; - if (!face.is_null()) { - if (!face.is_number_integer() || face.get() < 0) throw std::runtime_error("face must be a face id (body_describe)"); - if (!panel->mcp_place_body_on_face(b, face.get(), why)) throw std::runtime_error(why); - } else if (resets) { - panel->mcp_reset_body_placement(b); - } else { - Vec3d d = Vec3d::Zero(); - if (!move.is_null()) { - if (!move.is_array() || move.size() != 3 || !std::all_of(move.begin(), move.end(), [](const json& v) { return v.is_number(); })) - throw std::runtime_error("move must be [dx, dy, dz] in mm"); - d = Vec3d(move[0].get(), move[1].get(), move[2].get()); - } - int axis = -1; - double angle = 0.0; - if (!rotate.is_null()) { - static const std::map axes{{"x", 0}, {"y", 1}, {"z", 2}}; - const json a = param(rotate, "axis"); - const json g = param(rotate, "angle"); - const auto named = a.is_string() ? axes.find(a.get()) : axes.end(); - if (!rotate.is_object() || named == axes.end() || !g.is_number() || rotate.size() != 2) - throw std::runtime_error("rotate must be {\"axis\": \"x\", \"y\" or \"z\", \"angle\": degrees}"); - axis = named->second; - angle = g.get(); - } - if (!panel->mcp_place_body(b, d, axis, angle, why)) throw std::runtime_error(why); - } - return json{{"ok", true}, {"body", b}, {"moved", panel->mcp_body_moved(b)}, {"placement", placement_json(*panel, b)}}; -} - -// --- Hand-off: Commit to Plate, New Design, Export STEP ---------------------------------- - -// Commit to Plate as the split button does, in `mode` (by default the button's, which this leaves -// alone), then delete the `replace` objects. With `replace` the deletions and the commit are one -// Prepare undo step: the commit's own snapshot is suppressed under the outer one. -json action_commit_to_plate(DesignPanel* panel, const json& params) -{ - using Mode = DesignPanel::CommitMode; - Mode mode = panel->commit_mode(); - const json m = params.value("mode", json("")); - if (m == "assembly") mode = Mode::Assembly; - else if (m == "bodies") mode = Mode::Bodies; - else if (m != "") throw std::runtime_error("mode must be \"assembly\" or \"bodies\""); - - Plater* plater = wxGetApp().plater(); - ObjectList* obj_list = wxGetApp().obj_list(); - if (plater == nullptr || obj_list == nullptr) throw CadPrecondition("Prepare is not ready"); - Model& model = plater->model(); - const std::vector replace = cad_commit_to_plate_replace(params.value("replace", json::array()), model); - // The Delete key does not pull an object from under an open gizmo either. - if (!replace.empty()) - for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_assmeble_canvas3D()}) - if (canvas != nullptr && canvas->get_gizmos_manager().get_current_type() != GLGizmosManager::Undefined) - throw CadPrecondition("close the " + Mcp::gizmo_name(canvas->get_gizmos_manager().get_current_type()) + - " gizmo first: replace deletes objects"); - - // commit_to_plate()'s own refusals, checked first so a refused call leaves no undo step. - const CadDocument& doc = panel->mcp_doc(); - if (doc.display_mesh.its.indices.empty()) - throw CadPrecondition("Nothing to commit: the design has no body; add a feature first"); - bool any_shown = doc.display_body_meshes.size() <= 1; // a lone body is sent even when hidden - for (size_t b = 0; !any_shown && b < doc.display_body_meshes.size(); ++b) - any_shown = panel->mcp_body_shown(int(b)) && !doc.display_body_meshes[b].its.indices.empty(); - if (!any_shown) throw CadPrecondition("Every body is hidden; show one first with body_set {body, visible: true}"); - - json replaced = json::array(); - for (int i : replace) replaced.push_back(json{{"index", i}, {"name", model.objects[i]->name}}); - - std::vector sent; - std::vector made; - { - std::optional snapshot; - if (!replace.empty()) snapshot.emplace(plater, _u8L("Commit to Plate")); - for (size_t i : panel->commit_to_plate(mode, &sent)) made.push_back(model.objects[i]); - if (made.empty()) throw CadPrecondition("Commit to Plate sent nothing"); - std::vector items; - for (int i : replace) items.emplace_back(itObject, i, -1); - obj_list->delete_from_model_and_list(items); - } - - // The new objects' indices once the replaced ones are gone. - json objects = json::array(); - for (const ModelObject* o : made) { - const auto it = std::find(model.objects.begin(), model.objects.end(), o); - objects.push_back(json{{"index", int(it - model.objects.begin())}, {"object_id", o->id().id}, {"name", o->name}, - {"parts", o->volumes.size()}}); - } - json hidden = json::array(); - for (int b = 0; b < int(doc.bodies.size()); ++b) - if (std::find(sent.begin(), sent.end(), b) == sent.end() && !panel->mcp_body_shown(b)) hidden.push_back(b); - return json{{"ok", true}, {"mode", mode == Mode::Bodies ? "bodies" : "assembly"}, {"objects", std::move(objects)}, - {"bodies_sent", sent}, {"bodies_hidden", std::move(hidden)}, {"replaced", std::move(replaced)}, - {"tab", "prepare"}}; -} - -// New Design without its confirmation dialog: discard_changes confirms, as project_new's does. -json action_new_design(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - const json discard = params.value("discard_changes", json(false)); - if (!discard.is_boolean()) throw std::runtime_error("discard_changes must be true or false"); - const json cleared = {{"features", doc.features.size()}, {"bodies", doc.bodies.size()}, {"variables", doc.variables.size()}}; - if (!discard.get() && !(doc.features.empty() && doc.bodies.empty() && doc.variables.empty())) - throw std::runtime_error("The design is not empty (" + cleared.dump() + - "); pass discard_changes: true to erase it. This also clears the Design undo history; " - "committed objects stay on the plate."); - panel->clear_document(); - return json{{"ok", true}, {"cleared", cleared}}; -} - -// Export STEP… to a path instead of its file dialog, with the server's output-path rules. -json action_export_step(DesignPanel* panel, const json& params) -{ - const CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw CadPrecondition("Nothing to export: the design has no body; add a feature first"); - const json path_arg = params.value("path", json()); - const json overwrite = params.value("overwrite", json(false)); - if (!path_arg.is_string()) throw std::runtime_error("export_step needs 'path', an absolute file path"); - if (!overwrite.is_boolean()) throw std::runtime_error("overwrite must be true or false"); - std::string err; - const auto path = Mcp::resolve_output_path(path_arg.get(), overwrite.get(), err); - if (!path) throw std::runtime_error(err); - const std::string path_utf8 = Mcp::path_to_utf8(*path); - if (!panel->export_step_to(path_utf8, err)) throw ToolFailure("STEP export failed: " + err, {{"code", "export_failed"}}); - - boost::system::error_code ec; - const auto bytes = boost::filesystem::file_size(*path, ec); - json moved = json::array(); - for (int b = 0; b < int(doc.bodies.size()); ++b) - if (panel->mcp_body_moved(b)) moved.push_back(b); - return json{{"ok", true}, {"path", path_utf8}, {"bytes", ec ? 0 : bytes}, {"bodies", doc.bodies.size()}, - {"moved_bodies", std::move(moved)}}; -} - -// --- The open sketch: shapes, edit ops and constraints (cad_sketch_call) ----------------------- -// -// Each runs the sketch tool's own step for its button or gesture (DesignSketchTool's *_scripted -// entry points), checks every argument first and throws, leaving the sketch as it was. sketch_draw, -// whose tools can still refuse an item while drawing it, puts the sketch back as it was before the call when one does. - -// SketchEntity::Type's names, as sketch_describe writes them. -const char* const kEntityTypes[] = {"line", "arc", "circle", "point", "ellipse", "ellipse_arc", "spline"}; -static_assert(std::size(kEntityTypes) == size_t(SketchEntity::Type::BSpline) + 1, "every entity type needs a name"); - -std::string entity_label(const std::vector& ents, int i) -{ - if (i == kSketchRefOrigin) return "origin"; - if (i == kSketchRefAxisX) return "x_axis"; - if (i == kSketchRefAxisY) return "y_axis"; - return std::string(kEntityTypes[int(ents[i].type)]) + " " + std::to_string(i); -} - -// `v`, a list of entity indices of the open sketch. -std::vector entity_indices(const json& v, const std::vector& ents) -{ - if (!v.is_array()) throw std::runtime_error("entities must be a list of entity indices"); - std::vector out; - for (const json& i : v) { - if (!i.is_number_integer()) throw std::runtime_error("entities must be a list of entity indices"); - const int e = i.get(); - if (e < 0 || e >= int(ents.size())) - throw std::runtime_error("entity " + std::to_string(e) + " does not exist; the sketch has " + - std::to_string(ents.size()) + " entities"); - out.push_back(e); - } - return out; -} - -// `entities`, else the selection: what a tool's picks would be. -std::vector entity_picks(const json& params, const DesignSketchTool& t) -{ - const json v = param(params, "entities"); - return v.is_null() || (v.is_array() && v.empty()) ? t.selection() : entity_indices(v, t.entities()); -} - -// The tools' own apply steps take over a gesture in progress or an open value field, as a click -// would; the person finishes or drops those first. -void check_sketch_idle(const DesignSketchTool& t) -{ - if (t.value_field_open()) throw CadPrecondition("a value field is open in the sketch; commit or cancel it (Enter or Esc) first"); - if (t.gesture_pending()) throw CadPrecondition("the armed sketch tool has a gesture in progress; finish it or press Esc first"); -} - -// How many of `cons` reference entity `e`. -int constraints_on(const std::vector& cons, int e) -{ - return int(std::count_if(cons.begin(), cons.end(), [e](const SketchEntityConstraintDef& c) { - return c.ea == e || c.eb == e || c.ec == e; - })); -} - -json solve_state(const DesignSketchTool& t) -{ - return json{{"entities", int(t.entities().size())}, {"constraints", int(t.constraints().size())}, - {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; -} - -// One item of sketch_draw: entities added as given (`tool` Select), or a shape a drawing tool builds -// from its clicks. -struct SketchDrawItem -{ - std::vector ents; - DesignSketchTool::Mode tool{DesignSketchTool::Mode::Select}; - std::vector clicks; // the tool's; a tangent arc's end only, its start being the end of what it leaves - int sides{0}; - bool circumscribed{false}; - bool construction{false}; - int from{-1}; // the entity a tangent arc leaves; -1 the one added last -}; - -// sketch_draw's types, in the order its schema lists them, each with the fields it takes beside `type` and -// `construction`. -struct ShapeType -{ - const char* name; - std::vector fields; -}; -const ShapeType kShapeTypes[] = { - {"line", {"p0", "p1"}}, - {"polyline", {"points"}}, - {"rectangle_2_point", {"p0", "p1"}}, - {"rectangle_center", {"center", "corner"}}, - {"rectangle_3_point", {"p0", "p1", "width"}}, - {"rectangle_rounded", {"p0", "p1", "radius"}}, - {"circle_center", {"center", "radius"}}, - {"circle_2_point", {"p0", "p1"}}, - {"circle_3_point", {"p0", "p1", "p2"}}, - {"arc_3_point", {"p0", "p1", "on_arc"}}, - {"arc_center", {"center", "radius", "start_angle", "start_angle_deg", "end_angle", "end_angle_deg"}}, - {"arc_tangent", {"end", "entity"}}, - {"slot", {"c0", "c1", "width"}}, - {"slot_arc", {"center", "start", "end", "width"}}, - {"ellipse", {"center", "radius", "rminor", "rotation", "rotation_deg"}}, - {"ellipse_arc", - {"center", "radius", "rminor", "rotation", "rotation_deg", "start_angle", "start_angle_deg", "end_angle", "end_angle_deg"}}, - {"spline", {"ctrl"}}, - {"polygon", {"center", "sides", "radius", "across_flats", "angle", "angle_deg"}}, - {"point", {"p"}}, -}; - -// Whether a, b and c lie on one line, so that no circle runs through them. -bool on_one_line(const Vec2d& a, const Vec2d& b, const Vec2d& c) -{ - const Vec2d u = b - a, v = c - a; - return std::abs(u.x() * v.y() - u.y() * v.x()) < 1e-9; -} - -// A sketch_draw item: a shape's fields turned into the clicks its tool takes, or plain entities. A field given as -// null is left out, as the schema's null defaults say, and a field its type does not take is refused. Every check -// is made here, or for a tangent arc's entity in sketch_draw() before anything is drawn. Whether an arc fits a -// tangent arc is known once the items before it are drawn, since its start is the end of what it leaves; when none -// does, sketch_draw() puts the sketch back as it was before the call. -SketchDrawItem sketch_draw_item(const json& given) -{ - using Mode = DesignSketchTool::Mode; - using ET = SketchEntity::Type; - if (!given.is_object()) throw std::runtime_error("each shape is an object with a type and its fields"); - json j = json::object(); - for (const auto& [key, value] : given.items()) - if (!value.is_null()) j[key] = value; - SketchDrawItem it; - const std::string t = j.value("type", std::string()); - const auto type = std::find_if(std::begin(kShapeTypes), std::end(kShapeTypes), [&t](const ShapeType& s) { return t == s.name; }); - if (type == std::end(kShapeTypes)) { - std::string types; - for (const ShapeType& s : kShapeTypes) types += (types.empty() ? "" : ", ") + std::string(s.name); - throw std::runtime_error("unknown type '" + t + "': sketch_draw draws " + types); - } - for (const auto& [key, value] : j.items()) - if (key != "type" && key != "construction" && std::find(type->fields.begin(), type->fields.end(), key) == type->fields.end()) - throw std::runtime_error(t + " takes no " + key); - it.construction = j.value("construction", false); - // Smaller than the weld tolerance is no shape: its points would merge. - auto size_arg = [&](const char* key) { - const double v = number_arg(j, key); - if (!(v >= kSketchJoinTol)) throw std::runtime_error(t + " " + key + " must be at least 0.001 mm"); - return v; - }; - // Two corners of a box, which must differ in x and in y. - auto box_corners = [&](const char* a_key, const char* b_key) { - const Vec2d a = point_arg(j, a_key), b = point_arg(j, b_key); - if (std::abs(b.x() - a.x()) < kSketchJoinTol || std::abs(b.y() - a.y()) < kSketchJoinTol) - throw std::runtime_error(t + " " + a_key + " and " + b_key + " must differ in x and in y"); - return std::make_pair(a, b); - }; - if (t == "polyline") { - const json points = j.value("points", json()); - if (!points.is_array() || points.size() < 2) throw std::runtime_error("polyline needs points, 2 or more [[x, y], ...]"); - for (size_t i = 0; i < points.size(); ++i) { - const Vec2d p = point_of(points[i], "points[" + std::to_string(i) + "]"); - if (i > 0 && (p - it.clicks.back()).norm() < kSketchJoinTol) - throw std::runtime_error("polyline points " + std::to_string(i - 1) + " and " + std::to_string(i) + " coincide"); - it.clicks.push_back(p); - } - // The last point on the first closes the loop, as a click on the chain's start does. - if (it.clicks.size() >= 3 && (it.clicks.back() - it.clicks.front()).norm() < kSketchJoinTol) { - if (it.clicks.size() < 4) throw std::runtime_error("a closed polyline needs three points before the one that closes it"); - it.clicks.back() = it.clicks.front(); - } - it.tool = Mode::Polyline; - } else if (t == "rectangle_2_point") { - // The Corner rectangle tool's two clicks, on opposite corners. - const auto [a, b] = box_corners("p0", "p1"); - it.tool = Mode::CornerRect; - it.clicks = {a, b}; - } else if (t == "rectangle_center") { - const auto [c, corner] = box_corners("center", "corner"); - it.tool = Mode::CenterRect; - it.clicks = {c, corner}; - } else if (t == "rectangle_3_point") { - // One side, then the Oblique rectangle tool's third click, the width off it to the left of p0 to p1. - const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"); - const double w = number_arg(j, "width"); - if ((b - a).norm() < kSketchJoinTol) throw std::runtime_error("rectangle_3_point p0 and p1 must be apart"); - if (std::abs(w) < kSketchJoinTol) throw std::runtime_error("rectangle_3_point width must be at least 0.001 mm either way"); - const Vec2d u = (b - a).normalized(); - it.tool = Mode::ObliqueRect; - it.clicks = {a, b, a + w * Vec2d(-u.y(), u.x())}; - } else if (t == "rectangle_rounded") { - const auto [a, b] = box_corners("p0", "p1"); - const double r = size_arg("radius"); - const double half = 0.5 * std::min(std::abs(b.x() - a.x()), std::abs(b.y() - a.y())); - if (!(r < half)) - throw std::runtime_error("rectangle_rounded radius must be less than half its shorter side, " + json(half).dump() + " mm"); - // The Rounded rectangle tool's third click sets the corner radius by its distance to the nearest corner. - it.tool = Mode::RoundedRect; - it.clicks = {a, b, Vec2d(std::min(a.x(), b.x()) + r, std::min(a.y(), b.y()))}; - } else if (t == "circle_2_point") { - const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"); - if ((b - a).norm() < 2.0 * kSketchJoinTol) - throw std::runtime_error("circle_2_point p0 and p1, the ends of a diameter, must be at least 0.002 mm apart"); - it.tool = Mode::TwoPointCircle; - it.clicks = {a, b}; - } else if (t == "circle_3_point") { - const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"), c = point_arg(j, "p2"); - if (on_one_line(a, b, c)) throw std::runtime_error("circle_3_point p0, p1 and p2 must not lie on one line"); - it.tool = Mode::ThreePointCircle; - it.clicks = {a, b, c}; - } else if (t == "arc_3_point") { - const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"), m = point_arg(j, "on_arc"); - if (on_one_line(a, b, m)) throw std::runtime_error("arc_3_point p0, p1 and on_arc must not lie on one line"); - it.tool = Mode::ThreePointArc; - it.clicks = {a, b, m}; - } else if (t == "arc_tangent") { - if (j.contains("entity")) { - const json e = j.at("entity"); - if (!e.is_number_integer() || e.get() < 0) - throw std::runtime_error("arc_tangent entity must be the index of the line or arc it leaves"); - it.from = e.get(); - } - it.tool = Mode::TangentArc; - it.clicks = {point_arg(j, "end")}; - } else if (t == "slot_arc") { - const Vec2d c = point_arg(j, "center"), s = point_arg(j, "start"), e = point_arg(j, "end"); - const double w = size_arg("width"); - const double rc = (s - c).norm(); - if (rc < kSketchJoinTol) throw std::runtime_error("slot_arc start must be apart from center"); - if ((e - c).norm() < kSketchJoinTol) throw std::runtime_error("slot_arc end must be apart from center"); - const Vec2d ds = (s - c) / rc, de = (e - c).normalized(); - if (std::abs(ds.x() * de.y() - ds.y() * de.x()) < 1e-9 && ds.dot(de) > 0.0) - throw std::runtime_error("slot_arc end must lie in another direction from center than start"); - if (!(0.5 * w < rc)) throw std::runtime_error("slot_arc width must be less than twice the distance from center to start"); - // The Arc slot tool's clicks: the centre, the centreline's start, its end's direction, and the width's half off - // the centreline circle. - it.tool = Mode::ArcSlot; - it.clicks = {c, s, e, c + (rc + 0.5 * w) * ds}; - } else if (t == "polygon") { - const Vec2d c = point_arg(j, "center"); - const json sides = j.value("sides", json()); - if (!sides.is_number_integer() || sides.get() < 3 || sides.get() > 1000) - throw std::runtime_error("polygon needs sides, 3 to 1000"); - if (j.contains("across_flats") == j.contains("radius")) - throw std::runtime_error("polygon needs radius (centre to a vertex) or across_flats, one of them"); - // The tool's second click: on a vertex (inscribed), or on an edge's midpoint, half the - // across-flats size out (circumscribed). - it.circumscribed = j.contains("across_flats"); - const double d = it.circumscribed ? size_arg("across_flats") / 2.0 : size_arg("radius"); - const double a = angle_arg(j, "angle", 0.0); - it.tool = Mode::Polygon; - it.sides = sides.get(); - it.clicks = {c, c + d * Vec2d(std::cos(a), std::sin(a))}; - } else if (t == "slot") { - const Vec2d c0 = point_arg(j, "c0"), c1 = point_arg(j, "c1"); - const double w = size_arg("width"); - if ((c1 - c0).norm() < kSketchJoinTol) throw std::runtime_error("slot centres c0 and c1 must be apart"); - const Vec2d u = (c1 - c0).normalized(); - it.tool = Mode::Slot; - it.clicks = {c0, c1, c0 + 0.5 * w * Vec2d(-u.y(), u.x())}; - } else if (t == "ellipse" || t == "ellipse_arc") { - const Vec2d c = point_arg(j, "center"); - const double a = size_arg("radius"), b = size_arg("rminor"); - if (b > a) throw std::runtime_error(t + " rminor must not exceed radius, the semi-major axis"); - const double phi = angle_arg(j, "rotation", 0.0); - const Vec2d u(std::cos(phi), std::sin(phi)), v(-std::sin(phi), std::cos(phi)); - it.tool = Mode::Ellipse; - it.clicks = {c, c + a * u, c + b * v}; - if (t == "ellipse_arc") { - for (const char* k : {"start_angle", "end_angle"}) - if (!j.contains(k) && !j.contains(std::string(k) + "_deg")) - throw std::runtime_error(std::string("ellipse_arc needs ") + k + " (or " + k + "_deg)"); - const double t0 = angle_arg(j, "start_angle", 0.0), t1 = angle_arg(j, "end_angle", 0.0); - if (std::abs(std::remainder(t1 - t0, 2.0 * M_PI)) < 1e-9) - throw std::runtime_error("ellipse_arc end_angle must differ from start_angle; a whole turn is an ellipse"); - // Points on the ellipse at those parametric angles, which the tool reads back off them. - auto on = [&](double s) { return Vec2d(c + a * std::cos(s) * u + b * std::sin(s) * v); }; - it.tool = Mode::EllipseArc; - it.clicks.push_back(on(t0)); - it.clicks.push_back(on(t1)); - } - } else if (t == "spline") { - const json ctrl = j.value("ctrl", json()); - if (!ctrl.is_array() || ctrl.size() < 2) throw std::runtime_error("spline needs ctrl, 2 or more poles [[x, y], ...]"); - for (size_t i = 0; i < ctrl.size(); ++i) { - const Vec2d p = point_of(ctrl[i], "ctrl[" + std::to_string(i) + "]"); - if (i > 0 && (p - it.clicks.back()).norm() < kSketchJoinTol) - throw std::runtime_error("spline poles " + std::to_string(i - 1) + " and " + std::to_string(i) + " coincide"); - it.clicks.push_back(p); - } - it.tool = Mode::BSpline; - } else { - it.ents.push_back(sketch_entity_from(j)); // line, circle_center, arc_center, point - } - return it; -} - -json sketch_draw(DesignSketchTool& t, const json& params) -{ - using Mode = DesignSketchTool::Mode; - std::vector items; - const json list = param(params, "entities"), type = param(params, "type"); - if (!list.is_null()) { - // An entities given is the list form, an empty one included. Each item holds its shape's fields, so one beside - // the list would draw nothing, and is refused. construction is no shape's field: beside the list it is each - // item's that gives none of its own. - for (const auto& [key, value] : params.items()) - if (key != "entities" && key != "construction" && key != "generation" && !value.is_null()) - throw std::runtime_error(key + " belongs in an item of entities, not beside the list"); - if (!list.is_array()) throw std::runtime_error("entities must be a list of shapes, each an object with a type and its fields"); - if (list.empty()) throw std::runtime_error("entities is empty: give it the shapes to draw, or a single type and its fields"); - const json construction = param(params, "construction"); - for (json j : list) { - if (j.is_object() && !construction.is_null() && j.value("construction", json()).is_null()) j["construction"] = construction; - items.push_back(sketch_draw_item(j)); - } - } else if (type.is_string() && !type.get().empty()) { - // One item, its fields beside `type`. - json one = params; - one.erase("entities"); - one.erase("generation"); - items.push_back(sketch_draw_item(one)); - } else { - throw std::runtime_error("sketch_draw needs 'entities' or a single 'type'"); - } - if (std::any_of(items.begin(), items.end(), [](const SketchDrawItem& it) { return it.tool != Mode::Select; })) - check_sketch_idle(t); - - const int before = int(t.entities().size()); - json shapes = json::array(); - // An item refused while drawing puts the sketch back as it was before the call, the items before it taken off. - const DesignSketchTool::DrawnState kept = t.drawn_state(); - try { - for (size_t i = 0; i < items.size();) { - if (items[i].tool == DesignSketchTool::Mode::Select) { - // Entities next to each other are added in one batch, so their constraints are inferred - // together, as a list of entities always was. - std::vector run; - size_t end = i; - for (; end < items.size() && items[end].tool == DesignSketchTool::Mode::Select; ++end) - run.insert(run.end(), items[end].ents.begin(), items[end].ents.end()); - int at = t.add_entities_scripted(run); - for (; i < end; ++i) { - shapes.push_back(json{{"first", at}, {"count", int(items[i].ents.size())}}); - at += int(items[i].ents.size()); - } - } else { - const SketchDrawItem& it = items[i++]; - std::vector clicks = it.clicks; - if (it.tool == Mode::TangentArc) { - // It leaves a line or an arc: the entity it names, one the sketch has or one an item before it - // added, else the entity added last. Its start is that entity's end, as the tool's first click - // snaps onto it. - const auto& ents = t.entities(); - if (it.from >= int(ents.size())) - throw std::runtime_error("arc_tangent entity " + std::to_string(it.from) + " does not exist; the sketch has " + - std::to_string(ents.size()) + " entities with the items before it"); - if (ents.empty()) throw CadPrecondition("arc_tangent needs a line or an arc to leave, and the sketch has none"); - const int from = it.from >= 0 ? it.from : int(ents.size()) - 1; - if (ents[from].type != SketchEntity::Type::Line && ents[from].type != SketchEntity::Type::Arc) - throw std::runtime_error("arc_tangent leaves a line or an arc, and " + entity_label(ents, from) + " is neither"); - clicks.insert(clicks.begin(), ents[from].p1); - } - const int at = t.add_shape_scripted(it.tool, clicks, it.sides, it.circumscribed, it.construction, it.from); - if (at < 0 && it.tool == Mode::TangentArc) - throw std::runtime_error("arc_tangent from item " + std::to_string(i - 1) + - " makes no arc: its end must be apart from its start, " + - json::array({clicks[0].x(), clicks[0].y()}).dump() + ", and off the line it leaves along"); - if (at < 0) throw std::runtime_error("the sketch tool built nothing from item " + std::to_string(i - 1)); - shapes.push_back(json{{"first", at}, {"count", int(t.entities().size()) - at}}); - } - } - } catch (...) { - t.restore_drawn_state(kept); - throw; - } - return json{{"ok", true}, {"first_index", before}, {"added", int(t.entities().size()) - before}, - {"shapes", std::move(shapes)}, {"entities", int(t.entities().size())}, {"dof", sketch_dof(t)}}; -} - -// sketch_fillet and sketch_chamfer: the Fillet and Chamfer tools on two picked lines. -json sketch_corner(DesignSketchTool& t, const json& params, bool chamfer) -{ - const std::string what = chamfer ? "chamfer" : "fillet"; - const char* key = chamfer ? "distance" : "radius"; - const auto& ents = t.entities(); - const std::vector lines = entity_picks(params, t); - if (lines.size() != 2 || lines[0] == lines[1]) - throw std::runtime_error(what + " needs two lines, as entities or the selection"); - for (int i : lines) - if (ents[i].type != SketchEntity::Type::Line) - throw std::runtime_error(what + " needs two lines that meet at a corner; " + entity_label(ents, i) + " is not a line"); - const double value = number_arg(params, key); - if (!(value > 0.0)) throw std::runtime_error(std::string(key) + " must be > 0"); - const int a = lines[0], b = lines[1]; - const Vec2d da = ents[a].p1 - ents[a].p0, db = ents[b].p1 - ents[b].p0; - if (std::abs(da.x() * db.y() - da.y() * db.x()) < 1e-12) // the tool's own corner test (op_corner) - throw std::runtime_error(what + " needs two lines that meet at a corner; lines " + std::to_string(a) + " and " + - std::to_string(b) + " are parallel"); - check_sketch_idle(t); - const int cons_before = int(t.constraints().size()); - if (!t.fillet_scripted(a, b, value, chamfer)) - throw std::runtime_error("the " + std::string(key) + " " + json(value).dump() + " overruns a leg of line " + - std::to_string(a) + " or " + std::to_string(b)); - // The new arc or segment is last; every constraint the op added binds it, the rest it released. - const int added = int(ents.size()) - 1, bound = constraints_on(t.constraints(), added); - json r{{"ok", true}, {"entity", added}, {"lines", json::array({a, b})}, - {"released_constraints", cons_before + bound - int(t.constraints().size())}}; - r.update(solve_state(t)); - return r; -} - -// What sketch_offset and sketch_mirror copy: `entities`, else the selection, else every entity. A listed index the -// sketch does not have is refused, and so is one listed twice. -std::vector copy_sources(const json& params, const DesignSketchTool& t, bool& listed) -{ - const json given = param(params, "entities"); - listed = !given.is_null() && !(given.is_array() && given.empty()); - const std::vector out = listed ? entity_indices(given, t.entities()) - : sketch_target_indices(params, t.selection(), int(t.entities().size()), true); - for (size_t i = 0; i < out.size(); ++i) - if (std::find(out.begin(), out.begin() + i, out[i]) != out.begin() + i) - throw std::runtime_error("entity " + std::to_string(out[i]) + " is listed twice"); - return out; -} - -// The constraints `indices` of the open sketch, as sketch_list_constraints writes them. -json constraints_at(const DesignSketchTool& t, const std::vector& indices) -{ - json out = json::array(); - for (int c : indices) out.push_back(entity_constraint_json(t.constraints()[c], c)); - return out; -} - -// sketch_offset: offset copies. The copy of one entity alone is the Offset tool's Confirm, which adds it with no -// constraint inferred and binds it to its source, Parallel for a line and Concentric for an arc or a circle: inferred -// first, the copy of a horizontal or vertical line would be held so, and the solver refuses the redundant Parallel. -// Several entities' copies are added as drawn entities are, bound to nothing. -json sketch_offset(DesignSketchTool& t, const json& params) -{ - if (!params.contains("distance")) throw std::runtime_error("sketch_offset needs 'distance'"); - const double d = number_arg(params, "distance"); - bool listed = false; - const std::vector sources = copy_sources(params, t, listed); - std::vector src; - for (int i : sources) src.push_back(t.entities()[i]); - if (src.empty()) throw CadPrecondition("nothing to offset"); - const auto out = SketchEngine::offset_entities(src, d); - if (out.empty()) throw std::runtime_error("offset produced nothing (ellipses and splines are not offset)"); - const int base = int(t.entities().size()); - std::vector bound; - if (sources.size() == 1) { - check_sketch_idle(t); - if (!t.offset_scripted(sources.front(), d, bound)) throw std::runtime_error("the Offset tool refused the offset"); - } else { - t.add_entities_scripted(out); - } - return json{{"ok", true}, {"first_index", base}, {"added", int(t.entities().size()) - base}, - {"constraints_added", constraints_at(t, bound)}, {"dof", sketch_dof(t)}}; -} - -// sketch_mirror: about `axis`, a line of the sketch or one of its axes, the Mirror tool's Confirm, which binds each -// copy Symmetric to its source; or across the line through axis_a and axis_b, two free points, copies bound to nothing. -json sketch_mirror(DesignSketchTool& t, const json& params) -{ - const auto& ents = t.entities(); - const json axis_v = param(params, "axis"); - bool listed = false; - std::vector targets = copy_sources(params, t, listed); - if (axis_v.is_null()) { - const Vec2d a = params.contains("axis_a") ? point_arg(params, "axis_a") : Vec2d(0, 0); - const Vec2d b = params.contains("axis_b") ? point_arg(params, "axis_b") : Vec2d(0, 1); - if (targets.empty()) throw CadPrecondition("nothing to mirror"); - std::vector src; - for (int i : targets) src.push_back(ents[i]); - const auto out = SketchEngine::mirror_entities(src, a, b); - const int base = t.add_entities_scripted(out); - return json{{"ok", true}, {"first_index", base}, {"added", int(out.size())}, - {"constraints_added", json::array()}, {"dof", sketch_dof(t)}}; - } - if (params.contains("axis_a") || params.contains("axis_b")) - throw std::runtime_error("give axis, or axis_a and axis_b, not both"); - int axis = -1; - if (axis_v == "x_axis") - axis = kSketchRefAxisX; - else if (axis_v == "y_axis") - axis = kSketchRefAxisY; - else if (axis_v.is_number_integer()) - axis = entity_indices(json::array({axis_v}), ents).front(); - else - throw std::runtime_error("axis must be a line's entity index, \"x_axis\" or \"y_axis\""); - if (axis >= 0 && ents[axis].type != SketchEntity::Type::Line) - throw std::runtime_error("axis must be a line of the sketch, \"x_axis\" or \"y_axis\"; " + entity_label(ents, axis) + - " is not a line"); - // The tool takes no pick of its axis as something to mirror. - if (const auto it = std::find(targets.begin(), targets.end(), axis); it != targets.end()) { - if (listed) throw std::runtime_error("entity " + std::to_string(axis) + " is the axis; it is not mirrored about itself"); - targets.erase(it); - } - if (targets.empty()) throw CadPrecondition("nothing to mirror"); - check_sketch_idle(t); - const int base = int(ents.size()); - std::vector kept; - if (!t.mirror_scripted(targets, axis, kept)) throw std::runtime_error("the Mirror tool refused the mirror"); - return json{{"ok", true}, {"first_index", base}, {"added", int(ents.size()) - base}, - {"constraints_added", constraints_at(t, kept)}, {"dof", sketch_dof(t)}}; -} - -// sketch_trim: a Trim click at `at`; sketch_extend (extend): an Extend click there. -json sketch_trim_or_extend(DesignSketchTool& t, const json& params, bool extend) -{ - const Vec2d at = point_arg(params, "at"); - const double tol = params.contains("tolerance") ? number_arg(params, "tolerance") : 0.05; - if (!(tol > 0.0)) throw std::runtime_error("tolerance must be > 0"); - check_sketch_idle(t); - const int cons_before = int(t.constraints().size()); - const auto where = json::array({at.x(), at.y()}).dump(); - int picked = -1; - if (!t.trim_scripted(at, tol, extend, picked)) { - const auto& ents = t.entities(); - if (picked < 0) - throw std::runtime_error("no sketch entity within " + json(tol).dump() + " mm of " + where + "; tolerance widens the search"); - using ET = SketchEntity::Type; - const ET ty = ents[picked].type; - if (extend && ty != ET::Line && ty != ET::Arc) - throw std::runtime_error("extend works on lines and arcs; " + entity_label(ents, picked) + " is neither"); - if (!extend && ty != ET::Line && ty != ET::Arc && ty != ET::Circle) - throw std::runtime_error("trim works on lines, arcs and circles; " + entity_label(ents, picked) + " is none of them"); - throw std::runtime_error(extend ? "extend: " + entity_label(ents, picked) + " reaches no other entity from its end nearest " + where - : "trim: nothing to cut on " + entity_label(ents, picked) + " at " + where + - ": no other entity crosses it beyond that point (a circle needs two crossings)"); - } - json r{{"ok", true}, {"entity", picked}, {"geometry", sketch_entity_to(t.entities()[picked], picked)}, - {"released_constraints", cons_before - int(t.constraints().size())}}; - r.update(solve_state(t)); - return r; -} - -// sketch_transform: the Move, Rotate and Scale tools' Confirm, by params.type. sketch_pattern -// (pattern): the Linear and Polar array tools' Confirm, type linear or circular. -json sketch_transform(DesignSketchTool& t, const json& params, bool pattern) -{ - using Mode = DesignSketchTool::Mode; - using Types = std::vector>; - static const Types kTransforms = {{"move", Mode::Move}, {"rotate", Mode::Rotate}, {"scale", Mode::Scale}}; - static const Types kPatterns = {{"linear", Mode::Array}, {"circular", Mode::PolarArray}}; - const json typev = param(params, "type"); - const char* type = nullptr; - Mode mode = Mode::Move; - for (const auto& [name, m] : pattern ? kPatterns : kTransforms) - if (typev.is_string() && typev.get() == name) { type = name; mode = m; } - if (type == nullptr) throw std::runtime_error(pattern ? "type must be linear or circular" : "type must be move, rotate or scale"); - - // What each type reads; anything else would be ignored, so it is refused. - const bool shifts = mode == Mode::Move || mode == Mode::Array, turns = mode == Mode::Rotate || mode == Mode::PolarArray; - const bool counts = mode == Mode::Array || mode == Mode::PolarArray, pivots = mode != Mode::Move && mode != Mode::Array; - const std::pair takes[] = {{"dx", shifts}, {"dy", shifts}, {"angle", turns}, {"angle_deg", turns}, - {"scale", mode == Mode::Scale}, {"count", counts}, {"pivot", pivots}}; - for (const auto& [key, read] : takes) - if (!read && params.contains(key)) throw std::runtime_error(std::string(type) + " takes no " + key); - - const std::vector targets = entity_picks(params, t); - if (targets.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); - for (size_t i = 0; i < targets.size(); ++i) - if (std::find(targets.begin(), targets.begin() + i, targets[i]) != targets.begin() + i) - throw std::runtime_error("entity " + std::to_string(targets[i]) + " is listed twice"); - const Vec2d delta(params.contains("dx") ? number_arg(params, "dx") : 0.0, params.contains("dy") ? number_arg(params, "dy") : 0.0); - const double angle = angle_arg(params, "angle", mode == Mode::PolarArray ? 2.0 * M_PI : 0.0); - const double scale = params.contains("scale") ? number_arg(params, "scale") : 1.0; - int count = 0; - if (counts) { - const json c = param(params, "count"); - if (!c.is_number_integer() || c.get() < 2 || c.get() > 1000) - throw std::runtime_error(std::string(type) + " needs count, 2 to 1000 instances counting the original"); - count = c.get(); - } - std::optional pivot; - if (params.contains("pivot")) pivot = point_arg(params, "pivot"); - // A transform that moves nothing would still drop the constraints it invalidates. - if (shifts && delta.norm() < 1e-9) throw std::runtime_error(std::string(type) + " needs a non-zero dx or dy"); - if (mode == Mode::Rotate && std::abs(angle) < 1e-12) throw std::runtime_error("rotate needs a non-zero angle (or angle_deg)"); - if (mode == Mode::Scale && (!(scale > 0.0) || std::abs(scale - 1.0) < 1e-12)) - throw std::runtime_error("scale needs a positive factor other than 1"); - if (mode == Mode::PolarArray && !pivot) throw std::runtime_error("circular needs pivot, the centre to array about"); - if (mode == Mode::PolarArray && std::abs(angle) < 1e-12) throw std::runtime_error("circular needs a non-zero angle"); - - check_sketch_idle(t); - const int ents_before = int(t.entities().size()), cons_before = int(t.constraints().size()); - const auto used = t.transform_scripted(mode, targets, delta, angle, scale, count, pivot); - if (!used) throw std::runtime_error("the sketch tool refused the transform"); - json r{{"ok", true}, {"type", type}}; - if (counts) { - r["first_index"] = ents_before; - r["added"] = int(t.entities().size()) - ents_before; - r["bound"] = int(t.constraints().size()) - cons_before; // each copy's ties to its source - } else { - r["moved"] = targets; - r["released_constraints"] = cons_before - int(t.constraints().size()); - } - if (pivots) r["pivot"] = json::array({used->x(), used->y()}); - r.update(solve_state(t)); - return r; -} - -// The constraint type `v` names: SketchConstraintType's name in snake_case, or "equal", the -// CONSTRAIN bar's Equal (equal length, or equal radius for two curves). -SketchConstraintType constraint_type_arg(const json& v) -{ - if (!v.is_string()) - throw std::runtime_error("type must be a constraint type, such as \"parallel\" (tool_describe {tool: \"sketch_constrain\"} lists " - "them, and {tool: \"sketch_dimension\"} the dimensions)"); - const std::string s = v.get(); - if (s == "equal") return SketchConstraintType::EqualLength; - for (size_t i = 0; i < std::size(kConstraintTypes); ++i) - if (s == kConstraintTypes[i]) return SketchConstraintType(i); - std::string close; - for (const char* n : kConstraintTypes) - if (edit_distance(boost::algorithm::to_lower_copy(s), n) <= 2 + s.size() / 4) - close += std::string(close.empty() ? "" : ", ") + "\"" + n + "\""; - throw std::runtime_error("unknown constraint type \"" + s + "\"" + (close.empty() ? "" : "; did you mean " + close) + - " (tool_describe {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)"); -} - -// Why the CONSTRAIN bar refuses a pick, in ConstraintReject order: a code an agent can test and the -// English of the status line's message (constraint_reject_text in DesignPanel.cpp). -const std::pair kConstraintRejects[] = { - {"none", ""}, - {"need_one_entity", "needs an entity: pass entities, or select one"}, - {"need_two_entities", "needs two entities: pass entities, or select them"}, - {"need_a_line", "applies to a line"}, - {"need_two_lines", "applies to two lines"}, - {"need_two_rounds", "needs two circles or arcs"}, - {"need_tangent_pair", "needs a line and a circle or arc, or two circles or arcs"}, - {"need_joinable_points", "needs two entities with a point to join"}, - {"need_measurable_points", "needs two entities with a point to measure between"}, - {"need_point_and_line", "needs a point and a line"}, - {"need_two_points_or_lines", "needs two points or two lines"}, - {"need_axis_line", "needs two entities, then an axis line"}, - {"need_round", "needs a circle or an arc"}, - {"unsupported", "has no CONSTRAIN bar button; name its points with refs instead"}, -}; -static_assert(std::size(kConstraintRejects) == size_t(ConstraintReject::Unsupported) + 1, "every refusal needs a text"); - -// A point reference {entity, role}: "origin", or a point of an entity. The role may be left out -// where the entity has only one point: a point's p0, a circle's or an ellipse's centre. -std::pair point_ref(const json& r, const std::vector& ents, const std::string& what) -{ - if (!r.is_object() || !r.contains("entity")) - throw std::runtime_error(what + " must be {\"entity\": i or \"origin\", \"role\": \"p0\", \"p1\" or \"center\"}"); - const json& e = r.at("entity"); - if (e == "origin") { - if (r.contains("role")) throw std::runtime_error(what + ": the origin is a point and takes no role"); - return {kSketchRefOrigin, SketchPointRole::P0}; - } - if (!e.is_number_integer()) - throw std::runtime_error(what + " names a point: an entity index or \"origin\""); - const int i = entity_indices(json::array({e}), ents).front(); - // The points the solver gives each type (SketchSolver's slots). - using ET = SketchEntity::Type; - using R = SketchPointRole; - std::vector roles; - switch (ents[i].type) { - case ET::Line: case ET::BSpline: roles = {R::P0, R::P1}; break; - case ET::Arc: case ET::EllipseArc: roles = {R::P0, R::P1, R::Center}; break; - case ET::Circle: case ET::Ellipse: roles = {R::Center}; break; - case ET::Point: roles = {R::P0}; break; - } - std::string names; - for (R x : roles) names += (names.empty() ? "" : ", ") + std::string(kPointRoles[int(x)]); - if (!r.contains("role")) { - if (roles.size() == 1) return {i, roles.front()}; - throw std::runtime_error(what + " needs a role: " + entity_label(ents, i) + " has " + names); - } - const R role = R(enum_index(what + " role", r.at("role"), kPointRoles)); - if (std::find(roles.begin(), roles.end(), role) == roles.end()) - throw std::runtime_error(what + ": role \"" + kPointRoles[int(role)] + "\" does not exist on " + entity_label(ents, i) + - " (it has " + names + ")"); - return {i, role}; -} - -// A whole-entity reference {entity}: an entity, or "x_axis" / "y_axis", the sketch's axes. -int entity_ref(const json& r, const std::vector& ents, const std::string& what) -{ - if (!r.is_object() || !r.contains("entity")) - throw std::runtime_error(what + " must be {\"entity\": i, \"x_axis\" or \"y_axis\"}"); - if (r.contains("role")) throw std::runtime_error(what + " is a whole entity and takes no role"); - const json& e = r.at("entity"); - if (e == "x_axis") return kSketchRefAxisX; - if (e == "y_axis") return kSketchRefAxisY; - if (!e.is_number_integer()) throw std::runtime_error(what + " names an entity: an index, \"x_axis\" or \"y_axis\""); - return entity_indices(json::array({e}), ents).front(); -} - -// A constraint from `refs`, as entity_constraint_json writes it: each type's references are points -// (P) or whole entities (E) in the order the solver reads them. -SketchEntityConstraintDef refs_constraint(SketchConstraintType type, const std::string& name, const json& refs, - const std::vector& ents) -{ - using T = SketchConstraintType; - using ET = SketchEntity::Type; - const char* shape = "PP"; - const char* says = "two points"; - switch (type) { - case T::Fix: case T::LockX: case T::LockY: - shape = "P"; says = "one point"; break; - case T::Radius: case T::Diameter: - shape = "E"; says = "one entity"; break; - case T::Concentric: case T::EqualLength: case T::Parallel: case T::Perpendicular: case T::Angle: - case T::Tangent: case T::EqualRadius: case T::Collinear: - shape = "EE"; says = "two entities"; break; - case T::Midpoint: case T::PointOnLine: case T::PointOnObject: - shape = "PE"; says = "a point, then an entity"; break; - case T::Symmetric: - shape = "PPE"; says = "two points, then the axis line"; break; - default: break; - } - if (!refs.is_array() || refs.size() != std::strlen(shape)) - throw std::runtime_error(name + " takes refs: " + says); - SketchEntityConstraintDef d; - d.type = type; - int* ent[3] = {&d.ea, &d.eb, &d.ec}; - SketchPointRole* role[3] = {&d.ra, &d.rb, &d.rc}; - for (size_t k = 0; k < refs.size(); ++k) { - const std::string what = name + " refs[" + std::to_string(k) + "]"; - if (shape[k] == 'P') std::tie(*ent[k], *role[k]) = point_ref(refs[k], ents, what); - else *ent[k] = entity_ref(refs[k], ents, what); - } - // The entity each type acts on, as the planner checks a pick (plan_entity_constraint); the - // solver would drop anything else without a word. The axes are lines, though no segment. - auto line = [&](int e) { return e == kSketchRefAxisX || e == kSketchRefAxisY || (e >= 0 && ents[e].type == ET::Line); }; - auto seg = [&](int e) { return e >= 0 && ents[e].type == ET::Line; }; - auto round = [&](int e) { return e >= 0 && (ents[e].type == ET::Circle || ents[e].type == ET::Arc); }; - auto need = [&](bool ok, int e, const char* kind) { - if (!ok) throw std::runtime_error(name + " needs " + kind + "; " + entity_label(ents, e) + " is not one"); - }; - switch (type) { - case T::Radius: case T::Diameter: - need(round(d.ea), d.ea, "a circle or an arc"); - d.ra = SketchPointRole::Center; - break; - case T::Concentric: case T::EqualRadius: - need(round(d.ea), d.ea, "two circles or arcs"); - need(round(d.eb), d.eb, "two circles or arcs"); - if (type == T::Concentric) d.ra = d.rb = SketchPointRole::Center; - break; - case T::EqualLength: - need(seg(d.ea), d.ea, "two lines"); - need(seg(d.eb), d.eb, "two lines"); - break; - case T::Parallel: case T::Perpendicular: case T::Angle: case T::Collinear: - need(line(d.ea), d.ea, "two lines"); - need(line(d.eb), d.eb, "two lines"); - break; - case T::Tangent: - if (!((round(d.ea) && (line(d.eb) || round(d.eb))) || (line(d.ea) && round(d.eb)))) - throw std::runtime_error(name + " needs a line and a circle or arc, or two circles or arcs; got " + - entity_label(ents, d.ea) + " and " + entity_label(ents, d.eb)); - break; - case T::Midpoint: need(seg(d.eb), d.eb, "a line to sit at the middle of"); break; - case T::PointOnLine: need(line(d.eb), d.eb, "a line"); break; - case T::PointOnObject: need(line(d.eb) || round(d.eb), d.eb, "a line, circle or arc"); break; - case T::Symmetric: need(line(d.ec), d.ec, "an axis line"); break; - default: break; - } - return d; -} - -json constraint_items(const std::vector& cons) -{ - json items = json::array(); - for (size_t i = 0; i < cons.size(); ++i) items.push_back(entity_constraint_json(cons[i], int(i))); - return items; -} - -// Whether `type` is a dimension, which holds a measured value; the other types are geometric. -bool is_dimension(SketchConstraintType type) -{ - using T = SketchConstraintType; - return type == T::Distance || type == T::DistanceX || type == T::DistanceY || type == T::Angle || type == T::Radius || - type == T::Diameter; -} - -// sketch_constrain: a geometric constraint; sketch_dimension (dimension): a dimension. Each is a -// CONSTRAIN bar button on the picks, or a constraint on named points, and refuses the other's types. -json sketch_constrain(DesignSketchTool& t, const json& params, bool dimension) -{ - if (is_dimension(constraint_type_arg(param(params, "type"))) != dimension) { - const std::string type = params.at("type").get(); - throw std::runtime_error(dimension ? type + " is a geometric constraint, which sketch_constrain adds" - : type + " is a dimension, which sketch_dimension adds"); - } - const std::vector defs = cad_constraint_defs(params, t.entities(), t.selection()); - const int first = t.constrain_scripted(defs); - if (first < 0) - throw std::runtime_error("over-constrained: " + param(params, "type").get() + - " was rejected and rolled back (dof " + std::to_string(sketch_dof(t)) + ")"); - json added = json::array(), items = json::array(); - for (int i = first; i < int(t.constraints().size()); ++i) { - added.push_back(i); - items.push_back(entity_constraint_json(t.constraints()[i], i)); - } - json r{{"ok", true}, {"added", std::move(added)}, {"items", std::move(items)}}; - r.update(solve_state(t)); - return r; -} - -json sketch_list_constraints(DesignSketchTool& t, const json&) -{ - json r{{"ok", true}, {"scope", "live"}, {"items", constraint_items(t.constraints())}}; - r.update(solve_state(t)); - return r; -} - -// sketch_delete_constraint: a constraint row's delete button in a sketch session. -json sketch_delete_constraint(DesignSketchTool& t, const json& params) -{ - const json v = param(params, "index"); - if (!v.is_number_integer()) throw std::runtime_error("index must be a constraint index (sketch_list_constraints' items[].index)"); - const int i = v.get(); - if (i < 0 || i >= int(t.constraints().size())) - throw std::runtime_error("constraint " + std::to_string(i) + " is out of range; the sketch has " + - std::to_string(t.constraints().size()) + " constraints"); - json removed = entity_constraint_json(t.constraints()[i], i); - if (!t.remove_constraint(i)) throw std::runtime_error("constraint " + std::to_string(i) + " could not be removed"); - json r{{"ok", true}, {"removed", std::move(removed)}}; - r.update(solve_state(t)); - return r; -} - -// A Design command on the open sketch alone, then a repaint. -json on_open_sketch(DesignPanel* panel, const char* name, const json& params) -{ - json r = cad_sketch_call(mcp_sketch(panel), name, params); - panel->mcp_viewport()->request_repaint(); - return r; -} - -json action_sketch_list_constraints(DesignPanel* panel, const json& params) -{ - const json sketch = param(params, "sketch"); - if (sketch.is_null()) return cad_sketch_call(mcp_sketch(panel), "sketch_list_constraints", params); - // A committed sketch's are read from the document, so no session is needed, nor disturbed. - const CadDocument& doc = panel->mcp_doc(); - const int si = sketch_arg(sketch, doc); - const CadFeature& f = doc.features[si]; - if (f.entities.empty()) - throw std::runtime_error("sketch " + std::to_string(si) + " is not drawn from entities; feature_describe reads its constraints"); - return json{{"ok", true}, {"scope", "committed"}, {"sketch", si}, {"items", constraint_items(f.entity_constraints)}, - {"constraints", int(f.entity_constraints.size())}}; -} - -// --- Text and SVG art ------------------------------------------------------------------ - -// The `position` param: [x, y] in the plane, where the text's or the art's centre goes; the origin when left out. -Vec2d position_arg(const json& params) -{ - const json v = param(params, "position"); - return v.is_null() ? Vec2d::Zero() : point_of(v, "position"); -} - -// sketch_insert_svg's outlines: the filled shapes of the SVG file params.path, centred on the origin and scaled by -// params.scale, as Insert SVG reads them (svg_to_regions()). Throws std::runtime_error for a file that is not there -// and one that gives no outline. -ImportRegions svg_regions(const json& params) -{ - const std::string path = input_path(param(params, "path"), "path"); - const json s = param(params, "scale"); - const double scale = s.is_null() ? 1.0 : s.is_number() ? s.get() : 0.0; - if (!(scale > 0.0) || !std::isfinite(scale)) throw std::runtime_error("scale must be a number above 0"); - ImportRegions regions = svg_to_regions(path, scale); - if (regions.empty()) throw std::runtime_error("the SVG file gives no outline: it has no filled shape, or it is not SVG"); - return regions; -} - -// sketch_insert_svg with a sketch open: the outlines moved by params.position, added as Insert SVG adds them there, -// as lines (DesignSketchTool::add_imported_regions()). -json sketch_insert_svg(DesignSketchTool& t, const json& params) -{ - if (!param(params, "plane").is_null()) throw std::runtime_error("plane is the open sketch's: leave it out"); - const ImportRegions regions = transform_regions(svg_regions(params), position_arg(params), 1.0, 1.0); - const std::size_t before = t.entities().size(); - if (!t.add_imported_regions(regions)) throw std::runtime_error("the SVG file's outlines give no lines"); - return json{{"ok", true}, {"scope", "sketch"}, {"added", int(t.entities().size() - before)}, - {"entities", int(t.entities().size())}}; -} - -// With a sketch open, the outlines go into it (sketch_insert_svg()). Otherwise Insert SVG's art feature on `plane`, XY -// when it is left out or null, in one undo step, with no file dialog and no placement step. -json action_sketch_insert_svg(DesignPanel* panel, const json& params) -{ - if (const DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr && vp->is_sketching()) - return on_open_sketch(panel, "sketch_insert_svg", params); - const ImportRegions regions = svg_regions(params); - const json plane = param(params, "plane"); - int face_body = -1; - const SketchPlane pl = cad_resolve_plane(plane.is_null() ? json("XY") : plane, panel->mcp_doc(), false, &face_body); - const Vec2d at = position_arg(params); - json r = add_feature(panel, "art_index", [&] { return panel->mcp_push_art(regions, _L("SVG"), pl, face_body, at); }); - r["frame"] = frame_json(pl); - return r; -} - -// The Text dialog's Text feature from arguments (DesignPanel::mcp_push_text()), in one undo step, with no dialog and -// no placement step. Every refusal comes before anything changes: the font and the outline are checked first. -json action_sketch_text(DesignPanel* panel, const json& params) -{ - const json text = param(params, "text"); - if (!text.is_string()) throw std::runtime_error("text must be the words to outline"); - const json height = param(params, "height"); - if (!height.is_null() && !(height.is_number() && height.get() >= 0.5 && height.get() <= 500.0)) - throw std::runtime_error("height must be 0.5 to 500 mm"); - const std::string words = text.get(); - const std::string font = params.value("font", std::string()); - const bool bold = params.value("bold", false); - const bool italic = params.value("italic", false); - const double mm = height.is_null() ? 0.0 : height.get(); - int face_body = -1; - const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), panel->mcp_doc(), false, &face_body); - const Vec2d at = position_arg(params); - std::string why; - if (CadFeature outlined; !panel->mcp_outline_text(outlined, words, font, bold, italic, mm, why)) - throw std::runtime_error(why); - json r = add_feature(panel, "text_index", [&] { - const int index = panel->mcp_push_text(words, font, bold, italic, mm, pl, face_body, at, why); - if (index < 0) throw std::runtime_error(why); - return index; - }); - r["frame"] = frame_json(pl); - return r; -} - -// select_geometry: what a click selects in the model at rest, by id (DesignPanel::mcp_select()). An argument given as -// null is left out, as its null default says. The reply is what describe_design reports of the selection. -json action_select_geometry(DesignPanel* panel, const json& params) -{ - using Kind = DesignSelection::Kind; - std::set named; - for (const char* key : {"body", "face", "edges", "vertex", "plane", "sketch", "loop", "feature"}) - if (!param(params, key).is_null()) named.insert(key); - const auto is_form = [&named](std::initializer_list form) { - return named == std::set(form.begin(), form.end()); - }; - const auto index = [¶ms](const char* key) { return params.at(key).get(); }; - DesignSelection s; - if (named.empty()) { - s.kind = Kind::None; - } else if (is_form({"body"})) { - s.kind = Kind::Body; - } else if (is_form({"body", "face"})) { - s.kind = Kind::Face; - s.face = index("face"); - } else if (is_form({"body", "edges"})) { - s.kind = Kind::Edges; - for (const json& e : params.at("edges")) { - if (!e.is_number_integer()) throw std::runtime_error("edges is a list of edge ids"); - s.edges.push_back(e.get()); - } - } else if (is_form({"body", "vertex"})) { - s.kind = Kind::Vertex; - s.vertex = index("vertex"); - } else if (is_form({"plane"})) { - const std::string plane = params.at("plane").get(); - s.kind = Kind::Plane; - s.plane = plane == "XY" ? 0 : plane == "XZ" ? 1 : plane == "YZ" ? 2 : -1; - } else if (is_form({"sketch", "loop"})) { - s.kind = Kind::Loop; - s.sketch = index("sketch"); - s.loop = index("loop"); - } else if (is_form({"feature"})) { - s.kind = Kind::Feature; - s.feature = index("feature"); - } else { - throw std::runtime_error("select_geometry takes one of: body; body with face, edges or vertex; plane; sketch with " - "loop; feature; or nothing, which clears the selection"); - } - if (named.count("body") != 0) s.body = index("body"); - std::string why; - if (!panel->mcp_select(s, why)) throw std::runtime_error(why); - json r{{"ok", true}, - {"selection", selection_json(*panel)}, - {"plane", picked_plane_json(*panel)}, - {"feature", feature_row_json(*panel)}}; - if (s.kind == Kind::Vertex) { - r["point"] = vec3(cad_body_vertices(panel->mcp_doc(), s.body).at(size_t(s.vertex))); - r["placed_point"] = vec3(panel->mcp_viewport()->selected_vertex_point()); - } - return r; -} - -// The tab's Confirm on what is open, as Enter presses it, or the Text dialog's OK. -json action_confirm_tool(DesignPanel* panel, const json&) -{ - DesignPanel::ConfirmOutcome out; - std::string why; - if (!panel->mcp_confirm_tool(out, why)) throw CadPrecondition(why); - return json{{"was", out.was}, - {"ok", out.ok}, - {"feature", out.feature >= 0 ? json(out.feature) : json()}, - {"open", out.open.empty() ? json() : json(out.open)}, - {"status", into_u8(panel->mcp_status())}}; -} - -// The tab's Cancel on what is open, with no dialog, or the Text dialog's Cancel. -json action_cancel_tool(DesignPanel* panel, const json&) -{ - std::string was, why; - if (!panel->mcp_cancel_tool(was, why)) throw CadPrecondition(why); - return json{{"was", was}, {"status", into_u8(panel->mcp_status())}}; -} - -// --- dispatcher --------------------------------------------------------------------- - -} // namespace - -// Every silent form, by the id of the Design table's entry whose tool block describes it: run_cad_tool() and -// register_cad_commands() read this, and the block gives its access. -const std::pair kSilentForms[] = { - {"describe_design", [](DesignPanel* panel, const json&) { return describe_design(panel); }}, - {"select_geometry", action_select_geometry}, - {"confirm_tool", action_confirm_tool}, - {"cancel_tool", action_cancel_tool}, - {"feature_describe", action_feature_describe}, - {"body_describe", body_describe}, - {"measure", measure}, - {"body_mass_properties", body_mass_properties}, - {"body_section", body_section}, - {"body_compare", body_compare}, - {"interference", action_check_interference}, - {"sketch_describe", action_sketch_describe}, - {"sketch_validate", action_sketch_validate}, - {"sketch_list_constraints", action_sketch_list_constraints}, - {"import_step", import_step}, - {"import_mesh", import_mesh}, - {"extrude", action_extrude}, - {"revolve", action_revolve}, - {"fillet", action_fillet}, - {"chamfer", action_chamfer}, - {"hole", action_hole}, - {"boolean", action_boolean}, - {"pattern", action_pattern}, - {"shell", action_shell}, - {"rib", action_rib}, - {"draft", action_draft}, - {"mirror", action_mirror}, - {"body_transform", action_transform}, - {"thicken", action_thicken}, - {"split", action_split}, - {"thread", action_thread}, - {"sweep", action_sweep}, - {"loft", action_loft}, - {"sketch_project", action_sketch_project}, - {"sketch_text", action_sketch_text}, - {"sketch_insert_svg", action_sketch_insert_svg}, - {"delete_face", action_delete_face}, - {"sketch_blend_curve", action_sketch_blend_curve}, - {"construct_axis", action_construct_axis}, - {"construct_coordinate_system", action_construct_coordinate_system}, - {"construct_plane", action_construct_plane}, - {"helix", action_helix}, - {"align", action_align}, - {"list_align_types", action_list_align_types}, - {"set_variable", action_set_variable}, - {"feature_set_expression", action_feature_set_expression}, - {"feature_edit", action_feature_edit}, - {"feature_delete", action_feature_delete}, - {"feature_move", action_feature_move}, - {"feature_suppress", action_feature_suppress}, - {"feature_rename", action_feature_rename}, - {"body_set", action_body_set}, - {"body_delete", action_body_delete}, - {"body_place", action_body_place}, - {"commit_to_plate", action_commit_to_plate}, - {"new_design", action_new_design}, - {"export_step", action_export_step}, - {"surface_extrude", action_surface_extrude}, - {"surface_revolve", action_surface_revolve}, - {"surface_loft", action_surface_loft}, - {"surface_patch", action_surface_patch}, - {"surface_offset", action_surface_offset}, - {"sketch_create", action_sketch_create}, - {"sketch_finish", action_sketch_finish}, - {"sketch_cancel", action_sketch_cancel}, - {"sketch_edit", action_sketch_edit}, - {"sketch_draw", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_draw", a); }}, - {"sketch_select", action_sketch_select}, - {"sketch_delete", action_sketch_delete}, - {"sketch_toggle_construction", action_sketch_toggle_construction}, - {"sketch_offset", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_offset", a); }}, - {"sketch_mirror", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_mirror", a); }}, - {"sketch_repair", action_sketch_repair}, - {"sketch_set_value", action_sketch_set_value}, - {"sketch_fillet", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_fillet", a); }}, - {"sketch_chamfer", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_chamfer", a); }}, - {"sketch_trim", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_trim", a); }}, - {"sketch_extend", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_extend", a); }}, - {"sketch_transform", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_transform", a); }}, - {"sketch_pattern", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_pattern", a); }}, - {"sketch_constrain", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_constrain", a); }}, - {"sketch_dimension", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_dimension", a); }}, - {"sketch_delete_constraint", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_delete_constraint", a); }}, -}; -const std::size_t kSilentFormCount = std::size(kSilentForms); - -json run_guarded(const std::function& run) -{ - try { - return run(); - } catch (const ToolFailure& ex) { - // Its own refusal, code included; one that names no cause is read as a plain exception is. - if (ex.details.is_object() && ex.details.contains("code")) - throw; - throw ToolFailure(ex.what(), with_code(ex.details)); - } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it - throw ToolFailure(std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"), {{"code", "kernel_failure"}}); - } catch (const CadKernelFailure& ex) { - throw ToolFailure(std::string("OCCT: ") + ex.what(), {{"code", "kernel_failure"}}); - } catch (const CadPrecondition& ex) { - throw ToolFailure(ex.what(), {{"code", "precondition"}}); - } catch (const std::exception& ex) { - throw ToolFailure(ex.what(), {{"code", "invalid_argument"}}); - } -} - -ToolFailure no_design_tab() -{ - if (!wxGetApp().is_editor()) - return ToolFailure("The G-code viewer has no Design tab", {{"code", "design_unavailable"}}); - if (!wxGetApp().is_enable_cad_feature()) - return ToolFailure(kCadOffNow, {{"code", "design_unavailable"}}); - return ToolFailure("The Design tab isn't available in this window yet; retry, and if it stays unavailable restart " - "OrcaSlicer (turning the CAD feature on takes effect after a restart)", - {{"code", "design_unavailable"}}); -} - -ToolFailure no_design_view() -{ - return ToolFailure("The Design view is not built in this window; restart OrcaSlicer if it stays so", - {{"code", "design_unavailable"}}); -} - -ToolFailure design_busy(const std::string& why) -{ - return ToolFailure("Design tab busy: " + why, - {{"code", "design_busy"}, - {"hint", "confirm_tool keeps what is open when its Confirm is on (a card, the Text dialog, a body Move, " - "a sketch, Constrain mode) and cancel_tool discards it; a rebuild ends by itself, so call " - "again after it"}}); -} - -std::optional cad_generation(const json& args) -{ - if (!args.is_object() || !args.contains("generation")) - return std::nullopt; - // The numbers the schema's integer type takes (is_whole_number(): a whole float within int64 among them), not - // negative. - const json& g = args["generation"]; - if (!is_whole_number(g) || (!g.is_number_unsigned() && g.get() < 0)) - throw ToolFailure("generation must be an integer of 0 or more, as describe_design or body_describe gave it", - {{"code", "invalid_argument"}}); - return g.is_number_float() ? std::uint64_t(g.get()) : g.get(); -} - -namespace { - -// The silent form of entry `id`, or nullptr. -CadRun find_silent_form(const std::string& id) -{ - for (const auto& [key, run] : kSilentForms) - if (id == key) return run; - return nullptr; -} - -// Why a menu-only entry (a btn: or fly: handler) is refused for a selection it does not accept. -// TRN Refusal of a Design tab tool picked for a selection its right-click menu item is greyed for (Constrain -// sketch with a face selected). -const char* const kDoesNotApply = L("This tool does not apply to what is selected"); -// Why an entry of the sketch's vocabulary is refused outside a sketch, and one of the model's inside one. -// TRN Refusal of a Design tab tool picked outside a sketch, when it is a sketch tool (a line, a rectangle). -const char* const kSketchTool = L("This tool works in a sketch: open a sketch first"); -// TRN Refusal of a Design tab tool picked while a sketch is open, when it works on the model (Extrude, Shell). -const char* const kModelTool = L("This tool works on the model: finish or cancel the sketch first"); - -// The selection kinds the Design tab reports as what is selected (DesignPanel::offer_selection_kind()), as OfferSel -// bits: in a sketch, what is picked there; on the model, nothing, a face, an edge, a vertex, a body or a committed -// sketch's loop. Menu items accept other kinds too (two bodies, a datum, art, a sketch line on the model), which the tab -// never reports, so no selection can be one of them. -uint32_t reported_kinds(bool sketching) -{ - using S = OfferSel; - static const S in_sketch[] = {S::SkNone, S::SkLine, S::SkArc, S::SkPoint, S::Sk2Ent}; - static const S on_model[] = {S::None, S::FacePlanar, S::FaceCyl, S::FaceOther, S::EdgeStr, - S::EdgeCirc, S::Vertex, S::BodySolid, S::BodySheet, S::SkLoop}; - uint32_t bits = 0; - if (sketching) - for (const S kind : in_sketch) bits |= offer_bit(kind); - else - for (const S kind : on_model) bits |= offer_bit(kind); - return bits; -} - -// Item `item`'s handler, for a call of `command` that opens it (opened_item()), as a person's pick of the item or of -// its Speed Dial action runs it: past cad_gate() with no access of its own, so that only a rebuild refuses it, as the -// Design tab's keys and menu are refused by nothing; each tool decides for itself what an open card means to it. The -// handler runs in place, so a modal dialog it opens holds the call, which the core reports as blocked by that dialog. -// It is refused, as open_refusal() says, in the mode the item does not belong to, where the right-click menu does not -// offer it, and for a btn: or fly: handler a selection the menu greys the item for. The reply claims nothing about -// what the handler did, which may be to open a card, start a sketch tool, act at once or tell the person why it -// cannot: it says what the tab shows after it, its busy reason (a card, a dialog or a sketch now open) and its -// status line. Its `tool` is the command called. A call that is not a person's pick, made while a row of the Feature -// list is selected and nothing is picked in the view, targets that row: an item whose handler acts on it (feature_row) -// is not refused for the selection then, and applies. A person's pick keeps the menu's rule, which greys the item. -json open_tool(const DesignTool& item, const char* command, const json& args, bool person) -{ - DesignPanel* panel = cad_gate(CadAccess::None, args); - const int kind = panel->mcp_offer_selection_kind(); - const bool row_target = !person && panel->mcp_feature_row() >= 0 && kind == int(OfferSel::None) && - panel->mcp_picked_plane() < 0; - const bool applies = (row_target && item.feature_row) || (item.accepts & offer_bit(OfferSel(kind))) != 0; - if (std::optional refused = open_refusal(item, panel->mcp_sketch_map_applies(), kind, row_target)) - throw *refused; - const bool text_was_open = panel->mcp_text_dialog_open(); - panel->mcp_run_verb(item.id); - // A dialog the handler opened held the call until it was answered, unless the handler opened the Text dialog, - // which is modeless: the call returns with it open. A Text dialog open before the handler ran is not its dialog. - const bool modal = item.modal && !(panel->mcp_text_dialog_open() && !text_was_open); - std::string why; - const bool busy = panel->mcp_busy(false, false, why); - return json{{"interactive", true}, - {"tool", command}, - {"applies", applies}, - {"modal", modal}, - {"selection_kind", kind}, - {"busy", busy ? json(why) : json()}, - {"status", into_u8(panel->mcp_status())}}; -} - -// The end of the description of entry `t`'s command: the argument sets that name a menu item, its own args and those of -// the items folded into it, each once with the names of the items it opens (items folded in with one set are one tool -// under several labels, as the value items are with {}), so that a search for an item's name finds the command; empty -// when there are none. -std::string opening_calls(const DesignTool& t) -{ - std::vector> sets; // an argument set as JSON text, and its items' names - const auto add = [&sets](const DesignTool& item) { - const std::string args = json::parse(item.args).dump(); - const auto same = std::find_if(sets.begin(), sets.end(), [&args](const auto& set) { return set.first == args; }); - if (same == sets.end()) - sets.emplace_back(args, item.name); - else - same->second += std::string(", ") + item.name; - }; - if (t.action != nullptr && t.args != nullptr) - add(t); - for (const DesignTool& item : kDesignTools) - if (item.fold_into != nullptr && std::strcmp(item.fold_into, t.id) == 0) - add(item); - if (sets.empty()) - return {}; - std::string calls; - for (const auto& [args, names] : sets) - calls += (calls.empty() ? "" : ", ") + args + " (" + names + ")"; - return " Called with exactly one of these argument sets and nothing else, it opens that item's tool of the Design " - "tab for a person, as the menu item does: " + - calls + "."; -} - -// The command of the Design table's entry `t`, which has a handler, a tool block or both, and is no folded item. -NativeCommand design_command(const DesignTool& t) -{ - const json doc = t.doc != nullptr ? json::parse(t.doc) : json(); - json schema; - if (doc.is_null()) - schema = {{"type", "object"}, {"properties", json::object()}, {"additionalProperties", false}}; - else - schema = cad_input_schema(doc); - // The person's form is the call with no arguments where that opens an item's tool, the entry's own or one folded - // into it: it requires nothing (with_silent()), and runs in that item's mode only. - const DesignTool* person_item = opened_item(t, json::object()); - if (person_item != nullptr && !doc.is_null()) { - schema = with_silent(std::move(schema)); - schema["properties"]["silent"]["description"] = std::string(kSilentNote) + " " + mode_note(*person_item, true); - } - - const DesignTool* entry = &t; - NativeCommand c = cad_command( - t.id, t.name, std::move(schema), - [entry](const json& args, bool person) { - if (const DesignTool* item = opened_item(*entry, args)) - return open_tool(*item, entry->id, args, person); - return run_cad_tool(entry->id, silent_args(args)); - }, - [entry](const json& args) { return opened_item(*entry, args) != nullptr; }); - c.has_own_action = t.action != nullptr; - c.icon = t.icon != nullptr ? t.icon : ""; - c.heading = t.section != nullptr ? t.section : ""; - // The items folded into the command keep their actions, each a call of the command with the item's arguments, - // and say what a pick does as a command with a handler only does. - for (const DesignTool& item : kDesignTools) - if (item.fold_into != nullptr && std::strcmp(item.fold_into, t.id) == 0) - c.actions.push_back({{"key", item.id}, - {"title", item.name}, - {"icon", item.icon != nullptr ? item.icon : ""}, - {"description", std::string(item.hint) + ". " + kOpensToolNote + " " + mode_note(item)}, - {"args", json::parse(item.args)}}); - if (doc.is_null()) { - c.description = std::string(t.hint) + ". " + kOpensToolNote + " " + mode_note(t); - return c; - } - if (find_silent_form(t.id) == nullptr) - throw std::logic_error(std::string("The Design table's entry ") + t.id + " has a tool block but no silent form"); - std::string description = doc.at("summary").get(); - if (const std::string details = doc.at("details").get(); !details.empty()) - description += ' ' + details; - if (t.ok_false) description += std::string(" ") + kFailureNote; - description += opening_calls(t); - c.read_only = t.access == CadAccess::Read; - // A read answers the same however often it is asked, as the listed read-only tools say of themselves. - c.idempotent = c.read_only; - c.description = std::move(description); - c.examples = doc.at("examples"); - // commit_to_plate's replace_ids names Prepare's objects by id. - return with_target_ids(std::move(c)); -} - -} // namespace - -const DesignTool* find_design_tool(const std::string& id) -{ - for (const DesignTool& t : kDesignTools) - if (id == t.id) return &t; - return nullptr; -} - -bool is_design_command(const DesignTool& t) { return (t.action != nullptr || t.doc != nullptr) && t.fold_into == nullptr; } - -const DesignTool* opened_item(const DesignTool& entry, const json& args) -{ - // A call with no arguments gives none, null as {}. - const json given = person_form(args) ? json::object() : args; - if (entry.action != nullptr && (given.empty() || (entry.args != nullptr && json::parse(entry.args) == given))) - return &entry; - for (const DesignTool& item : kDesignTools) - if (item.fold_into != nullptr && std::strcmp(item.fold_into, entry.id) == 0 && item.args != nullptr && - json::parse(item.args) == given) - return &item; - return nullptr; -} - -bool offered_in_mode(const DesignTool& t, bool sketching) { return t.sketch_mode == sketching; } - -std::vector design_actions(const CommandCatalog& catalog, bool sketching, bool cad_on) -{ - std::vector actions; - if (!cad_on) return actions; - for (const DesignTool& t : kDesignTools) { - if (t.action == nullptr || !offered_in_mode(t, sketching)) continue; - const auto [command, action] = find_command_action(catalog, t.id); - if (command != nullptr && command->group == kDesignGroup) actions.push_back({command, action}); - } - return actions; -} - -std::optional open_refusal(const DesignTool& t, bool sketching, int kind, bool row_target) -{ - // The message is the person's; the hint names the commands that change the mode. - if (!offered_in_mode(t, sketching)) - return ToolFailure(t.sketch_mode ? kSketchTool : kModelTool, - {{"code", "wrong_mode"}, - {"mode", t.sketch_mode ? "sketch" : "model"}, - // A model tool's: Constrain mode is a sketch to the menu, and the busy gate refuses - // sketch_finish and sketch_cancel there, so the hint names the two that end either. - {"hint", t.sketch_mode ? "sketch_create {plane: \"XY\"} opens a sketch on a plane, sketch_edit " - "{sketch: i} a committed one" : - "confirm_tool keeps the open sketch, or ends Constrain mode, and " - "cancel_tool drops the sketch or leaves Constrain mode"}}); - // The item's handler acts on the Feature list's selected row, and says itself what it cannot do with it. - if (row_target && t.feature_row) - return std::nullopt; - const std::string handler(t.action); - const bool applies = (t.accepts & offer_bit(OfferSel(kind))) != 0; - // Only an item that accepts a kind the tab can report in its mode is greyed for the others; one that accepts none - // (Boolean's items take two bodies, Rib a sketch line) opens as its toolbar button does, whatever is selected. - const bool greyable = (handler.rfind("btn:", 0) == 0 || handler.rfind("fly:", 0) == 0) && - (t.accepts & reported_kinds(t.sketch_mode)) != 0; - if (applies || !greyable) - return std::nullopt; - // The item's own refusal is about the document (no body, no second sketch), which the menu shows only for - // an item that takes the selection; here the selection is the obstacle, so the reply names what to pick. - json accepts = json::array(); - for (int sel = 0; sel < int(OfferSel::Count); ++sel) - if ((t.accepts & offer_bit(OfferSel(sel))) != 0) - accepts.push_back(kDesignSelectionIds[sel]); - return ToolFailure(kDoesNotApply, {{"code", "wrong_selection"}, - {"selection_kind", kind}, - {"selection", kDesignSelectionIds[kind]}, - {"accepts", std::move(accepts)}}); -} - -DesignPanel* cad_gate(CadAccess access, const json& args) -{ - // The MCP server answers before the main window exists and while the app closes. - ui_plater(); - if (!wxGetApp().is_editor() || !wxGetApp().is_enable_cad_feature()) - throw no_design_tab(); - // The panel is built on first use, and in a headless session nobody clicks the tab that would - // build it, so it is built here rather than refused. It is null when no page was made at startup - // (the CAD feature was turned on later), while the page is mid-build, and after its build failed. - DesignPanel* panel = DesignPanel::ensure(); - if (panel == nullptr) - throw no_design_tab(); - - // Only Read commands, the opening of a tool and the Ui commands, which act on what is open, may run under a GUI - // editor or a sketch session they do not own. None may run during a rebuild, not even these: the rebuild's busy - // loop runs this call while the GUI's worker thread holds the document. Checked before hydrating, which writes it. - std::string why; - const bool under_open = access == CadAccess::Read || access == CadAccess::None || access == CadAccess::Ui; - if (panel->mcp_busy(under_open, access == CadAccess::Sketch, why)) - throw design_busy(why); - - // A project opened without ever showing the Design tab has its recipe only in the Model; - // load it, as showing the tab would, before anything reads or writes the document. - panel->hydrate_from_model(); - - // Stale-id guard, checked here rather than in each command's function. - // - // Global face and edge ids are indices into TopExp::MapShapes, valid only against the - // topology that produced them. Every dress-up rewrites those maps, so the natural way to - // drive the Design tab — read the scene once, then issue several operations — silently - // addresses the WRONG edge on every call after the first. Measured on a box: four chamfers - // with ids re-read each time remove 0.400/0.397/0.397/0.395 mm3; the same four with ids - // captured up front remove 0.400/0.008/0.397/0.280. Neither run errors, because a stale id - // still resolves to a real edge — just not the one that was asked for. - // - // So a caller may pass back the "generation" it got from describe_design or body_describe, - // and a mismatch is refused instead of silently obeyed. Optional by design: a call without it - // is not checked, and supplying it is what buys the guarantee. One check here rather than one - // per command, so a command added later cannot forget it. - // - // The type is checked first (cad_generation()), as a caller that skips the schema (run_cad_tool() called - // directly) may pass any: a bare get() on `"generation": "x"` would surface as an internal error - // instead of a parameter error. - if (const std::optional given = cad_generation(args)) { - const uint64_t want = *given; - const uint64_t have = panel->mcp_doc().topo_generation; - if (want != have) - throw ToolFailure("stale face/edge ids: they were read at generation " + std::to_string(want) - + " but the model is now at " + std::to_string(have) - + ". Re-read body_describe and use the new ids — the old ones still name real " - "edges, just not the ones you measured.", - {{"code", "stale_ids"}}); - } - return panel; -} - -json run_cad_tool(const std::string& id, const json& args) -{ - const DesignTool* entry = find_design_tool(id); - const CadRun run = find_silent_form(id); - if (entry == nullptr || run == nullptr) - throw ToolFailure("No Design command runs silently as " + id, {{"code", "no_silent_form"}}); - DesignPanel* panel = cad_gate(entry->access, args); - return run_guarded([&] { return run(panel, args); }); -} - -json cad_undo_redo(bool redo) -{ - DesignPanel* panel = cad_gate(CadAccess::Sketch, json::object()); - return run_guarded([&] { return undo_redo(panel, redo); }); -} - -json cad_input_schema(const json& block) -{ - json properties = json::object(); - json required = json::array(); - for (const json& param : block.at("params")) { - const std::string name = param.at("name").get(); - const std::string type = param.at("type").get(); - json property; - if (type.find('|') != std::string::npos) { - property["type"] = json::array(); - for (std::size_t from = 0;;) { - const std::size_t bar = type.find('|', from); - property["type"].push_back(type.substr(from, bar == std::string::npos ? std::string::npos : bar - from)); - if (bar == std::string::npos) break; - from = bar + 1; - } - } else { - property["type"] = type; - } - if (param.contains("min")) property["minimum"] = param["min"]; - if (param.contains("exclusive_min")) property["exclusiveMinimum"] = param["exclusive_min"]; - if (param.contains("max")) property["maximum"] = param["max"]; - if (param.contains("enum")) property["enum"] = param["enum"]; - if (param.contains("default")) property["default"] = param["default"]; - else required.push_back(name); - // A param whose default is null is one its function reads as left out when it is null (no limit, the open - // sketch), so a call may give null. One marked "nullable": false, whose function reads a null as given, - // keeps its type. - if (param.contains("default") && param["default"].is_null() && param.value("nullable", true)) { - if (!property["type"].is_array()) property["type"] = json::array({property["type"]}); - property["type"].push_back("null"); - if (property.contains("enum")) property["enum"].push_back(nullptr); - } - std::string description = param.value("description", std::string()); - if (const std::string unit = param.value("unit", std::string()); !unit.empty()) - description = description.empty() ? "In " + unit + "." : description + " (" + unit + ")"; - if (!description.empty()) property["description"] = std::move(description); - properties[name] = std::move(property); - } - properties["generation"] = {{"type", "integer"}, {"minimum", 0}, {"description", kGenerationNote}}; - json schema{{"type", "object"}, {"properties", std::move(properties)}, {"additionalProperties", false}}; - if (!required.empty()) schema["required"] = std::move(required); - return schema; -} - -namespace { - -// A Design function's value as its command replies with it: without "ok": true and an empty "error", which say -// nothing that a reply other than an error doesn't. An ok false, and an error's text beside it, stay. -json design_reply(json value) -{ - if (value.is_object()) { - if (const auto ok = value.find("ok"); ok != value.end() && *ok == true) - value.erase(ok); - if (const auto error = value.find("error"); error != value.end() && *error == "") - value.erase(error); - } - return value; -} - -} // namespace - -NativeCommand cad_command(std::string key, std::string title, json schema, - std::function fn, std::function opens) -{ - NativeCommand c; - c.key = std::move(key); - c.title = std::move(title); - c.group = kDesignGroup; - c.input_schema = std::move(schema); - c.run = [fn = std::move(fn), opens = std::move(opens)](const json& args, ToolContext& ctx) { - if (ctx.person()) { - try { - return ToolResult::ok(design_reply(fn(args, true))); - } catch (const ToolFailure& refused) { - // What the person reads, in the UI's language where the text is a msgid (an entry's refusal). Looked - // up in the application's catalogue only, as the right-click menu's items are (show_offer_menu()), so - // that a wxWidgets entry cannot answer for it. - throw ToolFailure(into_u8(wxGetTranslation(wxString::FromUTF8(refused.what()), SLIC3R_APP_KEY)), refused.details); - } - } - // `generation` guards ids within this session only: a replay rebuilds the same ids by replaying - // the history, but reaches another generation number, so a recorded one would refuse the replay. - // Journal the call without it. - json recorded = args; - if (recorded.is_object()) recorded.erase("generation"); - // A call that ran may be recorded, without its generation, as one that opens a tool (one with no arguments): - // with silent, its replay runs too. - if (opens && recorded.is_object() && !opens(args) && opens(recorded)) - recorded["silent"] = true; - ctx.set_journal_args(std::move(recorded)); - json result = ctx.run_ui([&] { return fn(args, false); }); - settle(ctx); - return ToolResult::ok(design_reply(std::move(result))); - }; - return c; -} - -void register_cad_commands(CommandCatalog& catalog) -{ - // Heading by heading, as tool_list's description indexes them, so that its listing of the group reads in the - // same order. Every command has a heading (DesignTool::section). - for (const char* section : kDesignSections) - for (const DesignTool& t : kDesignTools) - if (is_design_command(t) && t.section != nullptr && std::strcmp(t.section, section) == 0) - catalog.add(design_command(t)); -} - -void leave_out_cad_commands(CommandCatalog& catalog, bool editor) -{ - // A folded item's id too, which is no command but names an action. - for (const DesignTool& t : kDesignTools) - if (t.action != nullptr || t.doc != nullptr) - catalog.leave_out(t.id, editor ? kCadOffAtStartup : kNoDesignInViewer, "design_unavailable"); -} - -std::vector sketch_target_indices(const json& params, const std::vector& selection, int entity_count, bool all_if_empty) -{ - std::vector out; - // An empty list names nothing, so it reads as left out, as the schema's default [] says and as - // entity_picks() reads it. Anything else that is given names what it holds. - if (const auto given = params.find("entities"); given != params.end() && !(given->is_array() && given->empty())) { - for (const auto& v : *given) out.push_back(v.get()); - return out; - } - out = selection; - if (out.empty() && all_if_empty) - for (int i = 0; i < entity_count; ++i) out.push_back(i); - return out; -} - -std::string design_command_index() -{ - std::string index = " The Design tab's CAD commands (sketches, solid and surface features, bodies, measurements) follow " - "by heading; `tool_list {group: \"Design\"}` says what each does and `tool_describe {tool}` gives one's " - "manual. One whose schema has `silent` does what its menu item does when called with no arguments, " - "unless `silent` is true."; - for (const char* section : kDesignSections) { - std::string names; - for (const DesignTool& t : kDesignTools) - if (t.section != nullptr && std::strcmp(t.section, section) == 0) - names += (names.empty() ? "" : ", ") + std::string("`") + t.id + "`"; - index += std::string(" ") + section; - if (std::strcmp(section, "Menu items") == 0) - index += ", which take no arguments and do what their item of the right-click menu does"; - index += ": " + names + "."; - } - return index; -} - -json cad_note(const CommandCatalog& catalog) -{ - if (!wxGetApp().is_editor()) - return nullptr; - const std::vector& commands = catalog.commands(); - const bool registered = std::any_of(commands.begin(), commands.end(), [](const NativeCommand& c) { return c.group == kDesignGroup; }); - return registered && wxGetApp().is_enable_cad_feature() ? json() : json(kCadOffNote); -} - -SketchPlane cad_resolve_plane(const json& plane, const CadDocument& doc, bool drill, int* face_body) -{ - static const std::string kForms = - "plane must be \"XY\", \"XZ\", \"YZ\", {\"datum\": i} or {\"body\": b, \"face\": f}"; - if (plane.is_string()) { - // The base planes through the modeling origin, as the GUI's plane list offers them. - const std::string n = plane.get(); - SketchPlane pl; - if (n == "XY") pl = SketchPlane::XY(); - else if (n == "XZ") pl = SketchPlane::XZ(); - else if (n == "YZ") pl = SketchPlane::YZ(); - else throw std::runtime_error(kForms); - pl.origin += doc.modeling_origin; - return pl; - } - if (plane.is_object() && plane.size() == 1 && plane.contains("datum") && plane["datum"].is_number_integer()) { - // A datum is named by its feature index; the kernel lists the enabled Plane features in - // order, so its position there is the count of enabled Plane features before it. - const int fi = plane["datum"].get(); - if (fi < 0 || fi >= int(doc.features.size())) - throw std::runtime_error("datum " + std::to_string(fi) + " is not a feature (the design has " + - std::to_string(doc.features.size()) + ")"); - const CadFeature& f = doc.features[fi]; - if (f.type != CadFeatureType::Plane) - throw std::runtime_error("feature " + std::to_string(fi) + " (" + feature_type_name(f.type) + - ") is not a datum plane"); - if (!f.enabled) - throw CadPrecondition("datum plane " + std::to_string(fi) + " is hidden; show it first"); - const int ordinal = datum_ordinal(doc, fi); - const auto datums = doc.resolve_datum_planes(); - if (ordinal >= int(datums.size())) - throw CadPrecondition("datum plane " + std::to_string(fi) + " could not be resolved"); - return datums[ordinal].second; - } - if (plane.is_object() && plane.size() == 2 && plane.contains("body") && plane.contains("face") && - plane["body"].is_number_integer() && plane["face"].is_number_integer()) { - const int b = plane["body"].get(), fi = plane["face"].get(); - if (b < 0 || b >= int(doc.bodies.size())) - throw std::runtime_error("body " + std::to_string(b) + " is out of range (have " + - std::to_string(doc.bodies.size()) + ")"); - const TopoDS_Face face = GeometryEngine::face_by_index(doc.bodies[b].shape, fi); - if (face.IsNull()) - throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " does not exist (it has " + - std::to_string(GeometryEngine::face_count(doc.bodies[b].shape)) + " faces)"); - if (BRepAdaptor_Surface(face).GetType() != GeomAbs_Plane) - throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " is " + - face_kind_name(face) + "; a plane needs a planar face"); - SketchPlane pl; - if (!(drill ? doc.inward_plane_of_face(b, fi, pl) : doc.plane_of_face(b, fi, pl))) - throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " has no plane"); - if (face_body != nullptr) *face_body = b; - return pl; - } - throw std::runtime_error(kForms); -} - -json cad_feature_json(const CadDocument& doc, int index) -{ - check_feature_index(index, doc); - const CadFeature& f = doc.features[index]; - json j = feature_card(f); - j["index"] = index; - j["type"] = feature_type_name(f.type); - j["name"] = f.name; - j["suppressed"] = !f.enabled; - - // The plane the recipe builds on: a datum's resolved frame, or the plane the feature holds. - using T = CadFeatureType; - const bool own_profile = f.type != T::Sketch && f.sketch_ref < 0 && (!f.entities.empty() || !f.profile.points.empty()); - if (f.type == T::Plane) { - const auto datums = doc.resolve_datum_planes(); - const int ordinal = datum_ordinal(doc, index); - if (f.enabled && ordinal < int(datums.size())) j["plane"] = plane_json(datums[ordinal].second, doc.modeling_origin); - } else if (f.type == T::Sketch || f.type == T::Hole || f.type == T::Thread || f.type == T::Helix || f.type == T::Pattern || - f.type == T::Mirror || f.type == T::Project || (f.type == T::Cut && f.cut_face < 0) || own_profile) { - j["plane"] = plane_json(f.plane, doc.modeling_origin); - } - - // A sketch's geometry, or the loop an extrude or revolve carries itself; points are in the - // plane's frame. - if (!f.entities.empty()) { - json entities = json::array(), constraints = json::array(); - for (size_t i = 0; i < f.entities.size(); ++i) entities.push_back(sketch_entity_to(f.entities[i], int(i))); - for (size_t i = 0; i < f.entity_constraints.size(); ++i) - constraints.push_back(entity_constraint_json(f.entity_constraints[i], int(i))); - j["entities"] = std::move(entities); - j["constraints"] = std::move(constraints); - } else if (!f.profile.points.empty()) { - json points = json::array(), constraints = json::array(); - for (const Vec2d& p : f.profile.points) points.push_back(json::array({p.x(), p.y()})); - for (size_t i = 0; i < f.constraints.size(); ++i) constraints.push_back(profile_constraint_json(f.constraints[i], int(i))); - j["profile"] = json{{"points", std::move(points)}, {"closed", f.profile.closed}}; - j["constraints"] = std::move(constraints); - } - - // What consumes this feature: the references remove_feature() remaps, and for a datum plane - // the features built on it. - const int datum = f.type == T::Plane && f.enabled ? 3 + datum_ordinal(doc, index) : -1; - json used_by = json::array(); - for (int i = 0; i < int(doc.features.size()); ++i) { - bool uses = false; - CadDocument::for_each_feature_ref(doc.features[i], [&](int r) { uses = uses || r == index; }); - if (datum >= 0) CadDocument::for_each_datum_ref(doc.features[i], [&](int r) { uses = uses || r == datum; }); - if (uses) used_by.push_back(i); - } - json made = json::array(); - for (size_t b = 0; b < doc.bodies.size(); ++b) - if (doc.bodies[b].source_feature == index) made.push_back(int(b)); - j["used_by"] = std::move(used_by); - j["bodies_made"] = std::move(made); - for (const auto& [mate, reason] : doc.mate_conflicts) - if (mate == index) j["conflict"] = reason; - - // The model its body indices and face and edge ids are read in: the one just before it, which feature_edit's - // refs take, but for a datum, which the engine resolves against the finished model (for_each_body_ref()). - j["ids_of"] = f.type == T::Plane || f.type == T::Axis || f.type == T::CoordSys ? "finished" : "before"; - // As the last rebuild recorded them, named as the bodies they became are; null where that rebuild did not reach. - json before = nullptr; - if (size_t(index) < doc.bodies_before.size() && doc.bodies_before[size_t(index)]) { - before = json::array(); - const std::vector& was = *doc.bodies_before[size_t(index)]; - for (size_t b = 0; b < was.size(); ++b) { - const int now = doc.body_index(was[b].id); - const CadBody* body = now >= 0 ? &doc.bodies[size_t(now)] : nullptr; - before.push_back(json{{"index", int(b)}, {"name", body != nullptr && body->has_user_name ? body->user_name : was[b].name}}); - } - } - j["bodies_before"] = std::move(before); - return j; -} - -json cad_feature_changes(const json& was, const json& now) -{ - json changed = json::object(); - for (const char* part : {"params", "refs"}) { - const json before = was.value(part, json::object()), after = now.value(part, json::object()); - for (const auto& [k, v] : after.items()) { - const json old = before.value(k, json()); - if (old != v) changed[k] = json::array({old, v}); - } - } - // The plane a Mirror, a Helix or a Cut builds on is reported beside them, and a re-point of it is a change too. - const json old_plane = was.value("plane", json()), new_plane = now.value("plane", json()); - if (old_plane != new_plane) changed["plane"] = json::array({old_plane, new_plane}); - return changed; -} - -void cad_apply_feature_fields(CadFeature& f, const json& fields) -{ - if (!fields.is_object() || fields.empty()) - throw std::runtime_error("fields must name the fields to change, as {\"distance\": 15}"); - const json card = feature_card(f); - const json& editable = card["editable"]; - const json& ranges = card["ranges"]; - const std::string type = feature_type_name(f.type); - if (editable.empty()) - throw std::runtime_error(type + ": no field feature_edit can change; its inputs are geometry or picks"); - if (fields.contains("thread_diameter") && fields.contains("thread_radius")) - throw std::runtime_error("give thread_diameter or thread_radius, not both"); - // The two are one value, so a binding on either drives both. - auto same_value = [](const std::string& a, const std::string& b) { - auto thread_size = [](const std::string& k) { return k == "thread_diameter" || k == "thread_radius"; }; - return a == b || (thread_size(a) && thread_size(b)); - }; - - CadFeature edited = f; - for (const auto& [key, v] : fields.items()) { - if (std::find(editable.begin(), editable.end(), json(key)) == editable.end()) { - std::string list; - for (const json& e : editable) list += (list.empty() ? "" : ", ") + e.get(); - throw std::runtime_error(type + ": '" + key + "' is not an editable field; editable: " + list); - } - // Every rebuild writes a bound field from its expression, so a literal would not last. - for (const auto& [bound, e] : f.expr) - if (same_value(bound, key)) - throw std::runtime_error(key + " is driven by the expression '" + e + "'; change it with set_variable, or " - "remove the binding with feature_set_expression {field: '" + bound + "', expr: ''}"); - const auto range = ranges.find(key); - if (range == ranges.end()) { - set_card_choice(edited, key, v); - continue; - } - if (!v.is_number()) throw std::runtime_error(key + " must be a number"); - const double x = v.get(), lo = (*range)[0].get(), hi = (*range)[1].get(); - if (!(x >= lo && x <= hi)) throw std::runtime_error(Slic3r::format("%1% must be between %2% and %3%", key, lo, hi)); - if (key == "pattern_count" && x != std::floor(x)) throw std::runtime_error("pattern_count must be a whole number"); - CadDocument::set_numeric_field(edited, key, x); - } - f = std::move(edited); -} - -CadDocument cad_document_before(const CadDocument& doc, int feature) -{ - check_feature_index(feature, doc); - CadDocument before = doc.history_before(feature); - if (!before.recompute()) - throw ToolFailure("the model before feature " + std::to_string(feature) + " (" + doc.features[size_t(feature)].name + - ") does not rebuild: " + (before.error.empty() ? std::string("no reason given") : before.error), - {{"code", "rebuild_failed"}}); - return before; -} - -std::vector cad_body_vertices(const CadDocument& doc, int body) -{ - TopTools_IndexedMapOfShape map; - TopExp::MapShapes(body_shape(doc, json{{"body", body}}), TopAbs_VERTEX, map); - std::vector out; - out.reserve(size_t(map.Extent())); - for (int i = 1; i <= map.Extent(); ++i) { - const gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(map(i))); - out.emplace_back(p.X(), p.Y(), p.Z()); - } - return out; -} - -namespace { - -// "feature 5 (Sweep 6)": the feature whose refs feature_edit writes, as its refusals name it. -std::string feature_label(const CadDocument& doc, int index) -{ - return "feature " + std::to_string(index) + " (" + doc.features[size_t(index)].name + ")"; -} - -// The names feature_edit's refs takes for a feature of type `t`: those of feature_describe's refs that its card can -// pick again when it edits. Empty for a type whose card picks nothing again, and for an Extrude, whose profile and -// target are fixed. -std::vector ref_names(CadFeatureType t) -{ - using T = CadFeatureType; - switch (t) { - case T::Revolve: return {"revolve_axis_entity", "target_body"}; - case T::SurfaceRevolve: return {"revolve_axis_entity"}; - case T::Sweep: return {"sweep_path_ref", "target_body"}; - case T::Loft: return {"loft_profile_refs", "target_body"}; - case T::SurfaceLoft: return {"loft_profile_refs"}; - case T::Boolean: return {"target_body", "bool_tool_body"}; - case T::Mirror: - case T::Cut: - case T::Hole: - case T::Thread: return {"plane", "target_body"}; - case T::Helix: return {"plane"}; - case T::Rib: return {"rib_sketch_ref", "rib_entity", "target_body"}; - case T::Mate: return {"mate_cs_a", "mate_cs_b"}; - case T::Fillet: - case T::Chamfer: return {"edges", "face_group", "target_body"}; - case T::Shell: return {"shell_face", "target_body"}; - case T::Draft: return {"draft_face", "target_body"}; - case T::Thicken: return {"thicken_face", "target_body"}; - case T::DeleteFace: return {"delete_faces", "target_body"}; - case T::Plane: - return {"plane_type", "plane_base", "plane_axis", "plane_face_body", "plane_face", "plane_face2_body", "plane_face2", - "plane_edge_body", "plane_edge", "plane_edge2_body", "plane_edge2"}; - case T::Axis: - return {"axis_type", "axis_p1", "axis_p2", "axis_body", "axis_face", "axis_edge", "axis_plane_a", "axis_plane_b"}; - case T::CoordSys: - return {"coordsys_type", "coordsys_point", "coordsys_body", "coordsys_face", "coordsys_edge", "coordsys_x_hint"}; - case T::Pattern: - case T::Transform: - case T::ThickenSurface: - case T::SurfaceOffset: return {"target_body"}; - default: return {}; - } -} - -// Reads the values of feature_edit's refs for features[index] of `doc`, whose body indices and face and edge ids -// name those of `ids`: the model before the feature, or for a datum the finished model, `doc` itself. -struct RefReader -{ - const CadDocument& ids; - const CadDocument& doc; - int index; - bool finished; // `ids` is the finished model, a datum's - std::string at; // feature_label() of the feature - - // Where `ids` stands, as a refusal says it. - std::string where() const { return finished ? "in the finished model" : "before " + at; } - - int integer(const std::string& name, const json& v, const char* what) const - { - if (!v.is_number_integer()) throw std::runtime_error(name + " must be " + what); - return v.get(); - } - - // A feature before the one edited, of one of `types`, which `kinds` names. - int earlier(const std::string& name, const json& v, std::initializer_list types, const char* kinds) const - { - const int fi = integer(name, v, "a feature index (describe_design's features[].index)"); - if (fi < 0 || fi >= index) - throw std::runtime_error(name + " " + std::to_string(fi) + " is not an earlier feature: it must come before " + at); - const CadFeatureType t = doc.features[size_t(fi)].type; - if (std::find(types.begin(), types.end(), t) == types.end()) - throw std::runtime_error(name + " " + std::to_string(fi) + " (" + feature_type_name(t) + ") is not " + kinds); - return fi; - } - - // A body of `ids`, or -1 where `unset` names what -1 stands for. - int body(const std::string& name, const json& v, const char* unset) const - { - const int b = integer(name, v, unset != nullptr ? "a body index, or -1" : "a body index"); - if (unset != nullptr && b == -1) return b; - const int n = int(ids.bodies.size()); - if (b < 0 || b >= n) - throw std::runtime_error(name + " " + std::to_string(b) + " is not a body " + where() + ": there " + - (finished ? (n == 1 ? "is 1 body" : "are " + std::to_string(n) + " bodies") - : (n == 1 ? "was 1 body" : "were " + std::to_string(n) + " bodies"))); - return b; - } - - // The body a feature's target_body names in `ids`: -1 is the last one. - int target(int b) const - { - if (b >= 0) return b; - if (ids.bodies.empty()) throw CadPrecondition("there is no body " + where()); - return int(ids.bodies.size()) - 1; - } - - // Face (`edges` false) or edge ids, each of body `b` of `ids`. - void on_body(const std::vector& list, int b, bool edges) const - { - const TopoDS_Shape& shape = ids.bodies[size_t(b)].shape; - const int n = edges ? GeometryEngine::edge_count(shape) : GeometryEngine::face_count(shape); - const char* kind = edges ? "edge" : "face"; - for (const int id : list) - if (id < 0 || id >= n) - throw std::runtime_error(std::string(kind) + " " + std::to_string(id) + " of body " + std::to_string(b) + " does not exist " + - where() + ": the body " + (finished ? "has " : "had ") + std::to_string(n) + " " + kind + "s" + - (finished ? "" : " there")); - } - - // One id, or for `many` a list of distinct ids. - std::vector id_list(const std::string& name, const json& v, bool many) const - { - std::vector out; - if (many && v.is_array()) { - for (const json& e : v) { - if (!e.is_number_integer()) throw std::runtime_error(name + " must be ids from body_describe"); - if (std::find(out.begin(), out.end(), e.get()) != out.end()) - throw std::runtime_error(name + ": " + std::to_string(e.get()) + " is listed twice"); - out.push_back(e.get()); - } - if (out.empty()) throw std::runtime_error(name + " is an empty list"); - return out; - } - out.push_back(integer(name, v, many ? "an id or a list of ids from body_describe" : "an id from body_describe")); - return out; - } - - // A datum-plane reference: 0, 1 or 2 for XY, XZ or YZ, or 3 + N for the Nth shown Plane feature, which must come - // before the feature edited; -1 where `unset` allows it. - int datum(const std::string& name, const json& v, bool unset) const - { - const int d = integer(name, v, "0, 1 or 2 (XY, XZ or YZ), or 3 + N for the Nth shown datum plane"); - if ((unset && d == -1) || (d >= 0 && d < 3)) return d; - int seen = 0; - for (int i = 0; d >= 3 && i < index; ++i) - if (doc.features[size_t(i)].type == CadFeatureType::Plane && doc.features[size_t(i)].enabled && seen++ == d - 3) - return d; - throw std::runtime_error(name + " " + std::to_string(d) + " names no datum plane before " + at); - } -}; - -// A point or direction [x, y, z] of a datum's refs. -Vec3d vec3_ref(const std::string& name, const json& v, bool direction) -{ - if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) - throw std::runtime_error(name + " must be [x, y, z]"); - const Vec3d p(v[0].get(), v[1].get(), v[2].get()); - if (direction && !(p.norm() > 1e-9)) throw std::runtime_error(name + " must not be zero"); - return p; -} - -// The refs of a Plane, an Axis and a CoordSys: their types, points and datum references, and bodies, faces and edges -// of the finished model. -void apply_datum_refs(CadFeature& g, const json& refs, const RefReader& r) -{ - using T = CadFeatureType; - const auto given = [&](const char* k) { return refs.contains(k); }; - const auto body = [&](const char* k, int& field) { if (given(k)) field = r.body(k, refs[k], "unset"); }; - const auto id = [&](const char* k, int& field) { if (given(k)) field = r.integer(k, refs[k], "an id from body_describe, or -1"); }; - // A face or an edge set on a body: one of that body's, in the finished model. - const auto check = [&](int b, int ref, bool edges, const char* k) { - if (ref < 0) return; - if (b < 0) throw std::runtime_error(std::string(k) + " " + std::to_string(ref) + " is on no body: give its body too"); - r.on_body({ref}, b, edges); - }; - if (g.type == T::Plane) { - if (given("plane_type")) g.plane_type = PlaneType(enum_index("plane_type", refs["plane_type"], kPlaneTypes)); - if (given("plane_base")) g.plane_base = r.datum("plane_base", refs["plane_base"], false); - if (given("plane_axis")) { - g.plane_axis = r.integer("plane_axis", refs["plane_axis"], "0 (the base's X) or 1 (its Y)"); - if (g.plane_axis != 0 && g.plane_axis != 1) throw std::runtime_error("plane_axis must be 0 (the base's X) or 1 (its Y)"); - } - body("plane_face_body", g.plane_face_body); - id("plane_face", g.plane_face); - body("plane_face2_body", g.plane_face2_body); - id("plane_face2", g.plane_face2); - body("plane_edge_body", g.plane_edge_body); - id("plane_edge", g.plane_edge); - body("plane_edge2_body", g.plane_edge2_body); - id("plane_edge2", g.plane_edge2); - check(g.plane_face_body, g.plane_face, false, "plane_face"); - check(g.plane_face2_body, g.plane_face2, false, "plane_face2"); - check(g.plane_edge_body, g.plane_edge, true, "plane_edge"); - check(g.plane_edge2_body, g.plane_edge2, true, "plane_edge2"); - // What the Plane card's Confirm refuses, which the rebuild would not: an unresolved plane falls back silently. - if (const std::string why = r.doc.datum_plane_refusal(g); !why.empty()) throw std::runtime_error(why); - } else if (g.type == T::Axis) { - if (given("axis_type")) g.axis_type = AxisType(enum_index("axis_type", refs["axis_type"], kAxisTypes)); - if (given("axis_p1")) g.axis_p1 = vec3_ref("axis_p1", refs["axis_p1"], false); - if (given("axis_p2")) g.axis_p2 = vec3_ref("axis_p2", refs["axis_p2"], false); - body("axis_body", g.axis_body); - id("axis_face", g.axis_face); - id("axis_edge", g.axis_edge); - if (given("axis_plane_a")) g.axis_plane_a = r.datum("axis_plane_a", refs["axis_plane_a"], true); - if (given("axis_plane_b")) g.axis_plane_b = r.datum("axis_plane_b", refs["axis_plane_b"], true); - check(g.axis_body, g.axis_face, false, "axis_face"); - check(g.axis_body, g.axis_edge, true, "axis_edge"); - } else { - if (given("coordsys_type")) g.coordsys_type = CoordSysType(enum_index("coordsys_type", refs["coordsys_type"], kCoordSysTypes)); - if (given("coordsys_point")) g.coordsys_point = vec3_ref("coordsys_point", refs["coordsys_point"], false); - if (given("coordsys_x_hint")) g.coordsys_x_hint = vec3_ref("coordsys_x_hint", refs["coordsys_x_hint"], true); - body("coordsys_body", g.coordsys_body); - id("coordsys_face", g.coordsys_face); - id("coordsys_edge", g.coordsys_edge); - check(g.coordsys_body, g.coordsys_face, false, "coordsys_face"); - check(g.coordsys_body, g.coordsys_edge, true, "coordsys_edge"); - } -} - -// The refs of every other type, read in the model before the feature (`r.ids`). -void apply_model_refs(CadFeature& g, const json& refs, const RefReader& r) -{ - using T = CadFeatureType; - const auto given = [&](const char* k) { return refs.contains(k); }; - const CadDocument& doc = r.doc; - if (given("target_body")) g.target_body = r.body("target_body", refs["target_body"], g.type == T::Boolean ? nullptr : "the last body"); - - if (given("revolve_axis_entity")) { - // A line of the sketch the revolve turns, or of the profile it carries itself. - const int e = r.integer("revolve_axis_entity", refs["revolve_axis_entity"], "a line of the feature's sketch (entity index), or -1 for the plane axis"); - const bool own = g.sketch_ref < 0 || g.sketch_ref >= int(doc.features.size()); - if (e != -1 && !revolve_line(own ? g.entities : doc.features[size_t(g.sketch_ref)].entities, e)) - throw std::runtime_error("revolve_axis_entity " + std::to_string(e) + " is not a line of " + - (own ? std::string("its profile") : "sketch " + std::to_string(g.sketch_ref))); - g.revolve_axis_entity = e; - } - if (given("sweep_path_ref")) { - g.sweep_path_ref = r.earlier("sweep_path_ref", refs["sweep_path_ref"], {T::Sketch, T::Helix}, "a Sketch or a Helix"); - if (g.sweep_path_ref == g.sketch_ref) throw std::runtime_error("sweep_path_ref cannot be the profile sketch itself"); - } - if (given("loft_profile_refs")) { - const json& v = refs["loft_profile_refs"]; - if (!v.is_array() || v.size() < 2) throw std::runtime_error("loft_profile_refs must be two or more sketch feature indices, in loft order"); - std::vector profiles; - for (const json& p : v) { - const int s = r.earlier("loft_profile_refs", p, {T::Sketch, T::Project}, "a Sketch"); - if (std::find(profiles.begin(), profiles.end(), s) != profiles.end()) - throw std::runtime_error("loft_profile_refs: sketch " + std::to_string(s) + " is listed twice"); - profiles.push_back(s); - } - g.loft_profile_refs = std::move(profiles); - } - if (given("bool_tool_body")) g.bool_tool_body = r.body("bool_tool_body", refs["bool_tool_body"], nullptr); - // A Boolean's two operands; for every other type bool_tool_body is unused, and target_body -1 is the last body. - if (g.type == T::Boolean && (given("target_body") || given("bool_tool_body")) && g.target_body == g.bool_tool_body) - throw std::runtime_error("target_body and bool_tool_body must be two different bodies"); - - if (given("plane")) { - // A face is one of the model before the feature; a datum's frame is the finished model's, as a card's plane - // list resolves it. A hole or a thread drills the face's own body, as on its card. - const json& v = refs["plane"]; - const bool drill = g.type == T::Hole || g.type == T::Thread; - int face_body = -1; - if (v.is_object() && v.contains("datum")) { - if (const json d = v["datum"]; d.is_number_integer() && (d.get() < 0 || d.get() >= r.index)) - throw std::runtime_error("plane's datum " + std::to_string(d.get()) + " is not an earlier feature: it must come before " + r.at); - g.plane = cad_resolve_plane(v, doc, drill); - } else { - g.plane = cad_resolve_plane(v, r.ids, drill, &face_body); - } - if (g.type == T::Cut) g.cut_face = g.cut_face_body = -1; // a split along the plane, not along a face - if (drill && face_body >= 0) { - if (given("target_body") && g.target_body != face_body) - throw std::runtime_error("the plane is a face of body " + std::to_string(face_body) + ", so that body is drilled, not body " + - std::to_string(g.target_body)); - g.target_body = face_body; - } - } - if (given("rib_sketch_ref")) g.rib_sketch_ref = r.earlier("rib_sketch_ref", refs["rib_sketch_ref"], {T::Sketch}, "a Sketch"); - if (given("rib_entity")) g.rib_entity = r.integer("rib_entity", refs["rib_entity"], "a line of the rib's sketch (entity index)"); - if ((given("rib_sketch_ref") || given("rib_entity")) && - !(g.rib_sketch_ref >= 0 && g.rib_sketch_ref < int(doc.features.size()) && - revolve_line(doc.features[size_t(g.rib_sketch_ref)].entities, g.rib_entity))) - throw std::runtime_error("rib_entity " + std::to_string(g.rib_entity) + " is not a line of sketch " + std::to_string(g.rib_sketch_ref)); - if (given("mate_cs_a")) g.mate_cs_a = r.earlier("mate_cs_a", refs["mate_cs_a"], {T::CoordSys}, "a CoordSys"); - if (given("mate_cs_b")) g.mate_cs_b = r.earlier("mate_cs_b", refs["mate_cs_b"], {T::CoordSys}, "a CoordSys"); - if ((given("mate_cs_a") || given("mate_cs_b")) && g.mate_cs_a == g.mate_cs_b) - throw std::runtime_error("mate_cs_a and mate_cs_b must be two different coordinate systems"); - - if (given("edges") && given("face_group")) throw std::runtime_error("give edges or face_group, not both"); - if (given("edges")) { - const std::vector edges = r.id_list("edges", refs["edges"], true); - g.dressup_edge = edges.front(); - g.dressup_edges = edges.size() > 1 ? edges : std::vector(); - } - if (given("face_group")) { - const std::optional group = face_group_named(refs["face_group"]); - if (!group) throw std::runtime_error("face_group must be " + kFaceGroupWords); - g.face_group = *group; - g.dressup_edge = -1; - g.dressup_edges.clear(); - } - if (given("shell_face")) { - g.shell_face = r.integer("shell_face", refs["shell_face"], "a face id from body_describe, or -1 for a closed hollow"); - if (g.shell_face < -1) throw std::runtime_error("shell_face must be a face id from body_describe, or -1 for a closed hollow"); - } - if (given("draft_face")) g.draft_face = r.id_list("draft_face", refs["draft_face"], false).front(); - if (given("thicken_face")) g.thicken_face = r.id_list("thicken_face", refs["thicken_face"], false).front(); - if (given("delete_faces")) { - if (!refs["delete_faces"].is_array()) throw std::runtime_error("delete_faces must be a list of face ids from body_describe"); - g.delete_faces = r.id_list("delete_faces", refs["delete_faces"], true); - } - - // The faces and edges the feature works on, of its target body as it stood before the feature, whichever of the - // two changed. - const bool retarget = given("target_body"); - const int shown = g.target_body; - if ((g.type == T::Fillet || g.type == T::Chamfer) && (retarget || given("edges")) && !g.dressup_edge_ids().empty()) - r.on_body(g.dressup_edge_ids(), r.target(shown), true); - if (g.type == T::Shell && (retarget || given("shell_face")) && g.shell_face >= 0) r.on_body({g.shell_face}, r.target(shown), false); - if (g.type == T::Draft && (retarget || given("draft_face"))) r.on_body({g.draft_face}, r.target(shown), false); - if (g.type == T::Thicken && (retarget || given("thicken_face"))) r.on_body({g.thicken_face}, r.target(shown), false); - if (g.type == T::DeleteFace && (retarget || given("delete_faces"))) r.on_body(g.delete_faces, r.target(shown), false); -} - -} // namespace - -void cad_apply_feature_refs(CadFeature& f, const json& refs, const CadDocument& before, const CadDocument& doc, int index) -{ - using T = CadFeatureType; - const std::string type = feature_type_name(f.type); - if (f.type == T::Extrude) throw std::runtime_error("Extrude: its profile and its target are fixed"); - if (!refs.is_object() || refs.empty()) throw std::runtime_error("refs must name the references to change, as {\"sweep_path_ref\": 2}"); - const std::vector names = ref_names(f.type); - std::string list; - for (const std::string& n : names) list += (list.empty() ? "" : ", ") + n; - for (const auto& [name, v] : refs.items()) - if (std::find(names.begin(), names.end(), name) == names.end()) - throw std::runtime_error(names.empty() ? type + ": its card picks nothing again, so refs takes no name; '" + name + "' is not one" - : type + " takes " + list + " in refs, not '" + name + "'"); - const bool datum = f.type == T::Plane || f.type == T::Axis || f.type == T::CoordSys; - const RefReader r{datum ? doc : before, doc, index, datum, feature_label(doc, index)}; - CadFeature g = f; - if (datum) apply_datum_refs(g, refs, r); - else apply_model_refs(g, refs, r); - f = std::move(g); -} - -std::vector cad_commit_to_plate_replace(const json& replace, const Model& model) -{ - if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (object_list)"); - const int count = int(model.objects.size()); - std::vector out; - for (const json& v : replace) { - if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (object_list), not " + v.dump()); - const auto i = v.get(); - if (i < 0 || i >= count) - throw std::runtime_error("object " + std::to_string(i) + " is out of range; the project has " + std::to_string(count) + - " objects"); - if (std::find(out.begin(), out.end(), int(i)) != out.end()) - throw std::runtime_error("object " + std::to_string(i) + " is listed twice in replace"); - // Deleting one opens the "part of a cut object" warning, which the person answers. - if (model.objects[size_t(i)]->is_cut()) - throw CadPrecondition("object " + std::to_string(i) + - " is part of a cut object; delete it with object_select, then object_delete, which asks first"); - out.push_back(int(i)); - } - std::sort(out.begin(), out.end()); - return out; -} - -json cad_sketch_describe(const CadDocument& doc, const DesignSketchTool& tool, int sketch) -{ - sketch_arg(sketch, doc); - const CadFeature& f = doc.features[sketch]; - if (f.entities.empty()) - throw std::runtime_error("sketch " + std::to_string(sketch) + - " is not drawn from entities (a rectangle, circle, profile or imported art); feature_describe reads it"); - json ents = json::array(); - for (size_t i = 0; i < f.entities.size(); ++i) ents.push_back(sketch_entity_to(f.entities[i], int(i))); - json out{{"ok", true}, - {"sketch", sketch}, - {"name", f.name}, - {"plane", plane_json(f.plane, doc.modeling_origin)}, - {"entities", std::move(ents)}, - {"constraints", int(f.entity_constraints.size())}}; - out.update(sketch_report(tool.loop_report(f.entities))); - return out; -} - -json cad_sketch_call(DesignSketchTool& tool, const std::string& name, const json& params) -{ - const json p = params.is_object() ? params : json::object(); - if (name == "sketch_draw") return sketch_draw(tool, p); - if (name == "sketch_fillet") return sketch_corner(tool, p, false); - if (name == "sketch_chamfer") return sketch_corner(tool, p, true); - if (name == "sketch_trim") return sketch_trim_or_extend(tool, p, false); - if (name == "sketch_extend") return sketch_trim_or_extend(tool, p, true); - if (name == "sketch_offset") return sketch_offset(tool, p); - if (name == "sketch_mirror") return sketch_mirror(tool, p); - if (name == "sketch_transform") return sketch_transform(tool, p, false); - if (name == "sketch_pattern") return sketch_transform(tool, p, true); - if (name == "sketch_constrain") return sketch_constrain(tool, p, false); - if (name == "sketch_dimension") return sketch_constrain(tool, p, true); - if (name == "sketch_list_constraints") return sketch_list_constraints(tool, p); - if (name == "sketch_delete_constraint") return sketch_delete_constraint(tool, p); - if (name == "sketch_insert_svg") return sketch_insert_svg(tool, p); - throw std::runtime_error(name + " is not a Design command of the open sketch"); -} - -json cad_sketch_project(const CadDocument& doc, DesignSketchTool& tool, const json& params) -{ - if (!param(params, "plane").is_null()) throw std::runtime_error("plane is the open sketch's: leave it out"); - if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); - const json body = param(params, "source_body"); - if (!body.is_null() && !body.is_number_integer()) throw std::runtime_error("source_body must be a body index, or -1 for the last body"); - const int source = body.is_null() || body.get() == -1 ? int(doc.bodies.size()) - 1 : body.get(); - std::vector edges; - for (const json& v : param(params, "edges")) { - if (!v.is_number_integer()) throw std::runtime_error("edges must be edge ids (body_describe)"); - edges.push_back(v.get()); - } - const json face = param(params, "face"); - if (!face.is_null() && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe), or -1"); - // A body with no shape is the design's state; project_edges_on()'s other reasons are the call's edges, face and - // body index. - if (source >= 0 && source < int(doc.bodies.size()) && doc.bodies[size_t(source)].shape.IsNull()) - throw CadPrecondition("body " + std::to_string(source) + " has no shape"); - std::string error; - const std::vector ents = doc.project_edges_on(tool.plane(), source, edges, face.is_null() ? -1 : face.get(), error); - if (ents.empty()) throw std::runtime_error(error); - const int first = tool.add_entities_scripted(ents); - return json{{"ok", true}, {"scope", "sketch"}, {"first_index", first}, {"added", int(ents.size())}, - {"entities", int(tool.entities().size())}}; -} - -std::vector cad_constraint_defs(const json& params, const std::vector& ents, - const std::vector& selection) -{ - using T = SketchConstraintType; - const T type = constraint_type_arg(param(params, "type")); - const std::string name = params.at("type").get(); - const json refs = param(params, "refs"), picks = param(params, "entities"); - const bool by_refs = !refs.is_null() && !(refs.is_array() && refs.empty()); - const bool by_picks = !picks.is_null() && !(picks.is_array() && picks.empty()); - if (by_refs && by_picks) throw std::runtime_error("give entities or refs, not both"); - - // The value: mm, or degrees for an angle. A type that carries none refuses one. - const json value = param(params, "value"); - const bool valued = type == T::Distance || type == T::DistanceX || type == T::DistanceY || type == T::LockX || - type == T::LockY || type == T::Angle || type == T::Radius || type == T::Diameter || type == T::PointOnLine; - if (!value.is_null()) { - if (!value.is_number() || !std::isfinite(value.get())) throw std::runtime_error(name + " value must be a number"); - if (!valued) throw std::runtime_error(name + " takes no value"); - if ((type == T::Radius || type == T::Diameter) && !(value.get() > 0.0)) - throw std::runtime_error(name + " value must be > 0"); - if (type == T::Distance && value.get() < 0.0) throw std::runtime_error("distance value must be >= 0"); - } - - std::vector defs; - if (by_refs) { - defs.push_back(refs_constraint(type, name, refs, ents)); - if (value.is_null() && valued && type != T::PointOnLine) - throw std::runtime_error(name + " needs value (mm, or degrees for an angle)"); - write_plan_value(defs, value.is_null() ? 0.0 : value.get()); - return defs; - } - - // The CONSTRAIN bar's path: the planner takes the picks and chooses the points, as for a selection. - const std::vector picked = by_picks ? entity_indices(picks, ents) : selection; - const size_t takes = type == T::Fix || type == T::Horizontal || type == T::Vertical || type == T::Radius || type == T::Diameter - ? 1 : type == T::Symmetric ? 3 : 2; - if (by_picks && picked.size() > takes) - throw std::runtime_error(name + " takes " + std::to_string(takes) + (takes == 1 ? " entity" : " entities") + "; " + - std::to_string(picked.size()) + " were given"); - auto pick = [&](size_t k) { return k < picked.size() ? picked[k] : -1; }; - ConstraintPlan plan = plan_entity_constraint(ents, pick(0), pick(1), pick(2), type); - if (plan.kind == ConstraintPlan::Kind::Reject) { - std::string got; - for (int e : picked) got += (got.empty() ? "" : ", ") + entity_label(ents, e); - const auto& [code, text] = kConstraintRejects[int(plan.reason)]; - throw std::runtime_error(name + " " + text + (got.empty() ? "" : "; got " + got) + " (" + code + ")"); - } - // A value the button would ask for: the one given, else the current one, which the field shows. - if (plan.kind == ConstraintPlan::Kind::AskValue) write_plan_value(plan.defs, value.is_null() ? plan.prefill : value.get()); - return plan.defs; -} - -std::function cad_sketch_extrude(CadDocument& doc, const DesignSketchTool& tool, const json& params) -{ - refuse_with_sketch(params); - const int si = sketch_arg(params.value("sketch", json()), doc); - const double d = distance_arg(params); - const ExtrudeEnd end = extrude_end_arg(params); - const auto mode = operation_arg(params, "auto", kExtrudeOperations); - int body = std::max(-1, target_body_arg(params, doc)); - if (mode) check_has_body(*mode, doc); - const json loop = params.value("loop", json()); - std::vector subset; - if (!loop.is_null()) subset = loop_entities(tool, doc, si, loop); - // The card's defaults (open_tool): it works on the body the profile lies on or touches, and - // "auto" joins that body, or starts a new one when the profile touches none. - const int touching = doc.body_touching_sketch(si); - if (body < 0) body = touching; - const BooleanMode m = mode.value_or(touching >= 0 ? BooleanMode::Add : BooleanMode::New); - return [&doc, params, si, d, end, body, m, by_loop = !loop.is_null(), subset](const std::string& name) { - const SketchPlane plane = doc.features[si].plane; - const int e = by_loop ? doc.add_extrude_entities(subset, plane, d, false, m, name) : doc.add_extrude(si, d, false, m, name); - set_extrude_options(doc.features[e], params, end, d); - doc.features[e].target_body = body; - return e; - }; -} - -std::function cad_sketch_revolve(CadDocument& doc, const json& params) -{ - refuse_with_sketch(params); - const int si = sketch_arg(params.value("sketch", json()), doc); - const double angle = params.value("angle", 360.0); - const int axis = revolve_axis_arg(params); - const bool flip = params.value("flip", false); - const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); - const int body = std::max(-1, target_body_arg(params, doc)); - check_has_body(mode, doc); - const int axis_entity = revolve_axis_entity_arg(params, doc, si); - return [&doc, si, angle, axis, flip, mode, body, axis_entity](const std::string& name) { - const int r = doc.add_revolve(si, angle, axis, flip, mode, name); - doc.features[r].revolve_axis_entity = axis_entity; - doc.features[r].target_body = body; - return r; - }; -} - -std::function cad_surface_revolve(CadDocument& doc, const json& params) -{ - const int si = sketch_arg(params.value("sketch", json()), doc); - const double angle = params.value("angle", 360.0); - const int axis = revolve_axis_arg(params); - const bool flip = params.value("flip", false); - const int axis_entity = revolve_axis_entity_arg(params, doc, si); - return [&doc, si, angle, axis, flip, axis_entity](const std::string& name) { - const int r = doc.add_surface_revolve(si, angle, axis, name); - doc.features[r].flip = flip; - doc.features[r].revolve_axis_entity = axis_entity; - return r; - }; -} - -json cad_align_types(const CadDocument& doc, const json& params) -{ - for (const char* k : {"cs_a", "cs_b"}) - if (!params.value(k, json()).is_number_integer()) - throw std::runtime_error(std::string("list_align_types needs '") + k + "' (CoordSys feature index)"); - const int cs_a = params.at("cs_a").get(); - const int cs_b = params.at("cs_b").get(); - json types = json::array(); - for (const CadDocument::MateOption& o : doc.mate_options(cs_a, cs_b)) - types.push_back(json{{"type", enum_name(kAlignTypes, o.kind)}, {"fits", o.viable}, {"reason", o.viable ? json() : json(o.reason)}}); - return json{{"ok", true}, {"cs_a", cs_a}, {"cs_b", cs_b}, {"types", std::move(types)}}; -} - -SketchProfile cad_revolve_profile(const json& params) -{ - SketchProfile prof; - if (profile_from(params, prof)) return prof; - const double w = params.value("width", 20.0), h = params.value("height", 10.0); - if (w <= 0 || h <= 0) throw std::runtime_error("width and height must be > 0"); - // On one side of the axis, as make_revolve requires: a rectangle across it would sweep - // through itself. Both corner orders run counter-clockwise, as a drawn profile does. - const double a = w / 2; - prof.points = revolve_axis_arg(params) == 0 ? std::vector{{-a, 0}, {a, 0}, {a, h}, {-a, h}} - : std::vector{{0, -a}, {h, -a}, {h, a}, {0, a}}; - prof.closed = true; - return prof; -} - -std::function cad_face_extrude(CadDocument& doc, const json& params, SketchPlane& frame) -{ - for (const char* k : {"sketch", "loop", "profile", "width", "height", "plane"}) - if (params.contains(k) && !params.at(k).is_null() && !(params.at(k).is_array() && params.at(k).empty())) - throw std::runtime_error(std::string(k) + " cannot be given with face: the face is the profile and fixes its plane"); - const json fv = params.at("face"); - if (!fv.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); - if (doc.bodies.empty()) throw CadPrecondition("a face push/pull needs a body"); - const int asked = target_body_arg(params, doc); - const int b = asked >= 0 ? asked : int(doc.bodies.size()) - 1; - const int fi = fv.get(); - const TopoDS_Face face = GeometryEngine::face_by_index(doc.bodies[b].shape, fi); - if (face.IsNull()) - throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " does not exist (it has " + - std::to_string(GeometryEngine::face_count(doc.bodies[b].shape)) + " faces)"); - if (!doc.plane_of_face(b, fi, frame)) - throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " is " + face_kind_name(face) + - "; a push/pull needs a planar face"); - // The kernel grows a face blind or symmetric along its normal (apply_feature); the card's other - // ends and its taper act on sketch profiles only. - const ExtrudeEnd end = extrude_end_arg(params); - if (end != ExtrudeEnd::Blind && end != ExtrudeEnd::Symmetric) throw std::runtime_error("a face push/pull ends blind or symmetric"); - if (params.value("taper", 0.0) != 0.0) throw std::runtime_error("taper does not apply to a face push/pull"); - const double d = distance_arg(params); - const bool flip = params.value("flip", false); - // The card joins a picked face's own body by default. - const BooleanMode mode = operation_arg(params, "auto", kExtrudeOperations).value_or(BooleanMode::Add); - return [&doc, fi, d, mode, end, flip, b](const std::string& name) { - const int e = doc.add_extrude_face(fi, d, false, mode, name); - doc.features[e].extrude_end = end; - doc.features[e].flip = flip; - doc.features[e].target_body = b; // the face id is of this body - return e; - }; -} - -json cad_body_describe(const CadDocument& doc, const json& params) -{ - if (const json before = params.value("before", json()); !before.is_null()) { - if (!before.is_number_integer()) throw std::runtime_error("before must be a feature index (describe_design's features[].index)"); - json as_of = params; - as_of.erase("before"); - json out = cad_body_describe(cad_document_before(doc, before.get()), as_of); - out["before"] = before; - // The ids are the model's before that feature, read at the live document's generation, which a call passing - // them is checked against. - out["generation"] = doc.topo_generation; - return out; - } - const json vertices = params.value("vertices", json(false)); - if (!vertices.is_boolean()) throw std::runtime_error("vertices must be true or false"); - const TopoDS_Shape& shape = body_shape(doc, params); - - // Filters. Each narrows the list it applies to; direction applies to both. - auto kind_list = [&](const char* key, const auto& names) { - std::vector out; - const json v = params.value(key, json()); - if (v.is_null()) return out; - if (!v.is_array()) throw std::runtime_error(std::string(key) + " must be a list of kinds"); - // A face kind by its surface's noun, as agents often name it: plane for planar. - static const std::map nouns{ - {"plane", "planar"}, {"cylinder", "cylindrical"}, {"cone", "conical"}, {"sphere", "spherical"}, {"torus", "toroidal"}}; - for (const json& k : v) { - const auto noun = k.is_string() && std::string(key) == "kinds" ? nouns.find(k.get()) : nouns.end(); - out.push_back(enum_index(key, noun == nouns.end() ? k : json(noun->second), names)); - } - return out; - }; - const std::vector kinds = kind_list("kinds", kFaceKinds); - const std::vector edge_kinds = kind_list("edge_kinds", kEdgeKinds); - std::optional direction; - if (const json d = params.value("direction", json()); !d.is_null()) { - if (!d.is_array() || d.size() != 3 || !d[0].is_number() || !d[1].is_number() || !d[2].is_number()) - throw std::runtime_error("direction must be [x, y, z]"); - const Vec3d v(d[0].get(), d[1].get(), d[2].get()); - if (!(v.norm() > 1e-9)) throw std::runtime_error("direction must not be zero"); - direction = v.normalized(); - } - const json convex = params.value("convex", json()); - if (!convex.is_null() && !convex.is_boolean()) throw std::runtime_error("convex must be true or false"); - int extreme = -1; // index into kExtremes: axis = extreme / 2, the + side when it is even - static const char* const kExtremes[] = {"+x", "-x", "+y", "-y", "+z", "-z"}; - if (const json e = params.value("at_extreme", json()); !e.is_null()) extreme = enum_index("at_extreme", e, kExtremes); - const json adj = params.value("adjacency", json(false)); - if (!adj.is_boolean()) throw std::runtime_error("adjacency must be true or false"); - const bool adjacency = adj.get() || !convex.is_null(); - const json lim = params.value("limit", json()), off = params.value("offset", json()); - if (!lim.is_null() && !(lim.is_number_integer() && lim.get() >= 1)) throw std::runtime_error("limit must be an integer >= 1"); - if (!off.is_null() && !(off.is_number_integer() && off.get() >= 0)) throw std::runtime_error("offset must be an integer >= 0"); - const double kParallel = std::cos(M_PI / 180.0); // within 1 degree - - // Enumerate once. The _by_index accessors rescan the shape on every call (edge_by_index - // rebuilds the whole indexed map), so indexing a body face-by-face is quadratic: ~15 s on a - // 4.7k-face imported solid, on the UI thread. faces_of/edges_of keep the very same ids. - const std::vector faces = GeometryEngine::faces_of(shape); - const std::vector edges = GeometryEngine::edges_of(shape); - const int nf = int(faces.size()), ne = int(edges.size()); - std::vector> edge_faces, face_edges; - std::vector> convexity(ne); // only for an edge between two faces - if (adjacency) { - edge_faces = GeometryEngine::edge_faces(shape); - face_edges.resize(nf); - for (int e = 0; e < ne; ++e) { - for (int f : edge_faces[e]) face_edges[f].push_back(e); - if (edge_faces[e].size() == 2) - convexity[e] = GeometryEngine::edge_convexity(edges[e], faces[edge_faces[e][0]], faces[edge_faces[e][1]]); - } - } - std::vector> surfaces(nf); - auto surface = [&](int f) -> const GeometryEngine::SurfaceInfo& { - if (!surfaces[f]) surfaces[f] = GeometryEngine::surface_info(faces[f]); - return *surfaces[f]; - }; - double ext_at = 0, ext_tol = 0; - if (extreme >= 0) { - Bnd_Box box; - BRepBndLib::AddOptimal(shape, box, false, false); - double lo[3], hi[3]; - box.Get(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]); - ext_at = extreme % 2 == 0 ? hi[extreme / 2] : lo[extreme / 2]; - ext_tol = std::max(1e-3, 1e-6 * Vec3d(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]).norm()); - } - - auto face_matches = [&](int f) { - const GeometryEngine::SurfaceInfo& s = surface(f); - if (!kinds.empty() && std::find(kinds.begin(), kinds.end(), int(s.type)) == kinds.end()) return false; - // A normal is the face's own only on a plane; elsewhere it is one point's. - if (direction && (s.type != GeomAbs_Plane || GeometryEngine::face_normal_world(faces[f]).dot(*direction) < kParallel)) - return false; - return extreme < 0 || std::abs(s.centroid[extreme / 2] - ext_at) <= ext_tol; - }; - auto edge_matches = [&](int e) { - const BRepAdaptor_Curve c(edges[e]); - if (!edge_kinds.empty() && std::find(edge_kinds.begin(), edge_kinds.end(), edge_kind(c.GetType())) == edge_kinds.end()) - return false; - if (direction) { - if (c.GetType() != GeomAbs_Line) return false; - const gp_Dir t = c.Line().Direction(); - if (std::abs(Vec3d(t.X(), t.Y(), t.Z()).dot(*direction)) < kParallel) return false; - } - return convex.is_null() || (convexity[e] && *convexity[e] == (convex.get() ? 1 : -1)); - }; - - const bool face_filter = !kinds.empty() || direction || extreme >= 0; - const bool edge_filter = !edge_kinds.empty() || direction || !convex.is_null(); - std::vector face_ids, edge_ids; - for (int f = 0; f < nf; ++f) - if ((!face_filter && !edge_filter) || (face_filter && face_matches(f))) face_ids.push_back(f); - // A degenerate edge (a cone's apex) has no length and is not listed. - for (int e = 0; e < ne; ++e) - if (!BRep_Tool::Degenerated(edges[e]) && ((!face_filter && !edge_filter) || (edge_filter && edge_matches(e)))) - edge_ids.push_back(e); - // With adjacency, a list none of whose filters was given holds the neighbours of the other's matches. - auto neighbours = [](const std::vector& of, const std::vector>& links, size_t n) { - std::vector hit(n, false); - for (int i : of) - for (int j : links[i]) hit[j] = true; - std::vector out; - for (size_t j = 0; j < n; ++j) - if (hit[j]) out.push_back(int(j)); - return out; - }; - if (adjacency && edge_filter && !face_filter) face_ids = neighbours(edge_ids, edge_faces, nf); - if (adjacency && face_filter && !edge_filter) edge_ids = neighbours(face_ids, face_edges, ne); - - const size_t first = off.is_null() ? 0 : off.get(); - const size_t count = lim.is_null() ? std::max(face_ids.size(), edge_ids.size()) : lim.get(); - json jfaces = json::array(); - for (size_t k = first; k < face_ids.size() && k - first < count; ++k) { - const int f = face_ids[k]; - const GeometryEngine::SurfaceInfo& s = surface(f); - json jf{{"id", f}, {"kind", kFaceKinds[s.type]}, {"area", s.area}, {"centroid", vec3(s.centroid)}, - {"normal", vec3(GeometryEngine::face_normal_world(faces[f]))}}; - switch (s.type) { - case GeomAbs_Cylinder: - jf["radius"] = s.radius; jf["axis"] = vec3(s.axis); jf["internal"] = s.internal; - break; - case GeomAbs_Cone: - jf["apex"] = vec3(s.location); jf["axis"] = vec3(s.axis); jf["half_angle_deg"] = s.half_angle * 180.0 / M_PI; - jf["radius_min"] = s.radius; jf["radius_max"] = s.radius2; jf["internal"] = s.internal; - break; - case GeomAbs_Sphere: - jf["center"] = vec3(s.location); jf["radius"] = s.radius; jf["internal"] = s.internal; - break; - case GeomAbs_Torus: - jf["center"] = vec3(s.location); jf["axis"] = vec3(s.axis); - jf["major_radius"] = s.radius; jf["minor_radius"] = s.radius2; - break; - default: break; - } - if (adjacency) jf["edges"] = face_edges[f]; - jfaces.push_back(std::move(jf)); - } - json jedges = json::array(); - for (size_t k = first; k < edge_ids.size() && k - first < count; ++k) { - const int e = edge_ids[k]; - const std::vector pts = GeometryEngine::sample_edge_world(edges[e]); - if (pts.size() < 2) continue; - double len = 0; - for (size_t i = 1; i < pts.size(); ++i) len += (pts[i] - pts[i - 1]).norm(); - const BRepAdaptor_Curve c(edges[e]); - json je{{"id", e}, {"kind", kEdgeKinds[edge_kind(c.GetType())]}, {"length", len}, {"p0", vec3(pts.front())}, {"p1", vec3(pts.back())}}; - if (c.GetType() == GeomAbs_Circle) { - const GeometryEngine::CylinderFace circ = GeometryEngine::circle_of_edge(edges[e]); - je["radius"] = circ.radius; - je["center"] = vec3(circ.base); - } else if (c.GetType() == GeomAbs_Ellipse) { - const gp_Elips el = c.Ellipse(); - je["center"] = json::array({el.Location().X(), el.Location().Y(), el.Location().Z()}); - je["major_radius"] = el.MajorRadius(); - je["minor_radius"] = el.MinorRadius(); - } - if (adjacency) { - je["faces"] = edge_faces[e]; - if (convexity[e] && *convexity[e] != 0) je["convex"] = *convexity[e] > 0; - else if (convexity[e]) je["tangent"] = true; - } - jedges.push_back(std::move(je)); - } - json out{{"body", params.value("body", 0)}, {"face_count", nf}, {"edge_count", ne}, - {"faces_total", face_ids.size()}, {"edges_total", edge_ids.size()}, - {"faces", std::move(jfaces)}, {"edges", std::move(jedges)}, - // The ids above are indices into this exact topology and expire with it. Echo - // this back as "generation" on the calls that consume them. - {"generation", doc.topo_generation}}; - if (first + count < std::max(face_ids.size(), edge_ids.size())) out["next_offset"] = first + count; - if (vertices.get()) { - json jvertices = json::array(); - const std::vector points = cad_body_vertices(doc, params.value("body", 0)); - for (size_t v = 0; v < points.size(); ++v) jvertices.push_back(json{{"id", int(v)}, {"p", vec3(points[v])}}); - out["vertices"] = std::move(jvertices); - } - return out; -} - -namespace { - -// One measure ref: its shape, the point that stands for it (a face's centroid, an edge's middle -// sample, an axis's middle, the point itself) and, but for a point, a direction (a face's normal, -// an edge's chord, an axis). `planar` is set for a planar face. -TopoDS_Shape measure_ref(const CadDocument& doc, const json& params, const char* name, Vec3d& point, - std::optional& dir, bool& planar) -{ - const json& ref = params.at(name); - const std::string what = std::string("could not resolve ref \"") + name + "\": "; - planar = false; - dir.reset(); - if (!ref.is_object() || int(ref.contains("face")) + int(ref.contains("edge")) + int(ref.contains("point")) != 1) - throw std::runtime_error(what + "a ref is {\"face\": f}, {\"edge\": e} or {\"point\": [x, y, z]}, with an optional \"body\""); - if (ref.contains("point")) { - const json& p = ref.at("point"); - if (!p.is_array() || p.size() != 3 || !p[0].is_number() || !p[1].is_number() || !p[2].is_number()) - throw std::runtime_error(what + "point must be [x, y, z]"); - point = Vec3d(p[0].get(), p[1].get(), p[2].get()); - return BRepBuilderAPI_MakeVertex(gp_Pnt(point.x(), point.y(), point.z())).Vertex(); - } - const json bv = ref.contains("body") ? ref.at("body") : params.value("body", json(0)); - if (!bv.is_number_integer()) throw std::runtime_error(what + "body must be a body index"); - const int b = bv.get(); - if (b < 0 || b >= int(doc.bodies.size()) || doc.bodies[b].shape.IsNull()) - throw std::runtime_error(what + "body " + std::to_string(b) + " is out of range (have " + std::to_string(doc.bodies.size()) + ")"); - const TopoDS_Shape& shape = doc.bodies[b].shape; - const json axis = ref.value("axis", json(false)); - if (!axis.is_boolean()) throw std::runtime_error(what + "axis must be true or false"); - const std::string on_body = " of body " + std::to_string(b); - if (ref.contains("face")) { - if (!ref.at("face").is_number_integer()) throw std::runtime_error(what + "face must be a face id"); - const int fi = ref.at("face").get(); - const TopoDS_Face f = GeometryEngine::face_by_index(shape, fi); - if (f.IsNull()) - throw std::runtime_error(what + "face " + std::to_string(fi) + on_body + " does not exist (it has " + - std::to_string(GeometryEngine::face_count(shape)) + " faces)"); - if (axis.get()) { - // A cylinder's axis over the face's length: a hole's centre line, for distances to it. - const GeometryEngine::CylinderFace c = GeometryEngine::cylinder_of_face(f); - if (!c.ok) - throw std::runtime_error(what + "face " + std::to_string(fi) + on_body + " is " + face_kind_name(f) + - "; axis takes a cylindrical face"); - const Vec3d top = c.base + c.axis * c.height; - point = 0.5 * (c.base + top); - dir = c.axis; - return BRepBuilderAPI_MakeEdge(gp_Pnt(c.base.x(), c.base.y(), c.base.z()), gp_Pnt(top.x(), top.y(), top.z())).Edge(); - } - point = GeometryEngine::face_centroid_world(f); - dir = GeometryEngine::face_normal_world(f); - planar = BRepAdaptor_Surface(f).GetType() == GeomAbs_Plane; - return f; - } - if (axis.get()) throw std::runtime_error(what + "axis takes a cylindrical face"); - if (!ref.at("edge").is_number_integer()) throw std::runtime_error(what + "edge must be an edge id"); - const int ei = ref.at("edge").get(); - const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, ei); - if (e.IsNull()) - throw std::runtime_error(what + "edge " + std::to_string(ei) + on_body + " does not exist (it has " + - std::to_string(GeometryEngine::edge_count(shape)) + " edges)"); - const std::vector pts = GeometryEngine::sample_edge_world(e); - if (pts.size() < 2) throw std::runtime_error(what + "edge " + std::to_string(ei) + on_body + " has no length"); - point = pts[pts.size() / 2]; // the middle sample - dir = (pts.back() - pts.front()).normalized(); - return e; -} - -} // namespace - -json cad_measure(const CadDocument& doc, const json& params) -{ - if (!params.is_object() || !params.contains("a") || !params.contains("b")) - throw std::runtime_error("measure needs refs 'a' and 'b' ({face|edge|point})"); - Vec3d pa, pb; - std::optional da, db; - bool planar_a = false, planar_b = false; - const TopoDS_Shape sa = measure_ref(doc, params, "a", pa, da, planar_a); - const TopoDS_Shape sb = measure_ref(doc, params, "b", pb, db, planar_b); - json r{{"distance", (pa - pb).norm()}, {"point_a", vec3(pa)}, {"point_b", vec3(pb)}}; - if (da && db) { - const double c = std::max(-1.0, std::min(1.0, da->normalized().dot(db->normalized()))); - r["angle_deg"] = std::acos(c) * 180.0 / M_PI; - } - Vec3d ca, cb; - const double d = GeometryEngine::min_distance(sa, sb, ca, cb); - if (d < 0) throw CadKernelFailure("the minimum distance between the refs could not be computed"); - r["min_distance"] = d; - r["closest_a"] = vec3(ca); - r["closest_b"] = vec3(cb); - // The clearance between two parallel planar faces, as a lid fit wants it: across the gap, not - // along it. - if (planar_a && planar_b && da->cross(*db).norm() < 1e-6) r["parallel_gap"] = std::abs((pb - pa).dot(*da)); - return r; -} - -json cad_hole_placement(const CadDocument& doc, const json& params, SketchPlane& plane, int& target_body) -{ - if (doc.bodies.empty()) throw CadPrecondition("no body to drill"); - int face_body = -1; - plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true, &face_body); - const int body = target_body_arg(params, doc); - if (face_body >= 0 && body >= 0 && body != face_body) - throw std::runtime_error("the plane is a face of body " + std::to_string(face_body) + ", so that body is drilled, not body " + - std::to_string(body)); - // A face plane drills its own body, as the Hole card does for a picked face; otherwise the - // body asked for, or the kernel's default, the last body. - target_body = face_body >= 0 ? face_body : body; - json r{{"body", target_body >= 0 ? target_body : int(doc.bodies.size()) - 1}}; - const json at = params.value("at", json()); - if (at.is_null()) { - r["x"] = params.value("x", 0.0); - r["y"] = params.value("y", 0.0); - return r; - } - if (params.contains("x") || params.contains("y")) throw std::runtime_error("give at, or x and y, not both"); - static const std::string kAtForms = "at must be [x, y, z], {\"body\": b, \"face\": f} or {\"body\": b, \"edge\": e}"; - Vec3d p; - if (at.is_array()) { - if (at.size() != 3 || !at[0].is_number() || !at[1].is_number() || !at[2].is_number()) throw std::runtime_error(kAtForms); - p = Vec3d(at[0].get(), at[1].get(), at[2].get()); - } else if (at.is_object() && at.size() == 2 && at.contains("body") && at.at("body").is_number_integer() && - ((at.contains("face") && at.at("face").is_number_integer()) || (at.contains("edge") && at.at("edge").is_number_integer()))) { - // A round reference stands for its axis, so the hole shares it: the STEP-hole fix. - const int b = at.at("body").get(); - if (b < 0 || b >= int(doc.bodies.size())) - throw std::runtime_error("at: body " + std::to_string(b) + " is out of range (have " + std::to_string(doc.bodies.size()) + ")"); - const TopoDS_Shape& shape = doc.bodies[b].shape; - const bool is_face = at.contains("face"); - const int id = at.at(is_face ? "face" : "edge").get(); - const std::string what = std::string(is_face ? "face " : "edge ") + std::to_string(id) + " of body " + std::to_string(b); - GeometryEngine::CylinderFace round; - if (is_face) { - const TopoDS_Face f = GeometryEngine::face_by_index(shape, id); - if (f.IsNull()) throw std::runtime_error("at: " + what + " does not exist"); - round = GeometryEngine::cylinder_of_face(f); - if (!round.ok) throw std::runtime_error(what + " is " + face_kind_name(f) + "; \"at\" takes a cylindrical face or a circular edge"); - } else { - const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id); - if (e.IsNull()) throw std::runtime_error("at: " + what + " does not exist"); - round = GeometryEngine::circle_of_edge(e); - if (!round.ok) throw std::runtime_error(what + " is a " + edge_kind_name(e) + "; \"at\" takes a cylindrical face or a circular edge"); - } - if (std::abs(round.axis.dot(plane.normal)) < std::cos(M_PI / 180.0)) - throw std::runtime_error("the axis of " + what + " is not square to the plane, so a hole drilled from it cannot share that axis"); - p = round.base; - } else { - throw std::runtime_error(kAtForms); - } - // Projected onto the plane along its normal, in the plane's frame. - const Vec3d d = p - plane.origin; - r["x"] = d.dot(plane.x_axis); - r["y"] = d.dot(plane.y_axis); - r["off_plane"] = d.dot(plane.normal); - return r; -} - -std::function cad_datum_plane(CadDocument& doc, const json& params) -{ - using P = PlaneType; - CadFeature f; - f.type = CadFeatureType::Plane; - f.plane_type = P(enum_index("type", params.value("type", json("offset")), kPlaneTypes)); - const P t = f.plane_type; - auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; - const bool on_face = given("face_a"); - - // What each construction reads in resolve_datum_planes(); a param it would ignore is refused. - auto uses = [&](const std::string& k) { - if (k == "face_a") return t != P::TwoEdges; - if (k == "face_b") return t == P::Midplane; - if (k == "edge_a") return t == P::Angle || t == P::TwoEdges; - if (k == "edge_b") return t == P::TwoEdges; - if (k == "base") return (t == P::Offset || t == P::Coincident || t == P::Angle) && !on_face; - if (k == "offset") return t == P::Offset; - if (k == "angle") return (t == P::Offset && !on_face) || t == P::Angle || t == P::Tangent; - return t == P::Offset && !on_face; // axis - }; - for (const char* k : {"face_a", "face_b", "edge_a", "edge_b", "base", "offset", "angle", "axis"}) - if (given(k) && !uses(k)) - throw std::runtime_error(std::string(k) + " is not used by a " + kPlaneTypes[int(t)] + " plane" + - (on_face && std::string(k) != "face_a" ? " on face_a" : "")); - - // {"body": b, "face": f} or {"body": b, "edge": e}, on the current topology. - auto ref = [&](const char* key, const char* kind, int& body, int& id) { - if (!given(key)) return; - const json& v = params.at(key); - if (!v.is_object() || v.size() != 2 || !v.contains("body") || !v.contains(kind) || !v.at("body").is_number_integer() || - !v.at(kind).is_number_integer()) - throw std::runtime_error(std::string(key) + " must be {\"body\": b, \"" + kind + "\": id}"); - body = v.at("body").get(); - id = v.at(kind).get(); - if (body < 0 || body >= int(doc.bodies.size())) - throw std::runtime_error(std::string(key) + ": body " + std::to_string(body) + " is out of range (have " + - std::to_string(doc.bodies.size()) + ")"); - const TopoDS_Shape& s = doc.bodies[body].shape; - const bool face = std::string(kind) == "face"; - if (face ? GeometryEngine::face_by_index(s, id).IsNull() : GeometryEngine::edge_by_index(s, id).IsNull()) - throw std::runtime_error(std::string(key) + ": " + kind + " " + std::to_string(id) + " of body " + std::to_string(body) + - " does not exist (it has " + - std::to_string(face ? GeometryEngine::face_count(s) : GeometryEngine::edge_count(s)) + " " + kind + "s)"); - }; - ref("face_a", "face", f.plane_face_body, f.plane_face); - ref("face_b", "face", f.plane_face2_body, f.plane_face2); - ref("edge_a", "edge", f.plane_edge_body, f.plane_edge); - ref("edge_b", "edge", f.plane_edge2_body, f.plane_edge2); - - // The card's base list: the three base planes, then the shown datum planes in order. - const json base = params.value("base", json("XY")); - if (base.is_object() && !base.contains("datum")) - throw std::runtime_error("base must be \"XY\", \"XZ\", \"YZ\" or {\"datum\": i}; a face goes in face_a"); - cad_resolve_plane(base, doc, false); // refuses what is not a base plane or a shown datum - f.plane_base = base.is_string() ? (base == "XZ" ? 1 : base == "YZ" ? 2 : 0) : 3 + datum_ordinal(doc, base.at("datum").get()); - - // The card's spin controls: their defaults and limits. - auto number = [&](const char* key, double def, double lo, double hi) { - if (!given(key)) return def; - const json& v = params.at(key); - if (!v.is_number() || !(v.get() >= lo && v.get() <= hi)) - throw std::runtime_error(Slic3r::format("%1% must be a number from %2% to %3%", key, lo, hi)); - return v.get(); - }; - f.plane_offset = number("offset", 20.0, -100000, 100000); - f.plane_angle_tilt = number("angle", 0.0, -180, 180); - if (given("axis")) { - if (!params.at("axis").is_number_integer() || (params.at("axis") != 0 && params.at("axis") != 1)) - throw std::runtime_error("axis must be 0 (the base plane's X) or 1 (its Y)"); - f.plane_axis = params.at("axis").get(); - } - if (given("size")) { - const json& sz = params.at("size"); - if (!sz.is_array() || sz.size() != 2 || !sz[0].is_number() || !sz[1].is_number() || - !(sz[0].get() >= 1 && sz[0].get() <= 100000 && sz[1].get() >= 1 && sz[1].get() <= 100000)) - throw std::runtime_error("size must be [u, v], each from 1 to 100000 mm"); - f.plane_u_size = sz[0].get(); - f.plane_v_size = sz[1].get(); - } - if (const std::string why = doc.datum_plane_refusal(f); !why.empty()) throw std::runtime_error(why); - return [&doc, f](const std::string& name) { - const int i = doc.add_plane(f.plane_base, f.plane_offset, f.plane_angle_tilt, f.plane_axis, name); - CadFeature& p = doc.features[i]; - // The references and size the card's apply_plane_refs() copies. - p.plane_type = f.plane_type; - p.plane_face_body = f.plane_face_body; p.plane_face = f.plane_face; - p.plane_face2_body = f.plane_face2_body; p.plane_face2 = f.plane_face2; - p.plane_edge_body = f.plane_edge_body; p.plane_edge = f.plane_edge; - p.plane_edge2_body = f.plane_edge2_body; p.plane_edge2 = f.plane_edge2; - p.plane_u_size = f.plane_u_size; - p.plane_v_size = f.plane_v_size; - return i; - }; -} - -std::function cad_thread(CadDocument& doc, const json& params, json& resolved) -{ - auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; - auto flag = [&](const char* k) { - if (!params.at(k).is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); - return params.at(k).get(); - }; - // A size in mm that replaces the standard's; absent keeps it. - auto size = [&](const char* k) -> std::optional { - if (!given(k)) return std::nullopt; - if (!params.at(k).is_number() || !(params.at(k).get() > 0)) - throw std::runtime_error(std::string(k) + " must be a number > 0 (mm)"); - return params.at(k).get(); - }; - const bool on_face = given("face"), on_edge = given("edge"); - if (on_face && on_edge) throw std::runtime_error("give face or edge, not both"); - - SketchPlane plane; - GeometryEngine::CylinderFace cyl; - bool internal = false; - int target = -1; // the kernel's last body - if (on_face || on_edge) { - // A picked bore, boss or rim: the thread runs along its axis from its base, as the card's - // pick sets it, on that body. - const std::string kind = on_face ? "face" : "edge"; - for (const char* k : {"plane", "x", "y", "at"}) - if (given(k)) throw std::runtime_error(std::string(k) + " cannot be given with " + kind + ": the thread runs on its axis"); - if (doc.bodies.empty()) throw CadPrecondition("no body to thread"); - if (!params.at(kind).is_number_integer()) throw std::runtime_error(kind + " must be an id from body_describe"); - target = target_body_arg(params, doc); - if (target < 0) target = int(doc.bodies.size()) - 1; - const int id = params.at(kind).get(); - const TopoDS_Shape& shape = doc.bodies[target].shape; - const std::string what = kind + " " + std::to_string(id) + " of body " + std::to_string(target); - if (!doc.thread_target(target, on_face ? id : -1, on_face ? -1 : id, plane, cyl)) { - if (on_face) { - const TopoDS_Face f = GeometryEngine::face_by_index(shape, id); - if (f.IsNull()) - throw std::runtime_error(what + " does not exist (it has " + std::to_string(GeometryEngine::face_count(shape)) + " faces)"); - throw std::runtime_error(what + " is " + face_kind_name(f) + "; a thread needs a cylindrical face or a circular edge"); - } - const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id); - if (e.IsNull()) - throw std::runtime_error(what + " does not exist (it has " + std::to_string(GeometryEngine::edge_count(shape)) + " edges)"); - throw std::runtime_error(what + " is a " + edge_kind_name(e) + "; a thread needs a cylindrical face or a circular edge"); - } - // A bore taps, a boss is threaded; a rim cannot tell, so it is external unless told. - internal = given("internal") ? flag("internal") : cyl.internal; - resolved = {{"x", 0.0}, {"y", 0.0}}; - } else { - if (!given("internal")) - throw std::runtime_error("internal is required for a thread on a plane: true taps a hole in a body, false threads a rod"); - internal = flag("internal"); - if (!doc.bodies.empty()) { - resolved = cad_hole_placement(doc, params, plane, target); // placed as a hole is - } else { - // A rod threaded from nothing: there is no body to place against. - if (internal) throw CadPrecondition("an internal thread needs a body to tap; add or import one first"); - if (given("at")) throw std::runtime_error("at places a thread against a body, and there is none; give x and y"); - plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true); - resolved = {{"x", params.value("x", 0.0)}, {"y", params.value("y", 0.0)}}; - } - } - - // The standard named, else the one nearest the picked cylinder, as the card infers it. - const ThreadSpec* spec = nullptr; - if (given("designation")) { - const json& d = params.at("designation"); - if (!d.is_string()) throw std::runtime_error("designation must be a string such as \"M5\" or \"1/4-20 UNC\""); - spec = find_thread_standard(d.get()); - if (spec == nullptr) { - // The same name in another case, else the names that start the other or are one edit away. - const std::string want = boost::algorithm::to_lower_copy(d.get()); - std::string close; - for (const ThreadSpec& t : thread_standards()) - if (boost::algorithm::to_lower_copy(std::string(t.name)) == want) close = t.name; - if (close.empty() && !want.empty()) - for (const ThreadSpec& t : thread_standards()) { - const std::string n = boost::algorithm::to_lower_copy(std::string(t.name)); - if (n.rfind(want, 0) == 0 || want.rfind(n, 0) == 0 || edit_distance(n, want) <= 1) - close += (close.empty() ? "" : ", ") + t.name; - } - throw std::runtime_error("unknown designation \"" + d.get() + "\"" + - (close.empty() ? std::string("; ISO metric (M5, M8x1) and UTS (1/4-20 UNC) sizes are known") : "; close: " + close)); - } - } else if (cyl.ok) { - spec = nearest_thread_standard(2.0 * cyl.radius, internal); - } - const std::optional diameter = size("diameter"), pitch = size("pitch"), depth = size("depth"), length = size("length"); - if (spec == nullptr && (!diameter || !pitch)) - throw std::runtime_error("a thread on a plane needs designation, or diameter and pitch for a custom thread"); - ThreadSpec s = spec != nullptr ? *spec : ThreadSpec{"", *diameter, *pitch, ThreadSpec::Series::MetricCoarse}; - if (diameter) s.major_diameter_mm = *diameter; - if (pitch) s.pitch_mm = *pitch; - // The 60 degree V of the standards: a tapped thread runs from the minor diameter out to the - // major, a rod's in from the crests, as the card sets the depth for the role. - const double d = depth ? *depth : internal ? s.internal_depth_mm() : s.thread_depth_mm(); - double len = 0; - if (length) - len = *length; - else if (on_face && cyl.height > 1e-6) - len = cyl.height; // the card's default: the whole face - else - throw std::runtime_error(on_face ? "length is required: the face has no length" - : on_edge ? "length is required for a thread on an edge" - : "length is required for a thread on a plane"); - - const bool custom = spec == nullptr || s.major_diameter_mm != spec->major_diameter_mm || s.pitch_mm != spec->pitch_mm; - resolved["designation"] = custom ? json() : json(spec->name); - resolved["internal"] = internal; - resolved["diameter"] = s.major_diameter_mm; - resolved["pitch"] = s.pitch_mm; - resolved["depth"] = d; - resolved["length"] = len; - resolved["frame"] = frame_json(plane); - const double x = resolved.at("x").get(), y = resolved.at("y").get(); - return [&doc, s, len, d, internal, x, y, plane, target](const std::string& name) { - const int t = doc.add_thread(0.5 * s.major_diameter_mm, s.pitch_mm, len, d, internal, x, y, plane, name); - doc.features[t].target_body = target; - return t; - }; -} - -std::function cad_sweep(CadDocument& doc, const json& params) -{ - const int si = sketch_arg(params.value("sketch", json()), doc); - const json pv = params.value("path", json()); - if (!pv.is_number_integer()) throw std::runtime_error("path must be the feature index of a sketch or a helix (describe_design)"); - const int pi = pv.get(); - check_feature_index(pi, doc); - const CadFeatureType pt = doc.features[pi].type; - if (pt != CadFeatureType::Sketch && pt != CadFeatureType::Helix) - throw std::runtime_error("path " + std::to_string(pi) + " (" + feature_type_name(pt) + ") is not a sketch or a helix"); - if (pi == si) throw std::runtime_error("the path cannot be the profile sketch itself"); - const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); - const int body = std::max(-1, target_body_arg(params, doc)); - check_has_body(mode, doc); - return [&doc, si, pi, mode, body](const std::string& name) { - const int i = doc.add_sweep(si, pi, mode, name); - doc.features[i].target_body = body; - return i; - }; -} - -std::function cad_loft(CadDocument& doc, const json& params) -{ - const json pv = params.value("profiles", json()); - if (!pv.is_array()) throw std::runtime_error("profiles must be a list of sketch feature indices, in loft order"); - if (pv.size() < 2) throw std::runtime_error("loft needs 2 or more sketches in profiles"); - std::vector refs; - for (const json& v : pv) { - if (!v.is_number_integer()) throw std::runtime_error("profiles must hold sketch feature indices (describe_design)"); - const int si = sketch_arg(v, doc); - if (std::find(refs.begin(), refs.end(), si) != refs.end()) - throw std::runtime_error("sketch " + std::to_string(si) + " is listed twice in profiles"); - refs.push_back(si); - } - const json ruled = params.value("ruled", json(false)); - if (!ruled.is_boolean()) throw std::runtime_error("ruled must be true or false"); - const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); - const int body = std::max(-1, target_body_arg(params, doc)); - check_has_body(mode, doc); - return [&doc, refs, ruled = ruled.get(), mode, body](const std::string& name) { - const int i = doc.add_loft(refs, ruled, mode, name); - doc.features[i].target_body = body; - return i; - }; -} - -std::function cad_hole(CadDocument& doc, const json& params, json& resolved) -{ - const int style = enum_index("type", params.value("type", json("simple")), kHoleTypes); - // A seat's sizes are its type's: beside another type they would size nothing, so they are refused. A null is the - // argument left out. - static const std::pair kSeatOf[] = {{"cbore_diameter", 1}, {"cbore_depth", 1}, {"csink_diameter", 2}, {"csink_angle", 2}}; - for (const auto& [key, seat] : kSeatOf) - if (seat != style && params.contains(key) && !params.at(key).is_null()) - throw std::runtime_error(std::string(key) + " goes with type " + kHoleTypes[seat] + ", not " + kHoleTypes[style]); - const json named = params.value("designation", json()); - const bool standard = !named.is_null(); - if (standard) { - if (params.contains("diameter")) throw std::runtime_error("give diameter or designation, not both"); - // The standard sizes the seat too (CadDocument::add_hole_standard), so these would be replaced. - for (const char* k : {"cbore_diameter", "cbore_depth", "csink_diameter", "csink_angle", "standard"}) - if (params.contains(k)) - throw std::runtime_error(std::string(k) + " cannot be given with designation: the standard sizes the hole and its seat"); - if (!named.is_string() || named.get().empty()) - throw std::runtime_error("designation must be a standard size such as \"M6\" or \"1/4-20\""); - } - const double diameter = params.value("diameter", 5.0); - if (diameter <= 0) throw std::runtime_error("diameter must be > 0"); - const double depth = params.value("depth", 10.0); - const bool through = params.value("through", false); - const double cbore_diameter = params.value("cbore_diameter", 0.0); - const double cbore_depth = params.value("cbore_depth", 0.0); - const double csink_diameter = params.value("csink_diameter", 0.0); - const double csink_angle = params.value("csink_angle", 90.0); - const std::string provenance = params.value("standard", std::string()); - const std::string designation = standard ? named.get() : std::string(); - SketchPlane plane; - int body = -1; - resolved = cad_hole_placement(doc, params, plane, body); - resolved["frame"] = frame_json(plane); - const double x = resolved.at("x").get(), y = resolved.at("y").get(); - // add_hole_standard throws on a designation it does not know, which the caller's add_feature rolls back. - return [&doc, style, standard, designation, diameter, depth, through, cbore_diameter, cbore_depth, csink_diameter, - csink_angle, provenance, x, y, plane, body](const std::string& name) { - const int h = standard ? doc.add_hole_standard(designation, style, through, depth, x, y, plane, name) - : doc.add_hole_styled(diameter, depth, through, x, y, plane, style, cbore_diameter, cbore_depth, - csink_diameter, csink_angle, provenance, name); - doc.features[h].target_body = body; - return h; - }; -} - -std::function cad_thicken(CadDocument& doc, const json& params) -{ - const json type = params.value("type", json()); - if (!type.is_null() && type != "face" && type != "surface") throw std::runtime_error("type must be face or surface"); - const bool surface = thickens_surface(params); - const json face = params.value("face", json()); - if (surface && !face.is_null()) - throw std::runtime_error("type surface thickens a whole sheet body and takes no face; type face thickens a face"); - if (!surface && face.is_null()) throw std::runtime_error("type face needs face, a face id (body_describe)"); - if (!surface && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); - if (doc.bodies.empty()) throw CadPrecondition(surface ? "no sheet body to thicken" : "no body to thicken"); - const int body = target_body_arg(params, doc); - const double thickness = params.value("thickness", 2.0); - const bool flip = params.value("flip", false); - if (surface) - return [&doc, body, thickness, flip](const std::string& name) { return doc.add_thicken_surface(body, thickness, flip, name); }; - return [&doc, body, fi = face.get(), thickness, flip](const std::string& name) { - return doc.add_thicken(body, fi, thickness, flip, name); - }; -} - -std::function cad_pattern(CadDocument& doc, const json& params) -{ - const int layout = enum_index("type", params.value("type", json("linear")), kPatternTypes); - const bool curve = layout == 2; - // What each layout reads beside count and body, by layout (linear, circular, curve): beside another it would place - // nothing, so it is refused. A null is the argument left out. - struct Takes - { - const char* key; - const char* types; - bool by[3]; - }; - static const Takes kTakes[] = {{"spacing", "linear", {true, false, false}}, {"dir", "linear", {true, false, false}}, - {"angle", "circular", {false, true, false}}, {"plane", "linear or circular", {true, true, false}}, - {"sketch", "curve", {false, false, true}}, {"entity", "curve", {false, false, true}}}; - for (const Takes& t : kTakes) - if (!t.by[layout] && params.contains(t.key) && !params.at(t.key).is_null()) - throw std::runtime_error(std::string(t.key) + " goes with type " + t.types + ", not " + kPatternTypes[layout]); - // The curve the copies follow, which a curve pattern needs. - if (curve) - for (const char* k : {"sketch", "entity"}) - if (!params.value(k, json()).is_number_integer()) - throw std::runtime_error(std::string("a curve pattern needs ") + k + - (std::string(k) == "sketch" ? ", the feature index of the sketch holding the guide curve" - : ", the guide curve's entity index within that sketch")); - const int count = params.value("count", 3); - if (count < 1) throw std::runtime_error("count must be >= 1"); - if (doc.bodies.empty()) throw CadPrecondition("no body to pattern"); - const int body = target_body_arg(params, doc); - if (curve) - return [&doc, count, sketch = params.at("sketch").get(), entity = params.at("entity").get(), body](const std::string& name) { - return doc.add_pattern_on_curve(count, sketch, entity, body, name); - }; - const double spacing = params.value("spacing", 10.0); // linear step (mm) - const int dir = params.value("dir", 0); // 0 = plane X, 1 = plane Y - const double angle = params.value("angle", 360.0); // circular total sweep (deg) - const SketchPlane plane = cad_resolve_plane(params.value("plane", json("XY")), doc, false); - return [&doc, circular = layout == 1, count, spacing, dir, angle, body, plane](const std::string& name) { - const int p = doc.add_pattern(circular, count, spacing, dir, angle, body, name); - doc.features[p].plane = plane; // the circular pattern's axis, the linear one's step directions - return p; - }; -} - -std::function cad_align(CadDocument& doc, const json& params) -{ - for (const char* k : {"cs_a", "cs_b"}) - if (!params.value(k, json()).is_number_integer()) - throw std::runtime_error(std::string("align needs '") + k + "' (CoordSys feature index)"); - const int kind = enum_index("type", params.value("type", json("fastened")), kAlignTypes); - const int cs_a = params.at("cs_a").get(); - const int cs_b = params.at("cs_b").get(); - const double offset = params.value("offset", 0.0); - const double angle = params.value("angle", 0.0); - const bool flip = params.value("flip", false); - return [&doc, kind, cs_a, cs_b, offset, angle, flip](const std::string& name) { - return doc.add_mate(kind, cs_a, cs_b, offset, angle, flip, name); - }; -} - -std::function cad_dressup(CadDocument& doc, const json& params, bool chamfer) -{ - const char* verb = chamfer ? "chamfer" : "fillet"; - const json given = params.value("edges", json()); - // A word names the card's Edges choice, an edge group; anything else is ids. - const std::optional group = face_group_named(given); - if (given.is_string() && !group) throw std::runtime_error("edges must be an edge id, a list of them, or " + kFaceGroupWords); - const std::vector edges = group ? std::vector() : edge_ids_arg(params, verb); - const char* key = chamfer ? "distance" : "radius"; - const double size = params.value(key, 1.0); - if (size <= 0) throw std::runtime_error(std::string(key) + " must be > 0"); - if (doc.bodies.empty()) throw CadPrecondition(std::string("no body to ") + verb); - const int body = target_body_arg(params, doc); - return [&doc, chamfer, group, edges, size, body](const std::string& name) { - const int i = group ? (chamfer ? doc.add_chamfer(size, *group, name) : doc.add_fillet(size, *group, name)) - : (chamfer ? doc.add_chamfer(size, edges, name) : doc.add_fillet(size, edges, name)); - if (body >= 0) doc.features[i].target_body = body; // the edge ids are resolved against this body's shape - return i; - }; -} - -std::function cad_split(CadDocument& doc, const json& params, json& resolved) -{ - auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; - auto flag = [&](const char* k, bool def) { - if (!given(k)) return def; - if (!params.at(k).is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); - return params.at(k).get(); - }; - const bool by_plane = given("plane"), by_face = given("face"); - if (by_plane && by_face) throw std::runtime_error("give plane or face, not both"); - if (!by_plane && !by_face) - throw std::runtime_error("split needs plane (\"XY\", \"XZ\", \"YZ\", {\"datum\": i} or {\"body\": b, \"face\": f}) or face (a face id to split along)"); - if (doc.bodies.empty()) throw CadPrecondition("no body to split"); - const int body = target_body_arg(params, doc); - const int t = body >= 0 ? body : int(doc.bodies.size()) - 1; - const bool keep_upper = flag("keep_upper", true), keep_lower = flag("keep_lower", true); - if (!keep_upper && !keep_lower) throw std::runtime_error("keep_upper and keep_lower are both false, so nothing would be kept"); - // The kernel keeps the upper piece in the body's place and puts the lower one after it. - resolved = {{"body", t}}; - if (keep_upper) resolved["upper_body"] = t; - if (keep_lower) resolved["lower_body"] = keep_upper ? t + 1 : t; - - if (by_face) { - for (const char* k : {"offset", "flip"}) - if (given(k)) - throw std::runtime_error(std::string(k) + " goes with plane; to split along a face at an offset, give plane {\"body\": b, \"face\": f}"); - if (!params.at("face").is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); - const int face = params.at("face").get(); - const json fbv = params.value("face_body", json(-1)); - if (!fbv.is_number_integer() || fbv.get() < -1 || fbv.get() >= int(doc.bodies.size())) - throw std::runtime_error("face_body must be a body index, or -1 for the body being split"); - const int face_body = fbv.get(); - const int fb = face_body >= 0 ? face_body : t; - if (GeometryEngine::face_by_index(doc.bodies[fb].shape, face).IsNull()) - throw std::runtime_error("face " + std::to_string(face) + " of body " + std::to_string(fb) + " does not exist (it has " + - std::to_string(GeometryEngine::face_count(doc.bodies[fb].shape)) + " faces)"); - return [&doc, body, face_body, face, keep_upper, keep_lower](const std::string& name) { - return doc.add_split_by_face(body, face_body, face, keep_upper, keep_lower, name); - }; - } - if (given("face_body")) throw std::runtime_error("face_body goes with face"); - const SketchPlane plane = cad_resolve_plane(params.at("plane"), doc, false); - const json ov = params.value("offset", json(0.0)); - if (!ov.is_number()) throw std::runtime_error("offset must be a number (mm along the plane's normal)"); - const double offset = ov.get(); - const bool flip = flag("flip", false); - // The plane the kernel cuts along (apply_cut): moved along its normal, then turned over. - SketchPlane cut = plane; - cut.origin += cut.normal * offset; - if (flip) cut.normal = -cut.normal; - // A plane clear of the body would leave one piece empty; the card does not check this. - Bnd_Box box; - BRepBndLib::AddOptimal(doc.bodies[t].shape, box, false, false); - if (!box.IsVoid()) { - double x0, y0, z0, x1, y1, z1; - box.Get(x0, y0, z0, x1, y1, z1); - double lo = 1e300, hi = -1e300; - for (double x : {x0, x1}) - for (double y : {y0, y1}) - for (double z : {z0, z1}) { - const double side = (Vec3d(x, y, z) - cut.origin).dot(cut.normal); - lo = std::min(lo, side); - hi = std::max(hi, side); - } - if (lo >= -1e-6 || hi <= 1e-6) - throw std::runtime_error("the plane misses body " + std::to_string(t) + ": all of it lies on its " + - (lo >= -1e-6 ? "upper" : "lower") + " side, so there is nothing to split"); - } - resolved["frame"] = frame_json(cut); - return [&doc, plane, offset, flip, keep_upper, keep_lower, body](const std::string& name) { - return doc.add_cut(plane, offset, flip, keep_upper, keep_lower, body, name); - }; -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.hpp b/src/slic3r/GUI/Mcp/McpToolsDesign.hpp similarity index 91% rename from src/slic3r/GUI/Mcp/McpToolsCad.hpp rename to src/slic3r/GUI/Mcp/McpToolsDesign.hpp index 9c66ec97cd..4bddae2a9c 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.hpp +++ b/src/slic3r/GUI/Mcp/McpToolsDesign.hpp @@ -7,11 +7,15 @@ // is in. A call with exactly the arguments that choose one of the command's items (opened_item()) does what that // right-click menu item does, in the mode the item belongs to (open_refusal()); any other call, or one with // silent: true, runs the entry's tool block's silent form. They run on the UI thread through the GUI's own -// CadDocument (no engine of their own), behind one gate (cad_gate()): every command is refused (design_busy) during a -// rebuild, whose worker owns the document, and a silent form that changes the document also while the Design tab -// is busy with it, an open feature card or a sketch session; face and edge ids read at another generation are -// refused (stale_ids). The catalog holds the commands only while the CAD feature is on -// (NativeCommands::register_all_commands()). The unit tests call the cad_* helpers directly. +// CadDocument (no engine of their own), behind one gate (design_gate(), DesignTools.cpp): every command is refused +// (design_busy) during a rebuild, whose worker owns the document, and a silent form that changes the document also +// while the Design tab is busy with it, an open feature card or a sketch session; face and edge ids read at another +// generation are refused (stale_ids). The catalog holds the commands only while the CAD feature is on +// (NativeCommands::register_all_commands()). +// +// The design_* names here are the place's command machinery: its registration, schema, runs, menu items and undo. +// The cad_* names are the parts of the commands' work that the unit tests call directly, on the model, its sketches +// and features, and the plate; cad_note() is app_state's report of the CAD feature, named for its JSON key. // // A failed call's error names its cause in `code`, a word as the other commands' refusals have: // - design_unavailable: no Design tab to act on (the G-code viewer, the CAD feature off, a panel or a view that is not @@ -30,16 +34,14 @@ // - kernel_failure: a CAD kernel (OCCT) error reached the command's guard, wherever it was raised, its message after // "OCCT: "; // - export_failed: export_step could not transfer or write the STEP file; -// - no_silent_form: an entry with no silent form called as one (run_cad_tool() called directly). +// - no_silent_form: an entry with no silent form called as one (run_design_tool() called directly). #include "libslic3r/Point.hpp" -#include "slic3r/GUI/CAD/DesignOffer.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include -#include #include #include #include @@ -62,6 +64,7 @@ namespace GUI { class DesignPanel; class DesignSketchTool; +struct DesignTool; namespace Mcp { @@ -91,13 +94,14 @@ struct CadKernelFailure : std::runtime_error // plain exceptions. nlohmann::json run_guarded(const std::function& run); -// Why there is no Design panel to act on, as cad_gate() refuses it, each design_unavailable: the G-code viewer, which -// has no Design tab; the CAD feature off; else a panel that cannot be built (no page made at startup because the -// feature was turned on later, a page mid-build, or a build that failed), which a retry or a restart mends. UI thread. +// Why there is no Design panel to act on, as design_gate() refuses it, each design_unavailable: the G-code viewer, +// which has no Design tab; the CAD feature off; else a panel that cannot be built (no page made at startup because +// the feature was turned on later, a page mid-build, or a build that failed), which a retry or a restart mends. UI +// thread. ToolFailure no_design_tab(); // The refusal of a call that finds no Design view to act on (the panel's viewport, Feature list or parts list not -// built), which no change to the call mends: design_unavailable, as cad_gate() refuses a panel that cannot be built. +// built), which no change to the call mends: design_unavailable, as design_gate() refuses a panel that cannot be built. ToolFailure no_design_view(); // The refusal of a call the Design tab is too busy to take, `why` saying with what (DesignPanel::mcp_busy()): @@ -108,14 +112,16 @@ ToolFailure design_busy(const std::string& why); // integer type takes (is_whole_number(): a JSON integer stored signed or unsigned, since a script's or plugin's Python // integers reach the command as signed ones, or a whole float within int64) that is not negative. Anything else // throws ToolFailure (invalid_argument). -std::optional cad_generation(const nlohmann::json& args); +std::optional design_generation(const nlohmann::json& args); -// A Design command's silent form: what it does given its arguments, on the panel cad_gate() returned. -using CadRun = nlohmann::json (*)(DesignPanel* panel, const nlohmann::json& params); +// A Design command's silent form: what it does given its arguments, on the panel design_gate() returned. +using DesignRun = nlohmann::json (*)(DesignPanel* panel, const nlohmann::json& params); -// The silent forms, by the id of the table's entry whose tool block describes them: one per block. -extern const std::pair kSilentForms[]; -extern const std::size_t kSilentFormCount; +// A silent form, by the id of the table's entry whose tool block describes it. +using SilentForm = std::pair; + +// The silent forms: one per block. +const std::vector& silent_forms(); // A Design command: group Design, not listed, its function run on the UI thread and told whether it runs for a // person's pick (ToolContext::person()), which keeps the menu's rules where a call may target the Feature list's row @@ -125,7 +131,7 @@ extern const std::size_t kSilentFormCount; // records would open a tool and the call did not, so that a replay runs the silent form too (`opens` empty: // nothing opens a tool); then `fn` runs in one UI closure and the call settles. The reply is fn's value, without // an "ok": true or an empty "error", which say nothing; a ToolFailure is the call's error. -NativeCommand cad_command(std::string key, std::string title, nlohmann::json schema, +NativeCommand design_command(std::string key, std::string title, nlohmann::json schema, std::function fn, std::function opens = {}); @@ -136,18 +142,18 @@ NativeCommand cad_command(std::string key, std::string title, nlohmann::json sch // only while the Design tab is shown in its entry's mode, ActionRegistry::materialize_design_actions()). One with a // block is read_only for Read access, and its description is the block's summary, details and, for a silent form // that reports a rejected rebuild in its reply, how that shows, then the other calls that open a tool, each with its -// item's name; its examples are the block's and its schema cad_input_schema() of it, through with_silent() when a +// item's name; its examples are the block's and its schema design_input_schema() of it, through with_silent() when a // call with no arguments opens a tool. One with a handler only takes no arguments, and its description is its hint // and what the call does. // undo and redo are the shared commands of NativeCommands.cpp and not among them. -void register_cad_commands(CommandCatalog& catalog); +void register_design_tools(CommandCatalog& catalog); -// Records in `catalog`, built without the Design commands, that it leaves out the keys register_cad_commands() +// Records in `catalog`, built without the Design commands, that it leaves out the keys register_design_tools() // adds, and the ids of the items folded into them, which name actions, with code design_unavailable and why // (CommandCatalog::leave_out()): in the editor (`editor`) the CAD feature was off when OrcaSlicer started, and how a // person turns it on; in the G-code viewer, which has no Design tab whatever the preference, that a person opens the // project in the editor. -void leave_out_cad_commands(CommandCatalog& catalog, bool editor); +void leave_out_design_tools(CommandCatalog& catalog, bool editor); // What tool_list's description says of the Design commands, which tools/list does not show, so that an agent // learns without a call that they exist and are CAD: a lead saying what they cover, that tool_list's group Design @@ -170,16 +176,7 @@ std::vector sketch_target_indices(const nlohmann::json& params, const std:: // generation the call's face and edge ids were read at, is an optional property of every one. Every schema // refuses an argument it does not name (additionalProperties false), so a misspelt argument is an error rather // than a default the caller did not mean; a name agents often use for a param is read by normalize_arguments(). -nlohmann::json cad_input_schema(const nlohmann::json& block); - -// The checks every Design command passes before its function, in this order: the main window is up (not -// shutting down or still starting), the app is the editor and not the G-code viewer (design_unavailable), -// the CAD feature is on, and the Design panel can be built (design_unavailable for each); then the busy rules of -// `access` (design_busy, with a hint naming confirm_tool and cancel_tool; with Read, None and Ui only a rebuild's), the -// project's recipe loaded into an empty document (DesignPanel::hydrate_from_model()), as showing the tab would, and a -// `generation` in `args` that cad_generation() refuses (invalid_argument) or that is not the model's (stale_ids). -// Returns the panel. Throws ToolFailure, whose details carry the code. UI thread only. -DesignPanel* cad_gate(CadAccess access, const nlohmann::json& args); +nlohmann::json design_input_schema(const nlohmann::json& block); // The Design table's entry `id`, or nullptr. const DesignTool* find_design_tool(const std::string& id); @@ -212,7 +209,7 @@ struct DesignAction // The Speed Dial actions the Design tab has while it is shown in the mode `sketching` names (as offered_in_mode() // takes it): one per entry of the Design table with a handler offered in that mode, in the table's order, whose // command `catalog` holds: a folded item's runs the command it is folded into with the item's args. None while the -// CAD feature is off (`cad_on` false): the tab stays until a restart, but cad_gate() would refuse every pick of +// CAD feature is off (`cad_on` false): the tab stays until a restart, but design_gate() would refuse every pick of // its actions. std::vector design_actions(const CommandCatalog& catalog, bool sketching, bool cad_on); @@ -227,16 +224,16 @@ std::vector design_actions(const CommandCatalog& catalog, bool ske // is a msgid, the code wrong_mode, with a hint naming the commands that change the mode, or wrong_selection. std::optional open_refusal(const DesignTool& t, bool sketching, int kind, bool row_target = false); -// Runs the silent form of Design command `id` with `args` past cad_gate() with its entry's access, and +// Runs the silent form of Design command `id` with `args` past design_gate() with its entry's access, and // returns its result. One that fails has the code of its cause (the list at the top), with "OCCT: " before a // kernel exception's message; an id with no silent form is no_silent_form. UI thread only. -nlohmann::json run_cad_tool(const std::string& id, const nlohmann::json& args); +nlohmann::json run_design_tool(const std::string& id, const nlohmann::json& args); -// Edit > Undo, or Redo, in the Design tab, past cad_gate() with Sketch access: the Design history, or in a +// Edit > Undo, or Redo, in the Design tab, past design_gate() with Sketch access: the Design history, or in a // sketch session the sketch's own, which takes off or puts back the last drawn shape. Returns its scope, // "sketch" with the sketch's entities, or "design" and the undo and redo depth, features, bodies and // generation. Fails (precondition) when there is nothing to take back or put back. UI thread only. -nlohmann::json cad_undo_redo(bool redo); +nlohmann::json design_undo_redo(bool redo); // app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands // cannot run, because `catalog` holds none of them (the feature was off at startup) or the feature is off diff --git a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp deleted file mode 100644 index f0eb6756c8..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp +++ /dev/null @@ -1,451 +0,0 @@ -// The gizmo commands: a named target's gizmo opened on it (object_paint, object_measure, object_simplify, part_boolean, -// object_cut, object_lay_on_face, object_set_brim_ears). A call that names only its targets opens the gizmo and the -// client works it with the GUI tools; a command whose gizmo has an entry point that asks nothing also acts from its -// acting arguments (gizmo_acting_args()), with no gizmo: a cut by a plane, a lay on face by a direction, brim ears by -// position. - -#include "McpTargets.hpp" -#include "McpTools.hpp" -#include "UiInspector.hpp" - -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GLCanvas3D.hpp" -#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/Operations/GizmoOps.hpp" -#include "slic3r/GUI/Operations/ObjectOps.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Plater.hpp" -#include "slic3r/GUI/Selection.hpp" - -#include "libslic3r/BrimEarsPoint.hpp" -#include "libslic3r/Model.hpp" -#include "libslic3r/Point.hpp" -#include "libslic3r/TriangleMesh.hpp" -#include "libslic3r/libslic3r.h" - -#include - -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; - -namespace { - -using EType = GLGizmosManager::EType; - -// How a call's targets become what its gizmo opens on: `kinds` and `one` read them (resolve_targets()), and `to_gizmo` -// turns them into the selection the gizmo works on. -struct GizmoTargets -{ - unsigned kinds = kObjects; - bool one = true; - Targets (*to_gizmo)(const Model& model, Targets named) = nullptr; -}; - -// One instance of one object: the instance named, else the object's first. -Targets one_instance(const Model&, Targets named) -{ - if (!named.objects.empty()) { - named.instances = {{named.objects.front(), 0}}; - named.objects.clear(); - } - return named; -} - -// One part: the part named, else the only part of an object of one part. An object of several parts stays as it is, -// which the operation refuses as Simplify's panel would. -Targets one_part(const Model& model, Targets named) -{ - if (!named.objects.empty() && model.objects[std::size_t(named.objects.front())]->volumes.size() == 1) { - named.parts = {{named.objects.front(), 0}}; - named.objects.clear(); - } - return named; -} - -// Opens the gizmo of `type` on what `args` name, else on the selection as it is: a call that names no target does not -// read the selection as targets, so the gizmo's own condition decides what it opens on (Measure on a part). The reply -// is the gizmo, that it is open, and what is selected. -json open_on(const json& args, EType type, const GizmoTargets& reading) -{ - Plater& plater = ui_plater(); - Ops::OpenGizmoArgs op; - op.type = type; - if (names_targets(args)) { - const Ops::Outcome named = resolve_targets(plater.model(), nullptr, args, reading.kinds, reading.one); - if (!named) - throw refused(named.refusal()); - op.targets = reading.to_gizmo != nullptr ? reading.to_gizmo(plater.model(), named.value()) : named.value(); - } else - op.targets.from_selection = true; - const Ops::Outcome opened = Ops::open_gizmo(op); - if (!opened) - throw refused(opened.refusal()); - json reply = targets_reply(plater.model(), opened.value().on); - reply["gizmo"] = gizmo_name(int(type)); - reply["active"] = true; - return reply; -} - -// What every gizmo command's description says of working the open gizmo. -const char* const kWorkTheGizmo = - " Read the gizmo's panel with `widget_list {include_imgui: true}`, set its fields with `widget_set_value`, press its " - "buttons with `widget_click`, and click or drag on the model with `mouse_gesture`; `object_select {none: true}` closes it. " - "The gizmo already open on the same target stays open. Reply: gizmo (its name, as `app_state.gizmo` gives it), active, " - "and what is selected (objects, instances, parts)."; - -// Whether a call of `command` gives one of its acting arguments, and so does the job with no gizmo. -bool acts(const json& args, const std::string& command) -{ - for (const std::string& name : gizmo_acting_args(command)) - if (args.contains(name)) - return true; - return false; -} - -Vec3d to_vec3(const json& v, const char* what) -{ - // Each element too: a schema may give the array no items, and get() throws on anything but a number. - if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) - throw ToolFailure(std::string(what) + " must be [x, y, z], three numbers", {{"code", "invalid_argument"}}); - return {v[0].get(), v[1].get(), v[2].get()}; -} - -Ops::CutPlacement placement(const std::string& name) -{ - return name == "as_cut" ? Ops::CutPlacement::AsCut : name == "flip" ? Ops::CutPlacement::Flip : Ops::CutPlacement::PlaceOnCut; -} - -// What an object of the model is in a cut's reply: its index, id and name, and the open edges its parts have, which -// object_fix repairs. -json piece(const Model& model, int index) -{ - const ModelObject& object = *model.objects[std::size_t(index)]; - std::size_t open_edges = 0; - for (const ModelVolume* volume : object.volumes) - open_edges += its_num_open_edges(volume->mesh().its); - return {{"index", index}, {"object_id", object.id().id}, {"name", object.name}, {"open_edges", open_edges}}; -} - -// The one instance a gizmo command acts on: the instance or object named (the object's first instance), else the one -// selected. -std::pair acted_on(Plater& plater, const json& args) -{ - const Ops::Outcome named = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, - kObjects | kInstances, true); - if (!named) - throw refused(named.refusal()); - return one_instance(plater.model(), named.value()).instances.front(); -} - -// object_cut from its acting arguments. The arguments the Cut gizmo's panel could not set together are refused before -// anything is read: z with plane, a placement for a piece not kept, and placements or one piece with Cut to parts. -json cut_from_args(const json& args) -{ - if (args.contains("z") && args.contains("plane")) - throw ToolFailure("Give z or plane, not both."); - if (!args.contains("z") && !args.contains("plane")) - throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_plane", - L("A cut needs its plane: give z or plane with keep, upper, lower or to_parts.")}); - Ops::CutObjectArgs op; - if (args.contains("plane")) { - op.point = to_vec3(args["plane"]["point"], "plane.point"); - op.normal = to_vec3(args["plane"]["normal"], "plane.normal"); - if (op.normal.norm() < EPSILON) - throw ToolFailure("plane.normal is zero: give the direction the upper piece lies in."); - } - const std::string keep = args.value("keep", std::string("both")); - op.keep_upper = keep != "lower"; - op.keep_lower = keep != "upper"; - if (args.contains("upper") && !op.keep_upper) - throw ToolFailure("upper places the upper piece, but the upper piece is not kept (keep \"lower\")."); - if (args.contains("lower") && !op.keep_lower) - throw ToolFailure("lower places the lower piece, but the lower piece is not kept (keep \"upper\")."); - op.to_parts = args.value("to_parts", false); - if (op.to_parts && keep != "both") - throw ToolFailure("to_parts keeps both pieces, as two parts of one object; leave keep out."); - if (op.to_parts && (args.contains("upper") || args.contains("lower"))) - throw ToolFailure("to_parts places no piece: both stay as cut; leave upper and lower out."); - if (args.contains("upper")) - op.upper = placement(args["upper"].get()); - if (args.contains("lower")) - op.lower = placement(args["lower"].get()); - - Plater& plater = ui_plater(); - std::tie(op.object, op.instance) = acted_on(plater, args); - if (args.contains("z")) { - // A level plane that high above the bed, through the instance. - op.point = plater.model().objects[std::size_t(op.object)]->instances[std::size_t(op.instance)]->get_offset(); - op.point.z() = args["z"].get(); - op.normal = Vec3d::UnitZ(); - } - - const Ops::Outcome cut = Ops::cut_object(op); - if (!cut) - throw refused(cut.refusal()); - const Model& model = plater.model(); - json reply; - if (op.to_parts) { - reply["object"] = piece(model, cut.value().objects.front()); - reply["parts"] = targets_reply(model, cut.value()).value("parts", json::array()); - } else { - reply["pieces"] = json::array(); - for (int index : cut.value().objects) - reply["pieces"].push_back(piece(model, index)); - } - return reply; -} - -// object_lay_on_face from its acting arguments. -json lay_from_args(const json& args) -{ - if (!args.contains("normal")) - throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_normal", - L("Laying an object on a face needs the face's direction: give normal with frame.")}); - Plater& plater = ui_plater(); - Ops::LayOnFaceArgs op; - std::tie(op.object, op.instance) = acted_on(plater, args); - op.normal = to_vec3(args["normal"], "normal"); - op.world = args.value("frame", std::string("object")) == "world"; - const Ops::Outcome turned = Ops::lay_on_face(op); - if (!turned) - throw refused(turned.refusal()); - const Vec3d degrees = turned.value() * (180. / PI); - return {{"object", op.object}, {"instance", op.instance}, {"rotation", {degrees.x(), degrees.y(), degrees.z()}}}; -} - -// object_set_brim_ears from its acting arguments. -json brim_ears_from_args(const json& args) -{ - if (args.contains("points") && args.contains("clear")) - throw ToolFailure("Give points or clear, not both."); - Plater& plater = ui_plater(); - Ops::SetBrimEarsArgs op; - std::tie(op.object, op.instance) = acted_on(plater, args); - for (const json& point : args.value("points", json::array())) { - const json& at = point.at("position"); - if (!at.is_array() || at.size() != 2) - throw ToolFailure("points[].position must be [x, y]"); - Ops::BrimEar ear; - ear.position = Vec2d(at[0].get(), at[1].get()); - if (point.contains("radius")) - ear.radius = point["radius"].get(); - op.ears.push_back(ear); - } - const Ops::Outcome set = Ops::set_brim_ears(op); - if (!set) - throw refused(set.refusal()); - json ears = json::array(); - for (const BrimPoint& ear : set.value().ears) - ears.push_back({{"position", {ear.pos.x(), ear.pos.y(), ear.pos.z()}}, {"radius", ear.head_front_radius}}); - return {{"object", op.object}, {"ears", std::move(ears)}, {"brim_type", set.value().brim_type}, - {"takes_effect", set.value().takes_effect}}; -} - -NativeCommand gizmo_command(std::string name, std::string title, std::string description, json schema, EType type, - GizmoTargets reading, json examples) -{ - NativeCommand command = with_target_ids(mutate_tool(std::move(name), std::move(title), description + kWorkTheGizmo, - std::move(schema), [type, reading](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { return open_on(args, type, reading); }); - settle(ctx); - return ToolResult::ok(out); - })); - command.examples = std::move(examples); - return reaching({"open_gizmo"}, std::move(command)); -} - -// The painting gizmos, by object_paint's type. -const std::vector> kPaintTypes{ - {"supports", EType::FdmSupports}, {"seam", EType::Seam}, {"color", EType::MmSegmentation}, {"fuzzy_skin", EType::FuzzySkin}}; - -} // namespace - -const std::vector& gizmo_acting_args(const std::string& command) -{ - // The gizmo commands' acting arguments: a call with any of them does the job and opens no gizmo. - static const std::map> acting{ - {"object_paint", {}}, {"object_measure", {}}, {"object_simplify", {}}, {"part_boolean", {}}, - {"object_cut", {"z", "plane", "keep", "upper", "lower", "to_parts"}}, - {"object_lay_on_face", {"normal", "frame"}}, - {"object_set_brim_ears", {"points", "clear"}}}; - static const std::vector none; - const auto found = acting.find(command); - return found != acting.end() ? found->second : none; -} - -void register_gizmo_tools(CommandCatalog& catalog) -{ - std::vector paint_types; - for (const auto& [name, type] : kPaintTypes) - paint_types.push_back(name); - NativeCommand paint = with_target_ids(mutate_tool( - "object_paint", L("Paint on an object"), - std::string("Open a painting gizmo on an object's instance, the first unless instance is given: type supports opens " - "Support Painting, seam Seam Painting, color Color Painting (two filaments or more) and `fuzzy_skin` Paint-on " - "fuzzy skin. Painting is left to the gizmo: pick a tool and a brush in its panel and paint with " - "`mouse_gesture` strokes on the model. With no target, it opens on the selection as it is.") + - kWorkTheGizmo, - with_targets(object_schema({{"type", enum_prop(paint_types, "The painting gizmo to open.")}}, {"type"}), kObjects | kInstances, true), - [](const json& args, ToolContext& ctx) { - EType type = EType::FdmSupports; - for (const auto& [name, t] : kPaintTypes) - if (name == args.value("type", std::string())) - type = t; - json out = ctx.run_ui([&] { return open_on(args, type, {kObjects | kInstances, true, one_instance}); }); - settle(ctx); - return ToolResult::ok(out); - })); - paint.examples = json::parse(R"json([ - {"title": "Paint support enforcers on object 0", "calls": [ - {"tool": "object_paint", "args": {"object": 0, "type": "supports"}}]}, - {"title": "Paint colors on the second instance of object 1", "calls": [ - {"tool": "object_paint", "args": {"object": 1, "instance": 1, "type": "color"}}]}])json"); - catalog.add(reaching({"open_gizmo"}, std::move(paint))); - - catalog.add(gizmo_command( - "object_measure", L("Measure"), - "Open the Measure gizmo on objects, else on the selection as it is (a part selected is measured as a part). " - "Measuring is left to the gizmo: click two features of the model with `mouse_gesture` (Shift-click for a point) and " - "read the results in its panel.", - with_targets(object_schema({}), kObjects, false), EType::Measure, {kObjects, false, nullptr}, - json::parse(R"json([ - {"title": "Measure between objects 0 and 1", "calls": [{"tool": "object_measure", "args": {"objects": [0, 1]}}]}, - {"title": "Measure the selected part", "calls": [ - {"tool": "object_select", "args": {"parts": [[0, 1]]}}, {"tool": "object_measure", "args": {}}]}])json"))); - - catalog.add(gizmo_command( - "object_simplify", L("Simplify Model"), - "Open the Simplify gizmo on a part: the part named, else the only part of the object named (an object of several " - "parts needs part), else the selected part. The detail level or ratio and Apply are left to the gizmo.", - with_targets(object_schema({}), kObjects | kParts, true), EType::Simplify, {kObjects | kParts, true, one_part}, - json::parse(R"json([ - {"title": "Simplify object 0, an object of one part", "calls": [{"tool": "object_simplify", "args": {"object": 0}}]}, - {"title": "Simplify part 1 of object 2", "calls": [{"tool": "object_simplify", "args": {"object": 2, "part": 1}}]}])json"))); - - catalog.add(gizmo_command( - "part_boolean", L("Mesh Boolean"), - "Open the Mesh Boolean gizmo on an object of two parts or more, its first instance. The operation (Union, Difference " - "or Intersection), the two parts and Delete input are left to the gizmo: pick each part with a `mouse_gesture` click " - "on a point of it the camera can see, then press the operation's button.", - with_targets(object_schema({}), kObjects, true), EType::MeshBoolean, {kObjects, true, one_instance}, - json::parse(R"json([ - {"title": "Open Mesh Boolean on object 0", "calls": [{"tool": "part_boolean", "args": {"object": 0}}]}, - {"title": "Open Mesh Boolean on the selected object", "calls": [{"tool": "part_boolean", "args": {}}]}])json"))); - - const std::vector placements{"as_cut", "place_on_cut", "flip"}; - json point = array_prop({{"type", "number"}}, "`[x, y, z]` mm: a point of the plane, in the 3D view's coordinates."); - json normal = array_prop({{"type", "number"}}, "`[x, y, z]`: the direction the upper piece lies in; any length but zero."); - point["minItems"] = normal["minItems"] = 3; - json plane = object_schema({{"point", std::move(point)}, {"normal", std::move(normal)}}, {"point", "normal"}); - plane["description"] = "Cut along this plane. Not with z."; - NativeCommand cut = with_target_ids(mutate_tool( - "object_cut", L("Cut"), - std::string( - "Cut an object's instance, the first unless instance is given, along a plane, as the Cut gizmo's Perform cut does. " - "Acts from arguments: `z`, `plane`, `keep`, `upper`, `lower`, `to_parts`. With none of them it opens the Cut gizmo. z cuts " - "level, that many mm above the bed; plane `{point, normal}` cuts along any plane, the upper piece being the one " - "the normal points into. keep: both (default), upper or lower. upper and lower place a kept piece: `as_cut`, " - "`place_on_cut` (laid on its cut face) or flip; by default the upper piece is laid on its cut face and the lower " - "one stays as cut. `to_parts` keeps both pieces as two parts of one object, with no placement. A cut is one undo " - "step and replaces the object: its pieces go to the end of the object list, upper first, and the reply gives " - "them as pieces [`{index, object_id, name, open_edges}`], or with `to_parts` the object and its parts. A piece with " - "open edges is repaired by `object_fix`. Connectors, the dovetail and a cut along a contour are left to the gizmo: " - "open it with `object_cut` naming only the object.") + - kWorkTheGizmo, - with_targets(object_schema({{"z", prop("number", "mm above the bed: cut level at this height. Not with plane.")}, - {"plane", std::move(plane)}, - {"keep", enum_prop({"both", "upper", "lower"}, "The pieces kept. Default both.")}, - {"upper", enum_prop(placements, "Where the upper piece goes. Default `place_on_cut`.")}, - {"lower", enum_prop(placements, "Where the lower piece goes. Default `as_cut`.")}, - {"to_parts", prop("boolean", "Keep both pieces as two parts of one object, as the gizmo's " - "Cut to parts does. Default false.")}}), - kObjects | kInstances, true), - [](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { - return acts(args, "object_cut") ? cut_from_args(args) : open_on(args, EType::Cut, {kObjects | kInstances, true, one_instance}); - }); - settle(ctx); - return ToolResult::ok(out); - })); - cut.examples = json::parse(R"json([ - {"title": "Cut object 0 in two, 10 mm above the bed", "calls": [{"tool": "object_cut", "args": {"object": 0, "z": 10}}]}, - {"title": "Keep the part of object 1 above a tilted plane", "calls": [ - {"tool": "object_cut", "args": {"object": 1, "plane": {"point": [100, 100, 10], "normal": [1, 0, 1]}, "keep": "upper"}}]}])json"); - catalog.add(reaching({"open_gizmo", "cut_object"}, std::move(cut))); - - NativeCommand lay = with_target_ids(mutate_tool( - "object_lay_on_face", L("Lay on face"), - std::string( - "Lay an object's instance, the first unless instance is given, on one of its faces, as a click on that face in " - "the Lay on Face gizmo does. Acts from arguments: `normal`, `frame`. With none of them it opens the Lay on Face " - "gizmo. normal is the direction the face points out to: in the object's own frame (frame object, the default, " - "where `[0, 0, -1]` is the face that was its bottom) or in the 3D view's (frame world, where the face points now). " - "The instance turns so that face lies on the bed and drops onto it, one undo step; the object's other instances " - "turn with it. No flat face is looked for: the direction is laid down as given. A call that acts replies object, " - "instance and rotation, the instance's rotation in degrees as `object_list` gives it.") + - kWorkTheGizmo, - with_targets(object_schema({{"normal", array_prop({{"type", "number"}}, "`[x, y, z]`: the direction the face to lay on the bed " - "points out to; any length but zero.")}, - {"frame", enum_prop({"object", "world"}, "The frame normal is in: the object's own (default) or " - "the 3D view's. Needs normal.")}}), - kObjects | kInstances, true), - [](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { - return acts(args, "object_lay_on_face") ? lay_from_args(args) : - open_on(args, EType::Flatten, {kObjects | kInstances, true, one_instance}); - }); - settle(ctx); - return ToolResult::ok(out); - })); - lay.examples = json::parse(R"json([ - {"title": "Lay object 0 on the face that points down in its own frame", "calls": [ - {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [0, 0, -1]}}]}, - {"title": "Lay object 0 on the face that now points to +X", "calls": [ - {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [1, 0, 0], "frame": "world"}}]}])json"); - catalog.add(reaching({"open_gizmo", "lay_on_face"}, std::move(lay))); - - json ear = object_schema({{"position", array_prop({{"type", "number"}}, "`[x, y]` mm: where on the bed.")}, - {"radius", prop("number", "mm. Default: the gizmo's, eight first-layer line widths.")}}, - {"position"}); - NativeCommand brim = with_target_ids(mutate_tool( - "object_set_brim_ears", L("Brim ears"), - std::string( - "Set an object's brim ears from positions on the bed, as the Brim Ears gizmo places them, through the instance " - "named, the first unless instance is given. Acts from arguments: `points`, `clear`. With none of them it opens the " - "Brim Ears gizmo. points replaces the object's ears with those given, each at a bed position, with a radius " - "from 0.1 to 100 mm or the gizmo's default; clear removes them all. The ears are taken on the bed and stored in " - "the object's coordinates, so they are the object's, shared by its instances. One undo step. They print only " - "with the painted brim type: `settings_set` on the object sets `brim_type`. A call that acts replies object, ears " - "as stored ({position: `[x, y, z]` in the object's coordinates, radius}), `brim_type`, the brim type the object " - "prints with, and `takes_effect`, whether that is painted.") + - kWorkTheGizmo, - with_targets(object_schema({{"points", array_prop(std::move(ear), "The ears, in place of the object's.")}, - {"clear", {{"type", "boolean"}, {"enum", {true}}, {"description", "Remove every ear. Not with points."}}}}), - kObjects | kInstances, true), - [](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { - return acts(args, "object_set_brim_ears") ? brim_ears_from_args(args) : - open_on(args, EType::BrimEars, {kObjects | kInstances, true, one_instance}); - }); - settle(ctx); - return ToolResult::ok(out); - })); - brim.examples = json::parse(R"json([ - {"title": "Paint object 0's brim as two ears at its front corners", "calls": [ - {"tool": "settings_set", "args": {"target": "object", "object": 0, "values": {"brim_type": "painted"}}}, - {"tool": "object_set_brim_ears", "args": {"object": 0, "points": [{"position": [90, 90], "radius": 3}, {"position": [110, 90]}]}}]}, - {"title": "Remove object 1's ears", "calls": [{"tool": "object_set_brim_ears", "args": {"object": 1, "clear": true}}]}])json"); - catalog.add(reaching({"open_gizmo", "set_brim_ears"}, std::move(brim))); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp deleted file mode 100644 index 8d0747dd73..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp +++ /dev/null @@ -1,688 +0,0 @@ -// object_set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier), -// given as the whole set of ranges, whose settings the settings tools set. object_set_variable_layer_height: the -// Variable layer height panel's Adaptive, Smooth and Reset on an object. And how object_list reports both. -// plate_set_custom_gcode: the pauses, custom G-codes and filament changes of a plate's layers, through the Preview's -// layer slider. - -#include "slic3r/GUI/I18N.hpp" -#include "McpTargets.hpp" -#include "McpTools.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GCodeViewer.hpp" -#include "slic3r/GUI/GLCanvas3D.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/GUI_ObjectList.hpp" -#include "slic3r/GUI/IMSlider.hpp" -#include "slic3r/GUI/MainFrame.hpp" -#include "slic3r/GUI/Operations/ObjectOps.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/PartPlate.hpp" -#include "slic3r/GUI/Plater.hpp" -#include "slic3r/GUI/Selection.hpp" -#include "slic3r/GUI/TickCode.hpp" - -#include "libslic3r/Config.hpp" -#include "libslic3r/CustomGCode.hpp" -#include "libslic3r/GCode/GCodeProcessor.hpp" -#include "libslic3r/Model.hpp" -#include "libslic3r/Preset.hpp" -#include "libslic3r/PresetBundle.hpp" -#include "libslic3r/PrintConfig.hpp" -#include "libslic3r/Slicing.hpp" -#include "libslic3r/libslic3r.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; - -namespace { - -// A height as messages show it: 15, 12.5, 0.08. -std::string mm(double z) -{ - std::ostringstream out; - out << z; - return out.str(); -} - -ToolFailure overlap(const Slic3r::t_layer_height_range& lower, const Slic3r::t_layer_height_range& upper) -{ - return ToolFailure("Ranges " + height_range_text(lower) + " and " + height_range_text(upper) + - " overlap; ranges may touch, one's max_z being the next one's min_z"); -} - -bool same_ranges(const t_layer_config_ranges& a, const t_layer_config_ranges& b) -{ - return a.size() == b.size() && - std::equal(a.begin(), a.end(), b.begin(), [](const auto& x, const auto& y) { return x.first == y.first && x.second.get() == y.second.get(); }); -} - -// What the GUI tells a person about an object's layer heights, as warnings: the dialog it shows before -// variable layer heights or height ranges when the process mixes colours in sublayers, and what the -// object list's variable layer height mark implies for the ranges. -json layer_height_warnings(const ModelObject& object) -{ - json warnings = json::array(); - const bool variable = !layer_height_profile_json(object.layer_height_profile.get()).is_null(); - if (!variable && object.layer_config_ranges.empty()) - return warnings; - const auto* mixed = wxGetApp().preset_bundle->prints.get_edited_preset().config.option("enable_mixed_color_sublayer"); - if (mixed != nullptr && mixed->value) - warnings.push_back("Using variable layer height together with mixed color sublayer may result in poor color mixing quality."); - if (variable && !object.layer_config_ranges.empty()) - warnings.push_back("The object's variable layer height profile, not the ranges' layer_height, decides its layer heights."); - return warnings; -} - -// The index of the object a layer call names, else of the one selected in the Prepare view (or of the object of the -// selected instance or part), on an FFF printer. -int layer_object(Plater& plater, const json& args) -{ - if (plater.printer_technology() != ptFFF) - throw ToolFailure("Height range modifiers and variable layer heights are for FFF printers"); - const Ops::Outcome target = - resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, kObjects | kObjectOfSelection, true); - if (!target) - throw refused(target.refusal()); - return target.value().objects.front(); -} - -// The reply's naming of object `oi`, as every command with a target gives it. -json named_object(const Plater& plater, int oi) -{ - Ops::Targets object; - object.objects = {oi}; - return targets_reply(plater.model(), object); -} - -// The object object_set_variable_layer_height names, or the one selected, after the checks that need no view, such as -// an argument that goes with another action. -int profile_object(Plater& plater, const json& args) -{ - const int oi = layer_object(plater, args); - const std::string action = arg_string(args, "action"); - if (args.contains("quality") && action != "adaptive") - throw ToolFailure("quality goes with action adaptive"); - if ((args.contains("radius") || args.contains("keep_min")) && action != "smooth") - throw ToolFailure("radius and keep_min go with action smooth"); - return oi; -} - -// What the panel's Adaptive, Smooth and Reset buttons run, on the object selected as the panel's -// object is, without opening the panel. Reset of an object without a profile changes nothing. -json set_variable_layer_height(Plater& plater, const json& args) -{ - const int oi = profile_object(plater, args); - ModelObject& object = *plater.model().objects[std::size_t(oi)]; - const std::string action = arg_string(args, "action"); - GLCanvas3D& canvas = require_prepare_scene(plater); - - if (action != "reset" || !object.layer_height_profile.empty()) { - select_rows(&object, nullptr); - // The rule that enables the toolbar's Variable layer height item, with the reason it fails. - if (!plater.can_layers_editing()) - throw ToolFailure(object.max_z() <= SINKING_Z_THRESHOLD ? - "object " + std::to_string(oi) + " is below the bed, where its layer heights can't be edited" : - !canvas.is_layers_editing_allowed() ? - "The variable layer height tool needs an OpenGL shader that this system did not load" : - "object " + std::to_string(oi) + " could not be selected for the variable layer height tool"); - if (action == "adaptive") - canvas.adaptive_layer_height_profile(float(arg_double(args, "quality", 0.5))); - else if (action == "smooth") - canvas.smooth_layer_height_profile(HeightProfileSmoothingParams(unsigned(arg_int(args, "radius", 5)), arg_bool(args, "keep_min", false))); - else - canvas.reset_layer_height_profile(); - } - - json out = named_object(plater, oi); - out.update({{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}}); - if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null()) - out["layer_height_profile"] = std::move(profile); - if (json warnings = layer_height_warnings(object); !warnings.empty()) - out["warnings"] = std::move(warnings); - return out; -} - -// What the object list does when a person adds and removes ranges, with the whole set given at once, on the object the -// call names or the one selected. A range's settings are the settings tools' (target height_range). Everything the -// arguments can tell is checked before anything changes. -json set_height_ranges(Plater& plater, const json& args) -{ - const int oi = layer_object(plater, args); - ModelObject* object = plater.model().objects[std::size_t(oi)]; - ObjectList* list = wxGetApp().obj_list(); - t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), object->layer_config_ranges, - list->get_default_layer_config(oi)); - require_prepare_scene(plater); - - if (!same_ranges(ranges, object->layer_config_ranges)) { - // The object's row, as right-clicking it selects it, so no row or sidebar editor of the old ranges - // stays in use while they are replaced. - select_rows(object, nullptr); - plater.take_snapshot("Edit height ranges"); - object->layer_config_ranges = std::move(ranges); - list->reload_layer_rows(oi); - plater.changed_object(oi); - } - - json out = named_object(plater, oi); - out.update({{"object", oi}, - {"height", object->instance_bounding_box(0).max.z()}, - {"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}}); - if (json warnings = layer_height_warnings(*object); !warnings.empty()) - out["warnings"] = std::move(warnings); - return out; -} - -// The plate plate_set_custom_gcode names (default: the current one), after the checks that need neither its -// layers nor a view. -int gcode_plate(Plater& plater, const json& args) -{ - if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) - throw ToolFailure("Layer G-codes are for the plates of an FFF project"); - const bool edits = arg_bool(args, "clear", false) || !args.value("add", json::array()).empty() || - !args.value("remove", json::array()).empty(); - if (!edits) - throw ToolFailure("Give add, remove or clear; plate_list lists each plate's layer_gcode"); - PartPlateList& plates = plater.get_partplate_list(); - const int index = arg_int(args, "plate", plates.get_curr_plate_index()); - if (index < 0 || index >= plates.get_plate_count()) - throw ToolFailure(no_such_plate(index, plates.get_plate_count())); - PartPlate& plate = *plates.get_plate(index); - const std::string name = "plate " + std::to_string(index); - // The slider's menus offer no codes on a plate printed by object, and it erases them all when it - // shows one; a sliced G-code shown without its objects (.gcode.3mf) has no menus either. - if (!plate.has_printable_instances()) - throw ToolFailure(name + " has nothing to print, so no layers to place codes on"); - if (plate.get_real_print_seq() == PrintSequence::ByObject) - throw ToolFailure(name + " prints by object (print_sequence), which takes no layer G-codes"); - // A slice would replace the layers under the edit. - if (plater.is_slicing_any()) - throw ToolFailure("Slicing is in progress; app_wait {for: \"idle\"} first"); - return index; -} - -// Whether the Preview shows the plate's layers: its layer slider holds that plate's layers and codes, -// as when a person opened it. A plate edited after its slice and still shown keeps them, so a person -// can go on editing it, and so can MCP. -bool preview_shows_plate(Plater& plater, int index) -{ - PartPlateList& plates = plater.get_partplate_list(); - GLCanvas3D* preview = plater.get_preview_canvas3D(); - if (index != plates.get_curr_plate_index() || !plater.is_preview_shown() || preview == nullptr) - return false; - GCodeViewer& viewer = preview->get_gcode_viewer(); - return viewer_holds(viewer, plates.get_plate(index)->get_slice_result()) && - viewer.get_layers_slider()->GetMaxValue() + 1 == int(preview->get_gcode_layers_zs().size()); -} - -// A plate's codes as plate_list's layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer -// (1-based) where `zs` has a layer at or above z, the slider's rule for a stored height. -json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector& zs) -{ - std::vector items = codes.gcodes; - std::stable_sort(items.begin(), items.end()); - json out = json::array(); - for (const CustomGCode::Item& item : items) { - json code{{"z", std::round(item.print_z * 1000.) / 1000.}, {"type", custom_gcode_type_name(item.type)}}; - const auto layer = std::lower_bound(zs.begin(), zs.end(), item.print_z - epsilon()); - if (layer != zs.end()) - code["layer"] = int(layer - zs.begin()) + 1; - const bool change = item.type == CustomGCode::ToolChange || item.type == CustomGCode::ColorChange; - if (change && item.extruder > 0) - code["filament"] = item.extruder; - if (change && !item.color.empty()) - code["color"] = item.color; - if (item.type == CustomGCode::Custom && !item.extra.empty()) - code["gcode"] = item.extra; - out.push_back(std::move(code)); - } - return out; -} - -// plate_set_custom_gcode's reply, once the plater has the slider's codes. UI thread. -json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args) -{ - const Model& model = plater.model(); - const auto codes = model.plates_custom_gcodes.find(index); - const std::vector zs = plater.get_preview_canvas3D()->get_gcode_layers_zs(); - json out{{"plate", index}, - {"layers", zs.size()}, - {"changed", changed}, - {"layer_gcode", codes != model.plates_custom_gcodes.end() ? plate_layer_gcode(codes->second, zs) : json::array()}}; - if (changed) - out["note"] = "The plate's slice no longer matches its codes; slice it again before exporting."; - const PresetBundle& bundle = *wxGetApp().preset_bundle; - for (const json& item : args.value("add", json::array())) - if (arg_string(item, "type") == "pause" && bundle.printers.get_edited_preset().config.opt_string("machine_pause_gcode").empty()) { - out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with settings_set type printer)"}); - break; - } - return out; -} - -// Selects the plate plate_set_custom_gcode names and shows it in the Preview, unless the Preview shows its layers -// already, and returns its index. Refused calls leave the view alone. Only a plate with an up-to-date slice -// is opened: opening the Preview on one that is not starts a slice. -int show_plate_layers(Plater& plater, const json& args) -{ - const int index = gcode_plate(plater, args); - if (preview_shows_plate(plater, index)) - return index; - PartPlateList& plates = plater.get_partplate_list(); - if (!plates.get_plate(index)->is_slice_result_valid()) - throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (plate_slice {plates: " + - std::to_string(index) + "})"); - plater.select_view_3D("Preview"); - // What clicking a sliced plate in the Preview's plate toolbar does: select it and load its result, which - // a plate switch alone leaves to the next slice while the Preview shows. - plater.select_sliced_plate(index, true); - if (MainFrame* frame = wxGetApp().mainframe) - frame->select_tab(wxString(TAB_ID_PREVIEW)); - return index; -} - -// The edit itself: the plate's layers are in the Preview's layer slider, which takes the codes, and the -// next frame (or this call, at once) hands them to the plater, as for a person's edit. -json set_custom_gcode_at_layer(Plater& plater, int index, const json& args, CustomGCode::Info& handed_over) -{ - gcode_plate(plater, args); - if (!preview_shows_plate(plater, index)) - throw ToolFailure("The Preview no longer shows plate " + std::to_string(index) + "'s layers; call again"); - GLCanvas3D& preview = *plater.get_preview_canvas3D(); - IMSlider& slider = *preview.get_gcode_viewer().get_layers_slider(); - const PresetBundle& bundle = *wxGetApp().preset_bundle; - const bool spiral = bundle.prints.get_edited_preset().config.opt_bool("spiral_mode"); - bool changed = false; - try { - changed = edit_layer_gcode(slider, args, int(plater.get_extruder_colors_from_plater_config(nullptr).size()), - !bundle.printers.get_edited_preset().config.opt_string("template_custom_gcode").empty(), - slider.can_change_color() ? std::string() : - spiral ? std::string("spiral vase (spiral_mode) is on") : - std::string("its objects print with different filaments")); - } catch (const ToolFailure&) { - // Only the slider refusing a change comes after earlier changes; hand those over, as the next frame would. - preview.send_layer_ticks_changes(); - throw; - } - if (!changed) - return layer_gcode_reply(plater, index, false, args); - handed_over = slider.GetTicksValues(); - preview.send_layer_ticks_changes(); - return json(); -} - -} // namespace - -std::string height_range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); } - -std::vector layer_range_option_keys(int filaments) -{ - // A range's page in the sidebar edits layer_height and the per-region settings, of which the object - // list's Add settings menus offer a part or a range those with a category (no internal option), - // leaving out support settings, and per-feature filaments and wipe options while there is one - // filament (SettingsFactory's is_improper_category()). - std::vector keys{"layer_height"}; - for (const std::string& key : PrintRegionConfig().keys()) { - const ConfigOptionDef* def = print_config_def.get(key); - if (def == nullptr || def->category.empty() || def->category == "Support material" || - (filaments == 1 && (def->category == "Extruders" || def->category == "Wipe options"))) - continue; - keys.push_back(key); - } - // The filament column of a range's row. - keys.push_back("extruder"); - return keys; -} - -t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, - const t_layer_config_ranges& current, - const DynamicPrintConfig& defaults) -{ - if (!ranges.is_array()) - throw ToolFailure("ranges must be a list of {min_z, max_z}"); - t_layer_config_ranges out; - for (const json& r : ranges) { - if (!r.is_object()) - throw ToolFailure("A range is {min_z, max_z}"); - const Slic3r::t_layer_height_range range{arg_double(r, "min_z", -1.), arg_double(r, "max_z", -1.)}; - if (!(range.first >= 0. && range.first < range.second)) - throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + height_range_text(range)); - if (out.count(range) != 0) - throw overlap(range, range); - // A range of the object's with these heights keeps its settings, as the object list keeps a range it is not asked - // to change. - const auto kept = current.find(range); - if (kept != current.end()) - out[range].assign_config(kept->second.get()); - else - out[range].assign_config(defaults); - } - // Sorted by min_z; the slicer would trim an overlap silently, which from an agent is always a mistake. - const Slic3r::t_layer_height_range* lower = nullptr; - for (const auto& entry : out) { - if (lower != nullptr && entry.first.first + EPSILON < lower->second) - throw overlap(*lower, entry.first); - lower = &entry.first; - } - return out; -} - -void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range, - const std::function(int extruder)>& layer_height_bounds) -{ - // Only a layer height given is checked, as the range editor checks only what a person types. - if (!values.has("layer_height")) - return; - const DynamicPrintConfig& source = values.has("extruder") ? values : range; - const int extruder = source.has("extruder") ? source.opt_int("extruder") : 0; - const double height = values.opt_float("layer_height"); - const std::pair bounds = layer_height_bounds(extruder); - if (!(height >= bounds.first && height <= bounds.second)) - throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second)); -} - -json layer_config_ranges_json(const t_layer_config_ranges& ranges) -{ - json out = json::array(); - for (const auto& [range, config] : ranges) { - json values = json::object(); - for (const std::string& key : config.keys()) - values[key] = config.opt_serialize(key); - out.push_back({{"min_z", range.first}, {"max_z", range.second}, {"values", std::move(values)}}); - } - return out; -} - -json layer_height_profile_json(const std::vector& profile) -{ - // The object list marks an object's layer height as variable when its profile is more than a flat - // bottom-to-top pair. - if (profile.size() <= 4) - return nullptr; - double low = profile[1], high = profile[1]; - for (std::size_t i = 3; i < profile.size(); i += 2) { - low = std::min(low, profile[i]); - high = std::max(high, profile[i]); - } - // Computed heights, to the G-code's 0.001 mm. - const auto um = [](double h) { return std::round(h * 1000.) / 1000.; }; - return {{"points", profile.size() / 2}, {"min_height", um(low)}, {"max_height", um(high)}}; -} - -const char* custom_gcode_type_name(CustomGCode::Type type) -{ - switch (type) { - case CustomGCode::PausePrint: return "pause"; - case CustomGCode::Custom: return "custom"; - case CustomGCode::Template: return "template"; - case CustomGCode::ToolChange: return "change_filament"; - case CustomGCode::ColorChange: return "color_change"; - default: return "unknown"; - } -} - -CustomGCode::Type custom_gcode_type_from_name(const std::string& name) -{ - for (const CustomGCode::Type type : {CustomGCode::PausePrint, CustomGCode::Custom, CustomGCode::Template, CustomGCode::ToolChange}) - if (name == custom_gcode_type_name(type)) - return type; - return CustomGCode::Unknown; -} - -bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool has_template, const std::string& no_filament_change) -{ - const int layers = slider.GetMaxValue() + 1; - const auto layer = [](int tick) { return "layer " + std::to_string(tick + 1); }; - // `layer` counts from 1, as the slider's labels do; `z` is the layer whose top is at or above it, where - // the slider puts a stored height. - const auto item_tick = [&](const json& item) { - const bool by_layer = item.contains("layer"); - if (by_layer == item.contains("z")) - throw ToolFailure("Give layer or z for each code"); - if (by_layer) { - const int n = arg_int(item, "layer", 0); - if (n < 1 || n > layers) - throw ToolFailure("layer must be 1.." + std::to_string(layers) + " (z " + mm(slider.GetMinValueD()) + ".." + - mm(slider.GetMaxValueD()) + ")"); - return n - 1; - } - const double z = arg_double(item, "z", 0.); - const int tick = slider.get_tick_from_value(z, true); - if (tick < 0) - throw ToolFailure("z " + mm(z) + " is above the top layer (" + mm(slider.GetMaxValueD()) + " mm)"); - return tick; - }; - const auto listed = [](const std::map& codes) { - std::string text; - for (const auto& entry : codes) - text += (text.empty() ? "" : ", ") + std::to_string(entry.first + 1); - return codes.empty() ? std::string("no codes") : (codes.size() == 1 ? "a code on layer " : "codes on layers ") + text; - }; - - // Everything is checked on a copy first, so a refused call leaves the slider as it was. - std::map before; - for (const TickCode& code : slider.GetTicks()) - before.emplace(code.tick, code); - std::map after = arg_bool(args, "clear", false) ? std::map() : before; - for (const json& item : args.value("remove", json::array())) { - const int tick = item_tick(item); - if (after.erase(tick) == 0) - throw ToolFailure("No code on " + layer(tick) + " (" + listed(after) + ")"); - } - std::set added; - for (const json& item : args.value("add", json::array())) { - const int tick = item_tick(item); - const CustomGCode::Type type = custom_gcode_type_from_name(arg_string(item, "type")); - if (type == CustomGCode::Unknown) - throw ToolFailure("type must be pause, custom, template or change_filament"); - if (!added.insert(tick).second) - throw ToolFailure("Two codes for " + layer(tick)); - if (item.contains("filament") != (type == CustomGCode::ToolChange)) - throw ToolFailure(type == CustomGCode::ToolChange ? "change_filament needs filament" : "filament goes with type change_filament"); - if (item.contains("gcode") != (type == CustomGCode::Custom)) - throw ToolFailure(type == CustomGCode::Custom ? "custom needs gcode" : "gcode goes with type custom"); - TickCode code{tick, type}; - // The menus' rules: Add Custom Template only with a template, Change Filament only with two or more - // filaments and while the slider allows it, and the custom G-code dialog's buffer. - if (type == CustomGCode::Custom) { - code.extra = arg_string(item, "gcode"); - if (code.extra.empty() || code.extra.size() > 1023) - throw ToolFailure("gcode must be 1 to 1023 bytes, as the Custom G-code dialog takes"); - } else if (type == CustomGCode::Template && !has_template) { - throw ToolFailure("The printer's template_custom_gcode is empty; set it (settings_set type printer) or use type custom"); - } else if (type == CustomGCode::ToolChange) { - // The slider colours each filament change from the filaments of the slice. - const int slots = int(slider.GetExtruderColors().size()); - if (slots != filaments) - throw ToolFailure("The filaments changed since the plate was sliced; slice it again"); - if (slots < 2) - throw ToolFailure("change_filament needs two or more filaments; on a printer without a tool changer, add a filament " - "slot and turn on manual_filament_change"); - if (!no_filament_change.empty()) - throw ToolFailure("The plate takes no filament change: " + no_filament_change); - code.extruder = arg_int(item, "filament", 0); - if (code.extruder < 1 || code.extruder > slots) - throw ToolFailure("filament must be 1.." + std::to_string(slots)); - } - // One code per layer, as the slider's menus allow: on a layer with a code they only edit it. - if (const auto it = after.find(tick); it != after.end() && it->second.type != type) - throw ToolFailure(layer(tick) + " has a " + custom_gcode_type_name(it->second.type) + " code; remove it first (remove: [{layer: " + - std::to_string(tick + 1) + "}])"); - after[tick] = code; - } - - // Then the menus' own edits: Delete, Add, Edit Custom G-code and Change Filament on a filament change. - const auto same = [](const TickCode& a, const TickCode& b) { - return a.type == b.type && (a.type != CustomGCode::ToolChange || a.extruder == b.extruder) && - (a.type != CustomGCode::Custom || a.extra == b.extra); - }; - const auto edited_in_place = [](const TickCode& from, const TickCode& to) { - return from.type == to.type && (to.type == CustomGCode::Custom || to.type == CustomGCode::ToolChange); - }; - bool changed = false; - // The plater invalidates the plate's slice on the type of the last edit, which must not be a colour - // change's when other codes changed too. - CustomGCode::Type event = CustomGCode::Unknown; - for (const auto& [tick, code] : before) { - const auto it = after.find(tick); - if (it == after.end() || (!same(code, it->second) && !edited_in_place(code, it->second))) { - slider.delete_tick(code); - changed = true; - if (code.type != CustomGCode::ColorChange) - event = code.type; - } - } - for (const auto& [tick, code] : after) { - if (const auto it = before.find(tick); it != before.end() && same(it->second, code)) - continue; - if (code.type == CustomGCode::Custom) - slider.add_custom_gcode(code.extra, tick); - else if (!slider.add_code_as_tick(code.type, code.type == CustomGCode::ToolChange ? code.extruder : -1, tick)) - throw ToolFailure(std::string("The layer slider refused the ") + custom_gcode_type_name(code.type) + " on " + layer(tick) + - (changed ? "; the codes before it changed (plate_list lists them)" : "")); - changed = true; - event = code.type; - } - if (changed && event != CustomGCode::Unknown) - slider.post_ticks_changed_event(event); - return changed; -} - -void register_layer_tools(CommandCatalog& catalog) -{ - const json range = object_schema({{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}}, - {"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}}, - {"min_z", "max_z"}); - - catalog.add(with_target_ids(mutate_tool( - "object_set_height_ranges", L("Set height range modifiers"), - "Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed " - "with its own `layer_height`, filament and process settings, which `settings_get` and `settings_set` read and write with " - "the target `height_range`. A range given with the `min_z` and `max_z` of one the object has keeps its settings; a new " - "one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. " - "The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. " - "Reply: the object (objects, object), its height and its ranges as `object_list` shows them, with their settings, and " - "warnings, such as a variable layer height profile deciding the layer heights instead.", - with_targets(object_schema({{"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, {"ranges"}), kObjects, true), - [](const json& args, ToolContext& ctx) { - json out = ctx.run_ui([&] { return set_height_ranges(ui_plater(), args); }); - settle(ctx); - return ToolResult::ok(out); - }))); - - catalog.add(with_target_ids(mutate_tool( - "object_set_variable_layer_height", L("Set a variable layer height profile"), - "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive " - "computes layer heights from the object's shape (inside a height range, the range's `layer_height`), smooth smooths " - "its profile (or the one its height ranges give), reset goes back to its layer height and ranges. The object is " - "the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the " - "object (objects, object), its height, its `layer_height_profile {points, min_height, max_height}` as `object_list` " - "shows it (absent after reset), and warnings.", - with_targets(object_schema({{"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")}, - {"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1}, - {"description", "`adaptive`: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}}, - {"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}}, - {"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}}, - {"action"}), - kObjects, true), - [](const json& args, ToolContext& ctx) { - // Refused calls leave the view alone. The Prepare canvas edits layer heights only once it has drawn: - // GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home. The object is read once, - // before the wait, and named in the call that follows it. - json call = args; - ctx.run_ui([&] { - Plater& plater = ui_plater(); - call["object"] = profile_object(plater, args); - require_prepare_scene(plater); - return json(); - }); - poll_ui( - ctx, - []() -> json { - const GLCanvas3D* canvas = ui_plater().canvas3D(); - return canvas->is_initialized() && !canvas->is_reload_delayed() ? json(true) : json(); - }, - std::chrono::seconds(15), "the Prepare view to draw"); - json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), call); }); - settle(ctx); - return ToolResult::ok(out); - }))); - - const json layer = {{"type", "integer"}, {"minimum", 1}, {"description", "1-based, as the Preview's layer slider numbers layers."}}; - const json z = {{"type", "number"}, {"minimum", 0}, {"description", "mm: the layer whose top is at or above it."}}; - catalog.add(mutate_tool( - "plate_set_custom_gcode", L("Set custom G-code at a layer"), - "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview " - "layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the " - "plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects " - "it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding " - "where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not " - "undoable, as in the slider. A change invalidates the " - "plate's slice: slice again before exporting. Reply: the plate's codes as `plate_list`'s `layer_gcode` lists them, " - "each with z and layer.", - object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Default: the current plate."}}}, - {"add", array_prop(object_schema({{"layer", layer}, - {"z", z}, - {"type", enum_prop({"pause", "custom", "template", "change_filament"}, - "template runs the printer's `template_custom_gcode`.")}, - {"filament", {{"type", "integer"}, {"minimum", 1}, {"description", "`change_filament`: printed from this layer up."}}}, - {"gcode", prop("string", "custom: the G-code.")}}, - {"type"}), - "Codes to add, each with layer or z.")}, - {"remove", array_prop(object_schema({{"layer", layer}, {"z", z}}), "Codes to remove, by layer or z.")}, - {"clear", prop("boolean", "Remove every code on the plate first.")}}), - [](const json& args, ToolContext& ctx) { - // A setting changed just before is applied by an update scheduled a moment later, which may - // invalidate the plate. - poll_ui( - ctx, []() -> json { return ui_plater().is_background_process_update_scheduled() ? json() : json(true); }, - std::chrono::seconds(10), "the pending update of the slicing state"); - const int plate = ctx.run_ui([&] { return json(show_plate_layers(ui_plater(), args)); }).get(); - // A replay edits the same plate, whichever is current then. - json recorded = args; - recorded["plate"] = plate; - ctx.set_journal_args(std::move(recorded)); - // The Preview loads the plate's G-code at its first frame when it shows for the first time. - poll_ui( - ctx, - [plate]() -> json { - Plater& plater = ui_plater(); - return preview_shows_plate(plater, plate) && !plater.is_slicing_any() ? json(true) : json(); - }, - std::chrono::seconds(15), "the Preview to show plate " + std::to_string(plate) + "'s layers"); - CustomGCode::Info handed_over; - json out = ctx.run_ui([&] { return set_custom_gcode_at_layer(ui_plater(), plate, args, handed_over); }); - if (!out.is_null()) - return ToolResult::ok(out); - // The plater's handler writes the codes into the plate as the event arrives. - return ToolResult::ok(poll_ui( - ctx, - [&]() -> json { - Plater& plater = ui_plater(); - const Model& model = plater.model(); - const auto codes = model.plates_custom_gcodes.find(plate); - return codes != model.plates_custom_gcodes.end() && codes->second == handed_over ? layer_gcode_reply(plater, plate, true, args) : json(); - }, - std::chrono::seconds(5), "the layer slider's codes to reach the project")); - })); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp b/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp deleted file mode 100644 index e720482960..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsPreferences.cpp +++ /dev/null @@ -1,238 +0,0 @@ -// preferences_get and preferences_set: the app's preferences as the Preferences dialog shows them, read from and -// written through the table of GUI/Operations/PreferenceOps.hpp, which the dialog builds its rows from too. - -#include "McpTools.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PreferenceOps.hpp" - -#include "libslic3r/AppConfig.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; - -namespace { - -const char* kind_name(Ops::PreferenceKind kind) -{ - switch (kind) { - case Ops::PreferenceKind::Checkbox: return "checkbox"; - case Ops::PreferenceKind::Choice: return "choice"; - case Ops::PreferenceKind::Number: return "number"; - case Ops::PreferenceKind::Text: return "text"; - } - return "text"; -} - -// A bound of a number's range, whole where the row takes whole numbers. -json bound(const Ops::Preference& p, double value) -{ - if (p.decimals == 0) - return std::int64_t(value); - return value; -} - -// What a call learns of `p`'s refusal to be written: its reason, in English. -std::string refused_reason(const Ops::Preference& p) -{ - return Ops::Refusal{Ops::RefusalKind::Precondition, "preference_refused", p.refused, {p.key}}.english(); -} - -// preferences_get's item for `p`: its row, and the value the dialog shows: `shown` where the dialog shows a value of its -// own (Ops::shown_texts()), else the stored one, else the fallback. -json preference_item(const AppConfig& config, const Ops::Preference& p, const std::map& shown) -{ - std::string stored; - const bool is_stored = config.get("app", p.key, stored); - const auto own = shown.find(p.key); - const std::string text = own != shown.end() ? own->second : is_stored ? stored : p.fallback; - json item{{"key", p.key}, {"tab", p.tab}, {"section", p.section}, - {"label", p.label}, {"kind", kind_name(p.kind)}, - {"value", Ops::preference_value(p, text)}}; - if (!p.choices.empty()) { - json choices = json::array(); - for (const auto& [value, label] : p.choices) - choices.push_back({{"value", value}, {"label", label}}); - item["choices"] = std::move(choices); - } - if (p.min) - item["min"] = bound(p, *p.min); - if (p.max) - item["max"] = bound(p, *p.max); - if (!is_stored) - item["stored"] = false; - if (p.restart_needed) - item["restart_needed"] = true; - if (p.refused != nullptr) - item["refused"] = refused_reason(p); - return item; -} - -// What preferences_set replies when the operation refuses: the names the refusal carries under the key that says what -// they are, and where a refused preference changes instead. -ToolFailure preferences_refused(const Ops::Refusal& refusal, const std::vector& table) -{ - const std::string code = refusal.code; - if (code == "not_a_preference") - return refused(refusal, "preferences_get lists the Preferences dialog's preferences.", "similar"); - if (code == "no_such_choice") - return refused(refusal, "", "choices"); - if (code == "out_of_range") - return refused(refusal, "", "range"); - if (code == "preference_refused" && !refusal.args.empty()) - if (const Ops::Preference* p = Ops::find_preference(table, refusal.args.front())) - return refused(refusal, "It changes in the Preferences dialog: window_open {\"window\": \"preferences\", \"tab\": \"" + p->tab + - "\", \"key\": \"" + p->key + "\"}, then widget_set_value on the control named " + p->key + - " within Preferences.", - "keys"); - return refused(refusal); -} - -// preferences_set's reply: each preference changed, with its value before and after, typed as preferences_get gives it, -// stored_before: false where `before` is the fallback, restart_needed where the value is read at the next start; and -// those already so. -json changes_json(const Ops::PreferenceChanges& changes, const std::vector& table) -{ - json changed = json::array(); - for (const Ops::PreferenceChange& c : changes.changed) { - const Ops::Preference& p = *Ops::find_preference(table, c.key); - json item{{"key", c.key}, {"before", Ops::preference_value(p, c.before)}, {"after", Ops::preference_value(p, c.after)}}; - if (!c.stored_before) - item["stored_before"] = false; - if (p.restart_needed) - item["restart_needed"] = true; - changed.push_back(std::move(item)); - } - return {{"changed", std::move(changed)}, {"unchanged", changes.unchanged}}; -} - -} // namespace - -json preferences_settings(const AppConfig& config, const std::vector& shown, const json& args, - const std::map& shown_texts) -{ - const std::string tab = arg_string(args, "tab"); - std::vector asked; - if (args.contains("keys")) - for (const json& key : args["keys"]) - asked.push_back(key.get()); - const auto named = [&asked](const std::string& key) { return std::find(asked.begin(), asked.end(), key) != asked.end(); }; - const auto matches = [&](const Ops::Preference& p) { - return (tab.empty() || p.tab == tab) && (!args.contains("keys") || named(p.key)); - }; - - json items = json::array(), unknown = json::array(); - for (const Ops::Preference& p : shown) - if (matches(p)) - items.push_back(preference_item(config, p, shown_texts)); - // A named key the dialog does not show is read as the app configuration stores it. - for (const std::string& key : asked) { - if (Ops::find_preference(shown, key) != nullptr) - continue; - std::string value; - if (config.get("app", key, value)) - items.push_back({{"key", key}, {"value", value}}); - else - unknown.push_back(key); - } - json out{{"total", items.size()}, {"items", std::move(items)}}; - if (!unknown.empty()) { - out["unknown_keys"] = std::move(unknown); - // Some preferences are stored only once they are changed. - out["note"] = "unknown_keys are not stored and are no preference the Preferences dialog shows now."; - } - return out; -} - -void register_preference_tools(CommandCatalog& catalog) -{ - catalog.add(inspect_tool( - "preferences_get", L("Read preferences"), - "Read the app's preferences as the Preferences dialog shows them. With no argument, every preference it shows, " - "tab by tab in its order, each with key (its control is named after it), tab, section and label (the row's title, " - "in English), kind (checkbox, choice, number or text), value (what the dialog shows: `true` or `false` for a checkbox, " - "a number for a number field), a choice's choices (`{value, label}`; `preferences_set` takes the value), a number's " - "min and max, `stored: false` where nothing is stored and the value is the one the dialog shows then, " - "`restart_needed: true` for a preference read at the next start, which a write changes nothing before, and " - "refused, the reason, for a preference `preferences_set` does not write. The MCP server's switch and port read as " - "the dialog shows them: on while the server runs, and the port it is on, also where this session's launch " - "arguments set them without storing them; their stored says whether a value is stored. keys and tab narrow " - "the list together; a " - "named key the dialog does not show is read as the app configuration stores it (`{key, value}`), and one that is " - "neither is listed under `unknown_keys`. The app configuration also holds account and device state, which is read " - "only by name.", - object_schema({{"keys", array_prop({{"type", "string"}}, "Preference keys, e.g. [\"project_load_behaviour\"].")}, - {"tab", enum_prop({"general", "files", "behaviour", "control", "graphics", "online", "developer"}, - "The dialog's tab, as `window_open` names it.")}}), - [](const json& args, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([&] { - ui_plater(); - return preferences_settings(*wxGetApp().app_config, Ops::shown_preferences(), args, Ops::shown_texts()); - })); - })); - - NativeCommand write = reaching( - {"set_preferences"}, - mutate_tool( - "preferences_set", L("Change preferences"), - "Change preferences as their controls in the Preferences dialog do: values `{key: value}`, a checkbox as true or " - "false, a choice as one of its values, a number within its range, as `preferences_get` lists them, and the " - "downloads folder (`download_path`) as the absolute path of an existing folder. All are checked first and written " - "together, so nothing changes if one is refused; then each does what its control does in the app, in the keys' " - "order (the preview redrawn, the sidebar's lists, the settings' mode, the theme, preset sync started or " - "stopped, stealth mode's sign-out of the cloud accounts), and those `preferences_get` marks `restart_needed` are " - "stored and take effect at the next start. A key whose value is already the one given is left as it is. " - "Refused, by name and with the reason: a key the dialog does not show, and those `preferences_get` marks " - "refused, whose control opens a dialog, restarts OrcaSlicer, signs out, or reaches outside it (the language, " - "the login region, the network plug-in, file associations, the mixed-temperature warning, the MCP server's " - "switch and port); those change in the dialog: `window_open {\"window\": \"preferences\", \"tab\", " - "\"key\"}`, then `widget_set_value`. Not in the undo history. Reply: changed, [`{key, before, after}`] typed as " - "`preferences_get` gives them, with `stored_before: false` where nothing was stored and before is the value the " - "dialog showed, and `restart_needed: true` where `preferences_get` gives it; and unchanged, the keys already so.", - object_schema({{"values", {{"type", "object"}, - {"description", "`{key: value}`, e.g. `{\"auto_arrange\": false, \"auto_calculate_flush\": " - "\"color change\"}`."}}}}, - {"values"}), - [](const json& args, ToolContext& ctx) { - const json values = args.value("values", json::object()); - if (values.empty()) - throw ToolFailure("values names no preference: give {key: value}, e.g. {\"auto_arrange\": false}"); - std::map asked; - for (const auto& [key, value] : values.items()) - asked[key] = value; - json result = ctx.run_ui([&]() -> json { - ui_plater(); - const std::vector table = Ops::shown_preferences(); - const Ops::Outcome done = Ops::set_preferences(asked); - if (!done) - throw preferences_refused(done.refusal(), table); - return changes_json(done.value(), table); - }); - settle(ctx); - return ToolResult::ok(result); - })); - write.examples = json::parse(R"json([ - {"title": "Read the Behaviour tab's preferences and turn one off", "calls": [ - {"tool": "preferences_get", "args": {"tab": "behaviour"}}, - {"tool": "preferences_set", "args": {"values": {"auto_arrange": false}}}]}, - {"title": "Set a choice and a number", "calls": [ - {"tool": "preferences_set", "args": {"values": {"auto_calculate_flush": "color change", "opengl_fps_cap": 60}}}]}])json"); - catalog.add(std::move(write)); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPrinter.cpp b/src/slic3r/GUI/Mcp/McpToolsPrinter.cpp deleted file mode 100644 index e0aee0e168..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsPrinter.cpp +++ /dev/null @@ -1,230 +0,0 @@ -// The printing commands: print_start and printer_send open the dialog the Print button's Print and Send open for the -// selected printer, and printer_test_host asks the printer's print host whether it answers, as the Test button of its -// connection dialog does. What is printed or sent is left to the dialog, which a client answers with the dialog tools. -// printer_status reads what the Device tab shows of the printer it is connected to, and print_pause, print_resume and -// print_stop send that printer the tab's job commands. - -#include "McpTools.hpp" - -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/NativeCommandMenuItems.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PrinterOps.hpp" - -#include - -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; - -namespace { - -json temperature(const Ops::Temperature& t) -{ - return {{"current", t.current ? json(*t.current) : json()}, {"target", t.target ? json(*t.target) : json()}}; -} - -// print_pause, print_resume or print_stop: `command` sent to the connected printer. -NativeCommand job_command(const char* name, const char* title, Ops::JobCommand command, const std::string& description, - const char* examples, bool destructive) -{ - NativeCommand job = mutate_tool( - name, title, - description + " The printer's new state arrives when it reports: read it with `printer_status`. Reply: printer (its " - "name), state (the state it was in) and sent. A replay sends the command again.", - object_schema({}), - [command](const json&, ToolContext& ctx) { - json reply = ctx.run_ui([command] { - const Ops::Outcome sent = Ops::send_job_command(Ops::connected_printer(), command); - if (!sent) - throw refused(sent.refusal()); - return json{{"printer", sent.value().printer}, {"state", sent.value().state}, {"sent", true}}; - }); - return ToolResult::ok(std::move(reply)); - }, - destructive); - // It sends the printer a command. - job.open_world = true; - job.examples = json::parse(examples); - return reaching({"send_job_command"}, std::move(job)); -} - -json plates_prop(const char* all) -{ - return {{"type", {"string", "integer"}}, - {"description", std::string("\"current\" (default), a plate index, which is selected first, or \"all\" for ") + all + - ", where the Print button offers it."}}; -} - -} // namespace - -json printer_status_reply(const std::optional& status) -{ - if (!status) - return {{"connected", false}}; - json nozzles = json::array(); - for (const Ops::Temperature& nozzle : status->nozzles) - nozzles.push_back(temperature(nozzle)); - return {{"connected", true}, - {"name", status->name}, - {"model", status->model.empty() ? json() : json(status->model)}, - {"printer_type", status->printer_type}, - {"online", status->online}, - {"state", status->state}, - {"stage", status->stage}, - {"percent", status->percent}, - {"remaining_seconds", status->remaining_seconds}, - {"layer", status->layer}, - {"total_layers", status->total_layers}, - {"file", status->file}, - {"error_code", status->error_code}, - {"temperatures", - {{"nozzles", std::move(nozzles)}, {"bed", temperature(status->bed)}, {"chamber", temperature(status->chamber)}}}}; -} - -std::string read_print_plates(const json& args, std::optional& plate, bool& all) -{ - plate.reset(); - all = false; - if (!args.contains("plates")) - return {}; - const json& plates = args.at("plates"); - if (plates.is_number_integer()) { - plate = plates.get(); - return {}; - } - if (plates.is_string() && plates.get() == "all") - all = true; - else if (!plates.is_string() || plates.get() != "current") - return "plates is \"current\", \"all\" or a plate index"; - return {}; -} - -void register_printer_tools(CommandCatalog& catalog) -{ - NativeCommand print = mutate_tool( - "print_start", L("Print plate"), - "Open the dialog the Print button's Print plate opens for the selected printer, for the current plate or the plate " - "plates names, or with plates \"all\" Print all's. For a printer on the Bambu network or with printer agents it is the " - "Print dialog, which leaves the printer, bed levelling, flow calibration, timelapse, the AMS mapping and the button " - "that prints to it; for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...) it is the host's Send " - "G-code to printer host dialog, with Upload and Upload and Print. As the button does, it first applies the slicing " - "result, and it is refused (`not_sliced`) where the button would be disabled, as for a plate not sliced: slice with " - "`plate_slice` first. The call replies `blocked_by_dialog` while the dialog is open: read and set its fields with " - "`widget_list` and `widget_set_value`, and press its buttons with `dialog_answer`. Nothing prints until its button is " - "pressed. Refused: `all_plates_not_offered` for plates \"all\" where the button offers no Print all, `no_print_host` for " - "a printer with no print host address.", - object_schema({{"plates", plates_prop("Print all")}}), [](const json& args, ToolContext& ctx) { - Ops::OpenPrintDialogArgs op; - if (const std::string err = read_print_plates(args, op.plate, op.all); !err.empty()) - throw ToolFailure(err); - ctx.run_ui([&] { - if (const Ops::Outcome opened = Ops::open_print_dialog(op); !opened) - throw refused(opened.refusal()); - return json(); - }); - settle(ctx); - return ToolResult::ok(); - }); - // Its dialog prints on a printer. - print.open_world = true; - print.examples = json::parse(R"json([ - {"title": "Open the Print dialog for the current plate", "calls": [{"tool": "print_start", "args": {}}]}, - {"title": "Print the second plate after slicing it", "calls": [ - {"tool": "plate_slice", "args": {"plates": 1}}, {"tool": "print_start", "args": {"plates": 1}}]}])json"); - catalog.add(reaching({"open_print_dialog"}, std::move(print))); - - const std::string send = - "Open the dialog the Print button's Send opens for the selected printer, for the current plate or the plate plates " - "names. For a printer on the Bambu network or with printer agents it is the dialog that sends the sliced plate to the " - "printer's storage (with plates \"all\", Send all's), which leaves the printer, the file name, the storage and the " - "button that sends to it, and is refused (`not_sliced`) for a plate not sliced. For a printer with a print host " - "(OctoPrint, Moonraker, PrusaLink, Duet...) it is the Send G-code to printer host dialog: set the file name with " - "`widget_set_value` and press Upload or Upload and Print with `dialog_answer`; the plate is sliced if needed, then " - "uploaded in the background: `app_state.uploads` shows the row's state, and a failed upload also opens an error " - "dialog. The call replies `blocked_by_dialog` while the dialog is open. A replay sends again. Refused: " - "`all_plates_not_offered` for plates \"all\" where the button offers no Send all, `no_print_host` for a printer with no " - "print host address."; - const json send_action = NativeCommands::action("send_gcode", L("Send G-code to printer host"), L("Slice & Export"), "printer", - json::object(), send); - NativeCommand printer_send = reaching({"open_print_dialog"}, - menu_command("printer_send", L("Send G-code to printer host"), send, - object_schema({{"plates", plates_prop("Send all")}}), json::array({send_action}), - [](const json& args) { return MenuItems::send_gcode(args); })); - // It uploads to the printer's print host, or sends to the printer. - printer_send.open_world = true; - catalog.add(std::move(printer_send)); - - NativeCommand test_host = mutate_tool( - "printer_test_host", L("Test the print host"), - "Ask the selected printer's print host whether it answers, as the Test button of the printer's connection dialog " - "does, with its connection settings as they stand. Reply: ok, whether the host answered, and message, the button's " - "message in the app's language; branch on ok. A cloud host that wants a login is a failed test with the host's " - "message: logging in stays in the printer's connection dialog. The window does not redraw while the host is asked. " - "Refused: `no_print_host` for a printer with no print host address, `host_cannot_be_tested` for a kind of host that has " - "no test.", - object_schema({}), [](const json&, ToolContext& ctx) { - json reply = ctx.run_ui([] { - const Ops::Outcome tested = Ops::test_print_host(); - if (!tested) - throw refused(tested.refusal()); - return json{{"ok", tested.value().ok}, {"message", tested.value().message}}; - }); - return ToolResult::ok(std::move(reply)); - }); - // It asks the host over the network. - test_host.open_world = true; - test_host.examples = json::parse(R"json([ - {"title": "Check the print host after setting its address", "calls": [ - {"tool": "settings_set", "args": {"type": "printer", "values": {"host_type": "octoprint", "print_host": "192.168.1.20"}}}, - {"tool": "printer_test_host", "args": {}}]}])json"); - catalog.add(reaching({"test_print_host"}, std::move(test_host))); - - NativeCommand status = inspect_tool( - "printer_status", L("Printer status"), - "Read what the Device tab shows of the printer it is connected to, without sending it anything. Reply: connected; " - "with a printer, name, model (null where the tab would say Unknown), `printer_type` (the model's id), online, state " - "(IDLE, PREPARE, RUNNING, PAUSE, FINISH, FAILED...), stage (a number), percent, `remaining_seconds`, layer, " - "`total_layers`, file (the job's name), `error_code`, and temperatures: nozzles (one `{current, target}` each), bed and " - "chamber, null where the tab shows none. With no printer connected the reply is `{\"connected\": false}`, which is no " - "error. The values are what the printer last reported.", - object_schema({}), [](const json&, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([] { return printer_status_reply(Ops::printer_status(Ops::connected_printer())); })); - }); - status.examples = json::parse(R"json([ - {"title": "Read the connected printer's state and temperatures", "calls": [{"tool": "printer_status", "args": {}}]}])json"); - catalog.add(std::move(status)); - - catalog.add(job_command( - "print_pause", L("Pause the print"), Ops::JobCommand::Pause, - "Pause the print running on the printer the Device tab is connected to, as the tab's Pause button does. Refused: " - "`no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is RUNNING.", - R"json([{"title": "Pause the print once printer_status reads RUNNING", "calls": [ - {"tool": "printer_status", "args": {}}, {"tool": "print_pause", "args": {}}]}])json", - false)); - catalog.add(job_command( - "print_resume", L("Resume the print"), Ops::JobCommand::Resume, - "Resume the paused print on the printer the Device tab is connected to, as the tab's Resume button does. Refused: " - "`no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is PAUSE, and " - "`resume_at_printer`, in the app's own sentence, for a job (such as laser processing) that resumes only at the printer.", - R"json([{"title": "Resume the print once printer_status reads PAUSE", "calls": [ - {"tool": "printer_status", "args": {}}, {"tool": "print_resume", "args": {}}]}])json", - false)); - catalog.add(job_command( - "print_stop", L("Stop the print"), Ops::JobCommand::Stop, - "Stop the print on the printer the Device tab is connected to, as the tab's Stop button does, but without its " - "question \"Are you sure you want to stop this print?\": it asks nothing, and a stopped print cannot be resumed. " - "Refused: `no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is RUNNING, " - "PAUSE, PREPARE or SLICING.", - R"json([{"title": "Stop the print", "calls": [{"tool": "print_stop", "args": {}}]}])json", - true)); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsProject.cpp b/src/slic3r/GUI/Mcp/McpToolsProject.cpp deleted file mode 100644 index 076110ec0d..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsProject.cpp +++ /dev/null @@ -1,1030 +0,0 @@ -// project_new, project_open, project_import, project_save and project_export: the project's files in and out without -// file dialogs, and called as their menu items' actions, with them. calibration_generate_test: the Calibration menu's -// tests, which start a new project. - -#include "slic3r/GUI/I18N.hpp" -#include "JobRegistry.hpp" -#include "McpPaths.hpp" -#include "AutomationRuntime.hpp" -#include "McpTargets.hpp" -#include "McpTools.hpp" -#include "slic3r/GUI/ActionRegistry.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GUI.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/MainFrame.hpp" -#include "slic3r/GUI/NativeCommandMenuItems.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Operations/ExportOps.hpp" -#include "slic3r/GUI/Operations/ObjectOps.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PlateOps.hpp" -#include "slic3r/GUI/Operations/ProjectOps.hpp" -#include "slic3r/GUI/PartPlate.hpp" -#include "slic3r/GUI/Plater.hpp" -#include "slic3r/GUI/calib_dlg.hpp" - -#include "libslic3r/Config.hpp" -#include "libslic3r/Model.hpp" -#include "libslic3r/Preset.hpp" -#include "libslic3r/PresetBundle.hpp" -#include "libslic3r/PrintConfig.hpp" -#include "libslic3r/calib.hpp" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; -namespace fs = boost::filesystem; - -namespace { - -bool has_extension(const fs::path& p, std::initializer_list exts) -{ - const std::string name = path_to_utf8(p.filename()); - for (const char* e : exts) - if (boost::algorithm::iends_with(name, e)) - return true; - return false; -} - -json objects_summary(Plater& plater) -{ - json names = json::array(); - for (const ModelObject* o : plater.model().objects) - names.push_back(o->name); - return {{"objects", plater.model().objects.size()}, {"names", std::move(names)}, {"plates", plater.get_partplate_list().get_plate_count()}}; -} - -json project_json(const Ops::ProjectSummary& project) -{ - return {{"objects", project.object_names.size()}, {"names", project.object_names}, {"plates", project.plates}}; -} - -Ops::UnsavedChanges unsaved_changes_answer(bool discard) { return discard ? Ops::UnsavedChanges::Discard : Ops::UnsavedChanges::Refuse; } - -// What a tool that replaces the project adds to the refusal of unsaved changes. -constexpr const char* kUnsavedChangesHint = "project_save first, or pass discard_changes: true."; - -// Fails when the project has unsaved changes the caller did not say to drop. -void require_project_discardable(bool discard) -{ - if (const std::optional refusal = Ops::unsaved_changes_refusal(unsaved_changes_answer(discard))) - throw refused(*refusal, kUnsavedChangesHint); -} - -// A number for a message, as an agent writes it: 250, not 250.0. -std::string num(double v) { return v == std::floor(v) && std::abs(v) < 1e15 ? std::to_string((long long) v) : json(v).dump(); } - -bool is_rrf(const DynamicPrintConfig& printer) -{ - const auto* flavor = printer.option>("gcode_flavor"); - return flavor != nullptr && flavor->value == GCodeFlavor::gcfRepRapFirmware; -} - -bool is_belt(const DynamicPrintConfig& printer) -{ - const auto* belt = printer.option("belt_printer"); - return belt != nullptr && belt->value; -} - -// calibration_generate_test's test_model values, as each test's dialog lists its models. -std::vector calib_test_models(CalibMode mode) -{ - switch (mode) { - case CalibMode::Calib_Temp_Tower: return {"standard", "overhang"}; - case CalibMode::Calib_Input_shaping_freq: - case CalibMode::Calib_Input_shaping_damp: return {"ringing_tower", "fast_tower"}; - case CalibMode::Calib_Cornering: return {"ringing_tower", "fast_tower", "scv_v2"}; - default: return {}; - } -} - -// The rule of the test's dialog that `p` breaks, stated with the values given. -std::string calib_rule(CalibParamsError error, const Calib_Params& p, const DynamicPrintConfig& printer) -{ - const std::string range = "got start " + num(p.start) + ", end " + num(p.end) + ", step " + num(p.step); - switch (error) { - case CalibParamsError::BeltMethod: return "PA line and pattern tests are not enabled on belt printers; use method tower"; - case CalibParamsError::AccelBelowSpeed: return "every acceleration must be greater than every speed (they look swapped)"; - case CalibParamsError::Damping: - if (p.mode == CalibMode::Calib_Input_shaping_freq) - return "damping must be at least 0 and below 1; got " + num(p.start); - return "input_shaping_damp needs 0 <= start < end <= 1; got start " + num(p.start) + ", end " + num(p.end); - default: break; - } - switch (p.mode) { - case CalibMode::Calib_Temp_Tower: - return "temperature needs start at least end + 5 °C; got start " + num(p.start) + ", end " + num(p.end); - case CalibMode::Calib_Vol_speed_Tower: return "max_volumetric needs start > 0, step > 0 and end >= start + step; " + range; - case CalibMode::Calib_Retraction_tower: return "retraction needs start >= 0, step > 0 and end >= start + step; " + range; - case CalibMode::Calib_VFA_Tower: return "vfa needs start > 10, step > 0 and end >= start + step; " + range; - case CalibMode::Calib_Input_shaping_freq: - return "input_shaping_freq needs 0 <= start < end <= 500 Hz" + std::string(is_rrf(printer) ? "" : ", and so do start_y and end_y") + - "; got " + num(p.freqStartX) + "-" + num(p.freqEndX) + (is_rrf(printer) ? "" : ", Y " + num(p.freqStartY) + "-" + num(p.freqEndY)); - case CalibMode::Calib_Input_shaping_damp: - return "input_shaping_damp needs freq_x and freq_y within 0-500 Hz; got " + num(p.freqStartX) + ", " + num(p.freqStartY); - case CalibMode::Calib_Cornering: { - const bool jd = has_junction_deviation(printer); - return "cornering needs 0 <= start < end <= " + num(cornering_end_limits(printer).first) + - (jd ? " mm (junction deviation)" : " mm/s (jerk)") + "; got start " + num(p.start) + ", end " + num(p.end); - } - default: return "pressure_advance needs start >= 0, step >= 0.001 and end >= start + step; " + range; - } -} - -// Where a test's measured value belongs, from the wiki's calibration pages. -json calib_result_keys(CalibMode mode, const DynamicPrintConfig& printer) -{ - switch (mode) { - case CalibMode::Calib_Temp_Tower: return {{"type", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}}; - case CalibMode::Calib_Vol_speed_Tower: return {{"type", "filament"}, {"keys", {"filament_max_volumetric_speed"}}}; - case CalibMode::Calib_PA_Tower: - case CalibMode::Calib_PA_Line: return {{"type", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}}; - case CalibMode::Calib_PA_Pattern: - return {{"type", "filament"}, - {"keys", {"enable_pressure_advance", "pressure_advance", "adaptive_pressure_advance", "adaptive_pressure_advance_model"}}}; - case CalibMode::Calib_Flow_Rate: return {{"type", "filament"}, {"keys", {"filament_flow_ratio"}}}; - case CalibMode::Calib_Retraction_tower: return {{"type", "filament"}, {"keys", {"filament_retraction_length"}}}; - case CalibMode::Calib_VFA_Tower: - return {{"type", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}}; - case CalibMode::Calib_Cornering: - return {{"type", "printer"}, - {"keys", has_junction_deviation(printer) ? json{"machine_max_junction_deviation"} : json{"machine_max_jerk_x", "machine_max_jerk_y"}}}; - default: - return {{"type", "printer"}, - {"keys", {"input_shaping_emit", "input_shaping_type", "input_shaping_freq_x", "input_shaping_freq_y", "input_shaping_damp_x", - "input_shaping_damp_y"}}}; - } -} - -// What VFA's auto-adjust does to `params`, as the dialog's answer Yes would: {layer_height, end, reason} when it -// changed them; a warning when the upper blocks are left above the filament's limit. -json apply_vfa_fit(Calib_Params& params, bool auto_adjust, const PresetBundle& bundle, std::vector& warnings) -{ - const DynamicPrintConfig& printer = bundle.printers.get_edited_preset().config; - const VfaSpeedFit fit = fit_vfa_speed(params, printer, bundle.prints.get_edited_preset().config, bundle.filaments.get_edited_preset().config, - auto_adjust, vfa_candidate_layer_heights(bundle.prints, printer, params.extruder_id)); - const std::string over = "the end speed (" + num(params.end) + " mm/s) exceeds the filament's maximum volumetric speed (" + - num(fit.max_vol_speed) + " mm³/s)"; - switch (fit.kind) { - case VfaSpeedFit::ReducedLayerHeight: - params.vfa_layer_height = fit.layer_height; - return {{"layer_height", fit.layer_height}, - {"reason", over + " at the default layer height (" + num(fit.default_lh) + " mm); the layer height of a profile of this printer reaches it"}}; - case VfaSpeedFit::LoweredEnd: - params.vfa_layer_height = fit.layer_height; - params.end = fit.end; - return {{"layer_height", fit.layer_height}, - {"end", fit.end}, - {"reason", over + " even at the smallest layer height of this printer's profiles; the end speed was lowered to what it reaches"}}; - case VfaSpeedFit::Clamped: - warnings.push_back(over + ", which limits the outer wall to about " + std::to_string(std::lround(fit.speed_limit)) + - " mm/s: the blocks above print at that speed" + - (auto_adjust && params.nozzle_based_resize ? " (no compatible process profile to lower the layer height to)" : - " (auto_adjust and auto_scale lower the layer height to reach it)")); - return json(); - default: return json(); - } -} - -// project_export's format for a path given without one, from its extension. -std::string format_of(const std::string& path) -{ - static const std::pair formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"}, - {".stl", "stl"}, {".drc", "drc"}, {".obj", "toolpaths_obj"}}; - for (const auto& [ext, format] : formats) - if (boost::algorithm::iends_with(path, ext)) - return format; - throw ToolFailure("Give format (gcode, sliced_3mf, 3mf, stl, drc or toolpaths_obj), or a path ending in .gcode, .gcode.3mf, " - ".3mf, .stl, .drc or .obj"); -} - -} // namespace - -Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig& printer, std::vector& warnings) -{ - const std::string test = arg_string(args, "test"); - // The arguments each test takes, besides test, filament_slot, silent, discard_changes and preset_changes. - std::vector takes{"start", "end", "step"}; - CalibMode mode = CalibMode::Calib_None; - std::string method; - if (test == "temperature") { - mode = CalibMode::Calib_Temp_Tower; - takes = {"start", "end", "auto_scale", "test_model"}; - } else if (test == "max_volumetric") { - mode = CalibMode::Calib_Vol_speed_Tower; - } else if (test == "pressure_advance") { - method = arg_string(args, "method", "tower"); - mode = method == "tower" ? CalibMode::Calib_PA_Tower : method == "line" ? CalibMode::Calib_PA_Line : - method == "pattern" ? CalibMode::Calib_PA_Pattern : CalibMode::Calib_None; - if (mode == CalibMode::Calib_None) - throw ToolFailure("method of pressure_advance is tower, line or pattern"); - takes.push_back("method"); - if (mode == CalibMode::Calib_PA_Line) - takes.push_back("print_numbers"); - if (mode == CalibMode::Calib_PA_Pattern) - takes.insert(takes.end(), {"accelerations", "speeds"}); - } else if (test == "flow_ratio") { - method = arg_string(args, "method", "yolo"); - if (method != "pass1" && method != "pass2" && method != "yolo" && method != "yolo_perfectionist") - throw ToolFailure("method of flow_ratio is pass1, pass2, yolo or yolo_perfectionist"); - mode = CalibMode::Calib_Flow_Rate; - takes = {"method", "top_surface_pattern"}; - } else if (test == "retraction") { - mode = CalibMode::Calib_Retraction_tower; - } else if (test == "vfa") { - mode = CalibMode::Calib_VFA_Tower; - takes.insert(takes.end(), {"auto_scale", "auto_adjust"}); - } else if (test == "input_shaping_freq") { - mode = CalibMode::Calib_Input_shaping_freq; - takes = {"start", "end", "start_y", "end_y", "damping", "shaper_type", "test_model"}; - } else if (test == "input_shaping_damp") { - mode = CalibMode::Calib_Input_shaping_damp; - takes = {"freq_x", "freq_y", "start", "end", "shaper_type", "test_model"}; - } else if (test == "cornering") { - mode = CalibMode::Calib_Cornering; - takes = {"start", "end", "test_model"}; - } else { - throw ToolFailure("Unknown test \"" + test + "\""); - } - for (auto it = args.begin(); it != args.end(); ++it) - if (it.key() != "test" && it.key() != "filament_slot" && it.key() != "silent" && it.key() != "discard_changes" && - it.key() != "preset_changes" && std::find(takes.begin(), takes.end(), it.key()) == takes.end()) - throw ToolFailure(it.key() + " does not apply to " + test + (method.empty() ? "" : " with method " + method), {{"takes", takes}}); - - // The dialog's radio picks the Bowden defaults; here the printer's extruder type does. - const auto* extruder_type = printer.option("extruder_type"); - const bool bowden = extruder_type != nullptr && !extruder_type->values.empty() && extruder_type->values.front() == int(etBowden); - const bool rrf = is_rrf(printer); - Calib_Params p = calib_default_params(mode, printer, bowden); - if (mode == CalibMode::Calib_Input_shaping_freq) { - if (rrf && (args.contains("start_y") || args.contains("end_y"))) - throw ToolFailure("RepRapFirmware takes one frequency range for both axes; leave start_y and end_y out"); - p.freqStartX = arg_double(args, "start", p.freqStartX); - p.freqEndX = arg_double(args, "end", p.freqEndX); - p.freqStartY = arg_double(args, "start_y", p.freqStartX); - p.freqEndY = arg_double(args, "end_y", p.freqEndX); - p.start = arg_double(args, "damping", p.start); - } else if (mode == CalibMode::Calib_Input_shaping_damp) { - if (rrf && args.contains("freq_y")) - throw ToolFailure("RepRapFirmware takes one frequency for both axes; leave freq_y out"); - p.freqStartX = arg_double(args, "freq_x", p.freqStartX); - p.freqStartY = arg_double(args, "freq_y", p.freqStartX); - p.start = arg_double(args, "start", p.start); - p.end = arg_double(args, "end", p.end); - } else { - p.start = arg_double(args, "start", p.start); - p.end = arg_double(args, "end", p.end); - p.step = arg_double(args, "step", p.step); - } - - if (mode == CalibMode::Calib_Temp_Tower) { - // As the dialog's fields do when they lose focus: clamp, then round down to the tower's 5 °C blocks. - for (auto [name, t] : {std::make_pair("start", &p.start), std::make_pair("end", &p.end)}) { - const double given = *t; - if (const double clamped = clamp_calib_temp(*t); clamped != *t) { - *t = clamped; - warnings.push_back(std::string(name) + " " + num(given) + " °C is outside the supported range " + num(kCalibTempMin) + - "-" + num(kCalibTempMax) + " °C; clamped to " + num(*t) + " °C"); - } - if (const double rounded = round_calib_temp(*t); rounded != *t) { - warnings.push_back(std::string(name) + " " + num(*t) + " °C rounded down to " + num(rounded) + " °C, the tower's 5 °C blocks"); - *t = rounded; - } - } - } - p.nozzle_based_resize = arg_bool(args, "auto_scale", true); - if (mode == CalibMode::Calib_PA_Line) - p.print_numbers = arg_bool(args, "print_numbers", p.print_numbers); - if (mode == CalibMode::Calib_PA_Pattern) { - for (const json& a : args.value("accelerations", json::array())) - p.accelerations.push_back(a.get()); - for (const json& v : args.value("speeds", json::array())) - p.speeds.push_back(v.get()); - } - - if (const std::vector models = calib_test_models(mode); !models.empty()) { - const std::string model = arg_string(args, "test_model", models.front()); - const auto it = std::find(models.begin(), models.end(), model); - if (it == models.end()) - throw ToolFailure("test_model of " + test + " is " + boost::algorithm::join(models, ", ")); - p.test_model = int(it - models.begin()); - // The temperature dialog shows its model picker on belt printers only. - if (mode == CalibMode::Calib_Temp_Tower && args.contains("test_model") && !is_belt(printer)) - throw ToolFailure("test_model applies to the temperature test on belt printers only"); - if (mode == CalibMode::Calib_Temp_Tower && p.test_model == 1 && !boost::filesystem::exists(belt_temp_tower_asset(p))) - throw ToolFailure("No belt temperature tower model covers " + num(p.start) + " to " + num(p.end) + - " °C; use a range the tower models cover, for example 230 to 190"); - } - if (mode == CalibMode::Calib_Input_shaping_freq || mode == CalibMode::Calib_Input_shaping_damp) { - const std::vector types = shaper_type_values(printer); - p.shaper_type = arg_string(args, "shaper_type", types.front()); - if (std::find(types.begin(), types.end(), p.shaper_type) == types.end()) - throw ToolFailure("shaper_type " + p.shaper_type + " is not offered for " + - (printer.has("gcode_flavor") ? printer.opt_serialize("gcode_flavor") : std::string("this")) + - " firmware: " + boost::algorithm::join(types, ", ")); - } - - if (const CalibParamsError error = check_calib_params(p, printer); error != CalibParamsError::None) - throw ToolFailure(calib_rule(error, p, printer)); - if (mode == CalibMode::Calib_Cornering && p.end > cornering_end_limits(printer).second) - warnings.push_back("end " + num(p.end) + " is above " + num(cornering_end_limits(printer).second) + ": high values may cause layer shifts"); - return p; -} - -json calib_params_json(const json& args, const Calib_Params& p, const DynamicPrintConfig& printer) -{ - const bool rrf = is_rrf(printer); - json out; - switch (p.mode) { - case CalibMode::Calib_Temp_Tower: - out = {{"start", p.start}, {"end", p.end}, {"auto_scale", p.nozzle_based_resize}}; - if (is_belt(printer)) - out["test_model"] = calib_test_models(p.mode)[size_t(p.test_model)]; - break; - case CalibMode::Calib_PA_Tower: - case CalibMode::Calib_PA_Line: - case CalibMode::Calib_PA_Pattern: - out = {{"method", arg_string(args, "method", "tower")}, {"start", p.start}, {"end", p.end}, {"step", p.step}}; - if (p.mode == CalibMode::Calib_PA_Line) - out["print_numbers"] = p.print_numbers; - // Left out, the pattern's are taken from the process when it runs. - if (!p.accelerations.empty()) - out["accelerations"] = p.accelerations; - if (!p.speeds.empty()) - out["speeds"] = p.speeds; - break; - case CalibMode::Calib_Flow_Rate: - out = {{"method", arg_string(args, "method", "yolo")}, {"top_surface_pattern", arg_string(args, "top_surface_pattern", "archimedeanchords")}}; - break; - case CalibMode::Calib_VFA_Tower: - out = {{"start", p.start}, {"end", p.end}, {"step", p.step}, {"auto_scale", p.nozzle_based_resize}, {"auto_adjust", arg_bool(args, "auto_adjust", true)}}; - break; - case CalibMode::Calib_Input_shaping_freq: - out = {{"start", p.freqStartX}, {"end", p.freqEndX}}; - if (!rrf) - out.update({{"start_y", p.freqStartY}, {"end_y", p.freqEndY}}); - out.update({{"damping", p.start}, {"shaper_type", p.shaper_type}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}); - break; - case CalibMode::Calib_Input_shaping_damp: - out = {{"freq_x", p.freqStartX}}; - if (!rrf) - out["freq_y"] = p.freqStartY; - out.update({{"start", p.start}, {"end", p.end}, {"shaper_type", p.shaper_type}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}); - break; - case CalibMode::Calib_Cornering: - out = {{"start", p.start}, {"end", p.end}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}; - break; - default: out = {{"start", p.start}, {"end", p.end}, {"step", p.step}}; break; - } - return out; -} - -void register_project_tools(CommandCatalog& catalog) -{ - NativeCommand open = reaching({"open_project"}, mutate_tool( - "project_open", L("Open a project"), - "Open a project (.3mf) by absolute path, without a file dialog, replacing the current project, with the settings it " - "was saved with whatever the Preferences' Load behavior says; when the current project has unsaved changes that " - "fails, changing nothing, unless `discard_changes`. A G-code file replaces the project too, to show its toolpaths: " - "with unsaved changes the app asks first (`blocked_by_dialog`), whatever `discard_changes` says. `project_import` adds " - "models, or a project's objects alone, to the current project. Called with no arguments it is Load Project: the " - "Open dialog asks for the file (`blocked_by_dialog`), after asking about the unsaved changes. Reply: opened (project " - "or gcode), and objects, names and plates for a project, path for a G-code.", - object_schema({{"path", prop("string", "Absolute path of a .3mf project, or of a G-code file (.gcode, .bgcode).")}, - {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a project " - "replaces it.")}}, - {"path"}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - std::string err; - const auto path = resolve_input_path(arg_string(args, "path"), err); - if (!path) - throw ToolFailure(err); - const bool gcode = has_extension(*path, {".gcode", ".bgcode"}); - if (!gcode && !has_extension(*path, {".3mf"})) - throw ToolFailure("project_open opens a .3mf project or a G-code file; project_import adds models to the project"); - // A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes. - const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); - json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - if (gcode) { - plater.load_gcode(from_path(*path)); - return {{"opened", "gcode"}, {"path", path_to_utf8(*path)}}; - } - Ops::OpenProjectArgs open; - open.path = *path; - open.unsaved = unsaved_changes_answer(discard); - const Ops::Outcome opened = Ops::open_project(open); - if (!opened) - throw refused(opened.refusal(), kUnsavedChangesHint); - json o = project_json(opened.value()); - o["opened"] = "project"; - return o; - }); - settle(ctx); - return ToolResult::ok(out); - })); - open.actions = json::array({NativeCommands::action("load_project", L("Load Project"), L("Commands"), "menu_open", json::object(), - "Open a project through the Open dialog (it asks first if the current project " - "has unsaved changes); project_open with a path opens that file without a " - "dialog.")}); - catalog.add(NativeCommands::with_person_form(std::move(open), [](const json&) { return MenuItems::load_project(); })); - - NativeCommand import_ = reaching({"import_models"}, mutate_tool( - "project_import", L("Import models"), - "Add the models of files (STL, 3MF, STEP, OBJ, AMF, SVG...) to the current project by absolute path, without a file " - "dialog, as one undo step; a .3mf adds its objects only, not its settings (`project_open` opens it as a project). A " - ".zip archive gives the model files it holds (STL, OBJ, AMF, 3MF, STEP; a .3mf its objects only, as above), as Import " - "ZIP Archive does: those entries names, by their paths in the archive, else all of them, in place of its file list; " - "an entry the archive lacks is refused with the names it has, before anything is imported. Importing can open a " - "dialog (STEP mesh options, for instance); the reply is then `blocked_by_dialog`. Called with no arguments it is " - "Import 3MF/STL/STEP/SVG/OBJ/AMF, and with `archive: true` alone Import ZIP Archive: a file dialog asks for the files, " - "or for the archive and then which of its files to import (`blocked_by_dialog`). Reply: opened (models), added (how " - "many objects), archives (each archive's path and the entries taken) and the project's objects, names and plates.", - object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths of model files, or of a .zip archive of them.")}, - {"entries", {{"type", "array"}, - {"items", {{"type", "string"}}}, - {"minItems", 1}, - {"description", "The files to take from the one .zip archive among paths, by their paths " - "in it (\"parts/cube.stl\"). Default: every model file it holds."}}}, - {"archive", prop("boolean", "true, alone: ask for a ZIP archive in a file dialog and import the models " - "it holds, as Import ZIP Archive does.")}}, - {"paths"}), - [](const json& args, ToolContext& ctx) { - if (arg_bool(args, "archive", false)) - throw ToolFailure("archive asks for the archive in a file dialog, so it goes alone; paths imports files without one"); - if (args.contains("entries")) { - const json& given = args["paths"]; - const auto zips = std::count_if(given.begin(), given.end(), [](const json& p) { - return boost::algorithm::iends_with(p.get(), ".zip"); - }); - if (zips == 0) - throw ToolFailure("entries names files of a .zip archive: give the archive in paths"); - if (zips > 1) - throw ToolFailure("entries names the files of one archive: give one .zip in paths"); - } - std::vector paths; - for (const json& p : args["paths"]) { - std::string err; - auto resolved = resolve_input_path(p.get(), err); - if (!resolved) - throw ToolFailure(err); - if (has_extension(*resolved, {".gcode", ".bgcode"})) - throw ToolFailure(p.get() + " is a G-code file, which project_open opens to show its toolpaths"); - paths.push_back(*resolved); - } - if (paths.empty()) - throw ToolFailure("paths is empty"); - json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - Ops::ImportModelsArgs models; - models.paths = paths; - if (args.contains("entries")) - models.entries = args["entries"].get>(); - const Ops::Outcome imported = Ops::import_models(models); - if (!imported) { - const bool nothing = std::string(imported.refusal().code) == "nothing_loaded"; - throw refused(imported.refusal(), nothing ? "See app_log for the reason." : "", "entries"); - } - json o = objects_summary(plater); - o["opened"] = "models"; - o["added"] = imported.value().added; - if (!imported.value().archives.empty()) { - json archives = json::array(); - for (const Ops::ImportedArchive& archive : imported.value().archives) - archives.push_back({{"path", path_to_utf8(archive.path)}, {"entries", archive.entries}}); - o["archives"] = std::move(archives); - } - return o; - }); - settle(ctx); - return ToolResult::ok(out); - })); - import_.actions = json::array( - {NativeCommands::action("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", json::object(), - "Import models (3MF/STL/STEP/SVG/OBJ/AMF) through a file dialog, as one undo step; a project " - "file's settings are not loaded (project_open opens a project). project_import with paths adds " - "files' geometry without a dialog."), - NativeCommands::action("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", {{"archive", true}}, - "Import models from a ZIP archive (opens a file dialog).")}); - catalog.add(NativeCommands::with_person_form(std::move(import_), [](const json& action_args) { - return action_args.value("archive", false) ? MenuItems::import_zip_archive() : MenuItems::import_file(); - })); - - // New Project's menu item is its action: with no arguments it asks as the item does. - NativeCommand project_new = reaching({"new_project"}, mutate_tool( - "project_new", L("New Project"), - "Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes " - "if there are any: the reply is then `blocked_by_dialog`, and `dialog_answer` answers it. With arguments, or `silent: " - "true`, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless " - "`discard_changes`. The presets' unsaved changes carry over to the new project unless `preset_changes` is \"discard\", as " - "New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved " - "changes, discarded and modified list per preset the keys dropped and the keys still unsaved. With no arguments " - "the reply is ran and level, also once a prompt is answered, whatever the answer: Cancel keeps the project.", - object_schema({{"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail; for the " - "presets', see `preset_changes`.")}, - {"preset_changes", enum_prop({"keep", "discard"}, "The presets' unsaved changes, not the project's: keep " - "them for the new project (default) or drop them.")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); - const bool discard_presets = arg_string(args, "preset_changes", "keep") == "discard"; - json out = ctx.run_ui([&] { - ui_plater(); - const json before = unsaved_changes(); - Ops::NewProjectArgs fresh; - fresh.unsaved = unsaved_changes_answer(discard); - fresh.discard_preset_changes = discard_presets; - const Ops::Outcome started = Ops::new_project(fresh); - if (!started) - throw refused(started.refusal(), kUnsavedChangesHint); - json o = project_json(started.value()); - o.update(unsaved_changes_outcome(before)); - return o; - }); - settle(ctx); - return ToolResult::ok(out); - })); - project_new.actions = json::array({NativeCommands::action("new_project", L("New Project"), L("Commands"), "menu_open", json::object(), - "Runs project_new with no arguments, as New Project does: a new, empty " - "project, after asking about the unsaved changes if there are any.")}); - catalog.add(NativeCommands::with_person_form(std::move(project_new), [](const json&) { - if (Plater* plater = wxGetApp().plater()) - plater->new_project(); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - })); - - NativeCommand calibration = mutate_tool( - "calibration_generate_test", L("Generate a calibration test"), - "Generate a Calibration menu test as its dialog's OK does: a new project named after the test, with the test model " - "and the process, filament and printer presets changed as the test needs. It prints with `filament_slot` on the " - "extruder the filament map gives it, so the filament tab points at that slot's preset. Omitted parameters take the " - "dialog's defaults (pressure advance's by the printer's extruder type), but `filament_slot` defaults to 1, not the " - "filament tab's; temperatures are clamped to 155-500 °C and rounded down to 5 °C. Fails, changing nothing, while the " - "project has unsaved changes (pass `discard_changes`) or the presets do (pass `preset_changes`). With test alone it " - "opens that test's dialog (`blocked_by_dialog`), whose OK runs it, unless `silent: true`, which runs it with the " - "dialog's defaults. Reply: test, project, params (the values used, as the journal records them), objects, names, " - "plates, `presets_changed` (its filament names the `filament_slot`, and with several extruders the 1-based extruder " - "where the filament map decides it), `result_keys` (where the measured value belongs), warnings, adjusted (vfa), and " - "discarded and modified as `project_new`. Then `plate_slice` and `project_export`. To save a measured value: " - "`project_new {discard_changes, preset_changes: \"discard\"}`, `settings_set` the value, `preset_save`.", - object_schema( - {{"test", enum_prop({"temperature", "max_volumetric", "pressure_advance", "flow_ratio", "retraction", "vfa", "cornering", - "input_shaping_freq", "input_shaping_damp"}, - "The test, as the Calibration menu names it.")}, - {"filament_slot", {{"type", "integer"}, - {"minimum", 1}, - {"description", "The physical filament (1-based slot) to print with, as the dialog's filament " - "list offers them; not a mixed one. Default 1."}}}, - {"method", enum_prop({"tower", "line", "pattern", "pass1", "pass2", "yolo", "yolo_perfectionist"}, - "`pressure_advance`: tower (default), line or pattern; `flow_ratio`: pass1, pass2, yolo (default) or " - "`yolo_perfectionist`.")}, - {"start", prop("number", "Start of the swept value: °C, mm³/s, PA, mm, mm/s (vfa), Hz (`input_shaping_freq`), " - "damping (`input_shaping_damp`), junction deviation mm or jerk mm/s (cornering).")}, - {"end", prop("number", "End of the swept value.")}, - {"step", prop("number", "Step: `max_volumetric`, `pressure_advance`, retraction, vfa.")}, - {"start_y", prop("number", "`input_shaping_freq`: start of the Y range; default the X one.")}, - {"end_y", prop("number", "`input_shaping_freq`: end of the Y range; default the X one.")}, - {"damping", prop("number", "`input_shaping_freq`: the damping ratio printed with.")}, - {"freq_x", prop("number", "`input_shaping_damp`: the X frequency, Hz.")}, - {"freq_y", prop("number", "`input_shaping_damp`: the Y frequency, Hz; default `freq_x`.")}, - {"shaper_type", prop("string", "Input shaping: an `input_shaping_type` the printer's firmware offers; default the first.")}, - {"test_model", enum_prop({"ringing_tower", "fast_tower", "scv_v2", "standard", "overhang"}, - "Input shaping: `ringing_tower` (default) or `fast_tower`; cornering: also `scv_v2`; temperature on " - "belt printers: standard (default) or overhang.")}, - {"print_numbers", prop("boolean", "`pressure_advance` line: print the values (default true).")}, - {"accelerations", array_prop({{"type", "integer"}, {"minimum", 1}}, - "`pressure_advance` pattern: one test per acceleration and speed; default the process's.")}, - {"speeds", array_prop({{"type", "integer"}, {"minimum", 1}}, "`pressure_advance` pattern: default an optimal speed.")}, - {"top_surface_pattern", enum_prop({"archimedeanchords", "monotonic"}, "`flow_ratio` (default archimedeanchords).")}, - {"auto_scale", prop("boolean", "temperature, vfa: scale the model to the nozzle (default true).")}, - {"auto_adjust", prop("boolean", "vfa: lower the layer height, else the end speed, to stay within the filament's " - "maximum volumetric speed (default true); only with `auto_scale`.")}, - {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail; for the presets', " - "see `preset_changes`.")}, - {"preset_changes", enum_prop({"keep", "discard"}, "The presets' unsaved changes: keep them for the test or drop them " - "first. Required when there are any.")}}, - {"test"}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - json recorded = args; - const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); - json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - if (plater.printer_technology() != ptFFF) - throw ToolFailure("Calibration tests are for filament (FFF) printers"); - PresetBundle& bundle = *wxGetApp().preset_bundle; - const bool discard_presets = arg_string(args, "preset_changes") == "discard"; - // Discarded edits are gone before the test runs, so its rules and defaults are the saved printer's. - const DynamicPrintConfig& printer = discard_presets ? bundle.printers.get_selected_preset().config : - bundle.printers.get_edited_preset().config; - std::vector warnings; - Calib_Params params = calib_params_from_args(args, printer, warnings); - // The dialog's filament list offers the physical filaments; a mixed slot is none of them. - const size_t physical = std::min(bundle.num_physical_filaments(), bundle.filament_presets.size()); - const int slot = arg_int(args, "filament_slot", 1); - if (slot < 1 || size_t(slot) > physical) - throw ToolFailure(slot >= 1 && size_t(slot) <= bundle.filament_presets.size() ? - "Filament slot " + std::to_string(slot) + " is a mixed filament; a test prints with a " + - "physical one, slot 1.." + std::to_string(physical) : - "filament_slot must be 1.." + std::to_string(physical) + ", the physical filaments"); - const int extruder = calib_filament_extruder(size_t(slot - 1)); - params.filament_id = slot - 1; - params.extruder_id = std::max(extruder, 0); - require_project_discardable(discard); - // The GUI asks whether to keep or discard modified presets here; the caller answers with preset_changes. - const json before = unsaved_changes(); - if (!before.empty() && !args.contains("preset_changes")) { - const json modified = unsaved_changes_outcome(json::object()).value("modified", json::object()); - std::string list; - for (auto it = modified.begin(); it != modified.end(); ++it) - list += std::string(list.empty() ? "" : "; ") + it.key() + " \"" + it.value()["name"].get() + - "\": " + boost::algorithm::join(it.value()["keys"].get>(), ", "); - throw ToolFailure("Presets are modified (" + list + "). Pass preset_changes: \"discard\" to drop them first, or \"keep\" " - "to run the test with them", - {{"modified", modified}}); - } - // Switching the filament tab to the test's filament must not ask about another preset's changes. - const std::string& slot_preset = bundle.filament_presets[size_t(slot - 1)]; - if (!discard_presets && bundle.filaments.get_edited_preset().name != slot_preset && bundle.filaments.current_is_dirty()) - throw ToolFailure("The filament tab edits \"" + bundle.filaments.get_edited_preset().name + - "\", which has unsaved changes, and the test prints with filament slot " + std::to_string(slot) + - " (\"" + slot_preset + "\"); pass preset_changes: \"discard\", or save or drop those changes first"); - if (discard_presets && wxGetApp().has_current_preset_changes()) - wxGetApp().discard_current_preset_changes(); - const std::string switched_from = edit_filament_slot(slot); - - // The journal keeps VFA's end as asked, since the fit recomputes it from the presets. - recorded.update(calib_params_json(args, params, printer)); - const json adjusted = params.mode == CalibMode::Calib_VFA_Tower ? - apply_vfa_fit(params, arg_bool(args, "auto_adjust", true), bundle, warnings) : - json(); - const DynamicPrintConfig process_before = bundle.prints.get_edited_preset().config; - const DynamicPrintConfig filament_before = bundle.filaments.get_edited_preset().config; - const DynamicPrintConfig printer_before = bundle.printers.get_edited_preset().config; - switch (params.mode) { - case CalibMode::Calib_Temp_Tower: plater.calib_temp(params, true); break; - case CalibMode::Calib_Vol_speed_Tower: plater.calib_max_vol_speed(params, true); break; - case CalibMode::Calib_PA_Tower: - case CalibMode::Calib_PA_Line: - case CalibMode::Calib_PA_Pattern: plater.calib_pa(params, true); break; - case CalibMode::Calib_Flow_Rate: { - const std::string method = arg_string(args, "method", "yolo"); - plater.calib_flowrate(method == "yolo" || method == "yolo_perfectionist", - method == "pass2" || method == "yolo_perfectionist" ? 2 : 1, - arg_string(args, "top_surface_pattern") == "monotonic" ? ipMonotonic : ipArchimedeanChords, - params.filament_id, params.extruder_id, true); - break; - } - case CalibMode::Calib_Retraction_tower: plater.calib_retraction(params, true); break; - case CalibMode::Calib_VFA_Tower: plater.calib_VFA(params, true); break; - case CalibMode::Calib_Input_shaping_freq: plater.calib_input_shaping_freq(params, true); break; - case CalibMode::Calib_Input_shaping_damp: plater.calib_input_shaping_damp(params, true); break; - case CalibMode::Calib_Cornering: plater.Calib_Cornering(params, true); break; - default: break; - } - - json presets_changed = json::object(); - const auto changed_preset = [&presets_changed](const char* type, const PresetCollection& presets, const DynamicPrintConfig& config_before) { - if (json changes = changed_settings(config_before, presets.get_edited_preset().config); !changes.empty()) - presets_changed[type] = {{"name", presets.get_edited_preset().name}, {"changes", std::move(changes)}}; - }; - changed_preset("process", bundle.prints, process_before); - changed_preset("printer", bundle.printers, printer_before); - presets_changed["filament"] = {{"name", bundle.filaments.get_edited_preset().name}, - {"filament_slot", slot}, - {"changes", changed_settings(filament_before, bundle.filaments.get_edited_preset().config)}}; - // The extruder, as the dialog's filament list names it: only with several, once the filament map decides it. - if (const auto* nozzles = bundle.printers.get_edited_preset().config.option("nozzle_diameter"); - nozzles != nullptr && nozzles->size() > 1 && extruder >= 0) - presets_changed["filament"]["extruder"] = extruder + 1; - if (!switched_from.empty()) - presets_changed["filament"]["tab_switched_from"] = switched_from; - if (plater.model().objects.empty()) - throw ToolFailure("The project was replaced but the test model was not added; see app_log", - {{"presets_changed", presets_changed}}); - - json reply = calib_params_json(args, params, printer); - // The pattern's defaults are the process's acceleration and an optimal speed, which the test writes there. - if (params.mode == CalibMode::Calib_PA_Pattern) - for (const auto& [key, option] : {std::make_pair("accelerations", "outer_wall_acceleration"), std::make_pair("speeds", "outer_wall_speed")}) - if (!reply.contains(key)) - if (const auto* opt = bundle.prints.get_edited_preset().config.option(option)) - reply[key] = json::array({opt->get_at(0)}); - json o = {{"test", args["test"]}, {"project", into_u8(plater.get_project_name())}, {"params", std::move(reply)}}; - o.update(objects_summary(plater)); - o["presets_changed"] = std::move(presets_changed); - o["result_keys"] = calib_result_keys(params.mode, bundle.printers.get_edited_preset().config); - if (!warnings.empty()) - o["warnings"] = warnings; - if (!adjusted.is_null()) - o["adjusted"] = adjusted; - o.update(unsaved_changes_outcome(before)); - return o; - }); - ctx.set_journal_args(std::move(recorded)); - settle(ctx); - return ToolResult::ok(out); - }); - // The Calibration menu's items, each the dialog of its test. The tab strip's calib_sf glyph is drawn white for the dark - // tab bar and vanishes on the Speed Dial's light tile, so each item borrows the matching settings-group icon instead. - struct CalibrationMenuItem - { - const char* key; - const char* title; - const char* icon; - const char* test; - CalibKind kind; - }; - // Titles are L("...")-marked here so xgettext extracts them. - static const CalibrationMenuItem calibration_menu_items[] = { - {"calib_temperature", L("Temperature Calibration"), "param_temperature", "temperature", CalibKind::Temperature}, - {"calib_max_volumetric", L("Max Volumetric Speed Calibration"), "param_volumetric_speed", "max_volumetric", - CalibKind::MaxVolumetric}, - {"calib_pressure_advance", L("Pressure Advance Calibration"), "param_flow_ratio_and_pressure_advance", "pressure_advance", - CalibKind::PressureAdvance}, - {"calib_flow_ratio", L("Flow Ratio Calibration"), "param_flow_ratio_and_pressure_advance", "flow_ratio", CalibKind::FlowRatio}, - {"calib_retraction", L("Retraction Calibration"), "param_retraction", "retraction", CalibKind::Retraction}, - {"calib_cornering", L("Cornering Calibration"), "param_precision", "cornering", CalibKind::Cornering}, - {"calib_input_shaping_freq", L("Input Shaping Frequency Calibration"), "param_resonance_avoidance", "input_shaping_freq", - CalibKind::InputShapingFreq}, - {"calib_input_shaping_damp", L("Input Shaping Damping Calibration"), "param_resonance_avoidance", "input_shaping_damp", - CalibKind::InputShapingDamp}, - {"calib_vfa", L("VFA Calibration"), "param_speed", "vfa", CalibKind::VFA}, - }; - calibration.actions = json::array(); - for (const CalibrationMenuItem& item : calibration_menu_items) - calibration.actions.push_back(NativeCommands::action(item.key, item.title, L("Calibration"), item.icon, {{"test", item.test}}, - std::string("Open the ") + item.title + - " dialog; calibration_generate_test with the test's parameters, or " - "silent, runs it with no dialog.")); - catalog.add(NativeCommands::with_person_form(std::move(calibration), [](const json& action_args) { - const std::string test = action_args.at("test"); - for (const CalibrationMenuItem& item : calibration_menu_items) - if (test == item.test) - return MenuItems::calib(item.kind); - return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("Unknown test \"" + test + "\""), false}; - })); - - // Save Project's and Save Project As's menu items are its actions: with no arguments, or with save_as alone, it saves as - // the item does. - NativeCommand save = reaching({"save_project_as"}, mutate_tool( - "project_save", L("Save Project"), - "Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, " - "level), or, when it has none, through a file dialog (`blocked_by_dialog`; a native picker needs `dialog_auto_answer` " - "registered first); with `save_as: true` alone, as Save Project As does, always through the file dialog. With path, " - "it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name " - "ending in .gcode.3mf is refused (`project_export` writes that). Either way the save can still open a dialog " - "(`blocked_by_dialog`): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file " - "cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, " - "fails with `project_not_saved`, and a file already there stays as it was.", - object_schema({{"path", prop("string", "Absolute .3mf path.")}, - {"overwrite", prop("boolean", "Replace an existing file.")}, - {"save_as", prop("boolean", "true, alone: ask for the file in the save dialog, as Save Project As does. With " - "path it adds nothing: path is the new file.")}}, - {"path"}), - [](const json& args, ToolContext& ctx) { - std::string err; - auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); - if (!path) - throw ToolFailure(err); - ctx.run_ui([&] { - ui_plater(); - Ops::SaveProjectAsArgs save; - save.path = *path; - if (const Ops::Outcome saved = Ops::save_project_as(save); !saved) - throw refused(saved.refusal(), std::string(saved.refusal().code) == "sliced_file_name" ? - "That is project_export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." : - "See app_log."); - return json(); - }); - settle(ctx); - return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}}); - })); - save.actions = json::array( - {NativeCommands::action("save_project", L("Save Project"), L("Commands"), "menu_save", json::object(), - "Runs project_save with no arguments, as Save Project does: to the project's file, or through a " - "file dialog when it has none."), - NativeCommands::action("save_project_as", L("Save Project As"), L("Commands"), "menu_save", {{"save_as", true}}, - "Save the project as a .3mf file through the save dialog. project_save with a path saves there " - "without a dialog; a name ending in .gcode.3mf is refused (project_export {format: \"sliced_3mf\"} " - "writes that).")}); - save = NativeCommands::with_person_form(std::move(save), [](const json& action_args) { - if (action_args.value("save_as", false)) - return MenuItems::save_project_as(); - if (Plater* plater = wxGetApp().plater()) - return NativeCommands::project_save_result(plater->save_project(false)); - return AppActionRunResult{AppActionRunResult::Level::Succeeded}; - }); - // Every call but the two actions' requires path, and a call with path skips the file dialog: silent has nothing to add. - save.input_schema["properties"]["silent"]["description"] = - "Goes with path, which every call but {} and `{save_as: true}` requires, and adds nothing to it: a call with path skips " - "the file dialog already."; - catalog.add(save); - - NativeCommand export_ = reaching( - {"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "export_toolpaths_obj"}, - with_target_ids(mutate_tool( - "project_export", L("Export"), - "Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the " - "background, and the call returns once it is). `sliced_3mf`: the sliced plate, or all plates, as .gcode.3mf (slice " - "first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl and drc " - "(Draco): the objects as one file, or with `per_object` each in a file of its own, named after it, into the folder " - "path names; every object of every plate, or those objects names. `toolpaths_obj`: the toolpaths the Preview shows, " - "as an OBJ, refused while it shows none (slice the plate and show the Preview first). Without format, the path's " - "extension (.gcode, .gcode.3mf, .3mf, .stl, .drc, .obj) says which. Called with exactly the arguments of one of the " - "File > Export menu items (format alone, `sliced_3mf` with plates \"all\", stl or drc with `per_object`), it asks for the file " - "or folder in the dialog that item opens (`blocked_by_dialog`). A file per object of a project with no objects, and the " - "toolpaths while the Preview shows none, are refused in either form. Reply: path and bytes; for gcode, path and " - "export (ok, or superseded with a note when the project changed while it was written); for `per_object`, path and " - "files (each file written); for stl and drc, objects (those written).", - with_targets(object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl", "drc", "toolpaths_obj"}, - "What to write; default from the path's extension.")}, - {"path", prop("string", "Absolute output path: the file, or with `per_object` an existing folder.")}, - {"plates", {{"type", {"string", "integer"}}, - {"description", "\"current\" (default), a plate index, which is selected first and is " - "the plate gcode and `sliced_3mf` write, or \"all\" (`sliced_3mf` only)."}}}, - {"per_object", prop("boolean", "stl and drc: a file per object, into a folder. Default false.")}, - {"overwrite", prop("boolean", "Replace an existing file.")}}, - {"path"}), - kObjects, false), - [](const json& args, ToolContext& ctx) { - const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path")); - const bool per_object = arg_bool(args, "per_object", false); - const bool meshes = format == "stl" || format == "drc"; - if (per_object && !meshes) - throw ToolFailure("per_object goes with format stl or drc"); - if (per_object && (args.contains("plates") || args.contains("overwrite"))) - throw ToolFailure("per_object writes every object into the folder path names: plates and overwrite go with one file"); - if (format == "toolpaths_obj" && args.contains("plates")) - throw ToolFailure("toolpaths_obj writes the toolpaths the Preview shows: plates goes with the other formats"); - const json plate = args.value("plates", json("current")); - const bool all = plate.is_string() && plate.get() == "all"; - if (plate.is_string() && !all && plate.get() != "current") - throw ToolFailure("plates is \"all\", \"current\" or a plate index"); - if (all && format != "sliced_3mf") - throw ToolFailure("plates \"all\" applies to sliced_3mf only"); - std::string err; - const auto path = per_object ? resolve_output_dir(arg_string(args, "path"), err) : - resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); - if (!path) - throw ToolFailure(err); - std::optional ticket; - json written = json::object(); // what the reply adds for stl and drc - ctx.run_ui([&]() -> json { - // A G-code export finishes in the background: held from before it starts. - if (format == "gcode") - ctx.begin_operation(); - Plater& plater = ui_plater(); - const std::optional index = plate.is_number_integer() ? std::optional(plate.get()) : std::nullopt; - // The export's own refusals of the object indices given come before the target check, which - // refuses an index the project lacks without no_such_object's code. - std::vector indices; - if (args.contains("object") && args.at("object").is_number_integer()) - indices.push_back(args.at("object").get()); - for (const json& entry : args.value("objects", json::array())) - if (entry.is_number_integer()) - indices.push_back(entry.get()); - if (const std::optional refusal = Ops::export_objects_refusal(format, indices, per_object, plater.model())) - throw refused(*refusal); - // The objects named, by index or id; none named: every object. - Targets named; - if (names_targets(args)) { - const Ops::Outcome found = resolve_targets(plater.model(), nullptr, args, kObjects, false); - if (!found) - throw refused(found.refusal()); - named = found.value(); - } - if (const std::optional refusal = - Ops::export_objects_refusal(format, named.objects, per_object, plater.model())) - throw refused(*refusal); - if (meshes) { - Ops::ExportStlArgs mesh; - mesh.path = *path; - mesh.plate = index; - mesh.objects = named.objects; - mesh.per_object = per_object; - mesh.draco = format == "drc"; - const Ops::Outcome> files = Ops::export_stl(mesh); - if (!files) - throw refused(files.refusal(), std::string(files.refusal().code) == "file_not_written" ? "See app_log." : ""); - Targets exported = named; - if (exported.objects.empty()) - for (int o = 0; o < int(plater.model().objects.size()); ++o) - exported.objects.push_back(o); - written = targets_reply(plater.model(), exported); - if (per_object) { - written["files"] = json::array(); - for (const fs::path& file : files.value()) - written["files"].push_back(path_to_utf8(file)); - } - return json(); - } - if (format == "toolpaths_obj") { - if (const Ops::Outcome drawn = Ops::export_toolpaths_obj({*path}); !drawn) - throw refused(drawn.refusal(), std::string(drawn.refusal().code) == "no_toolpaths" ? - "plate_slice {preview: true} slices the plate and shows it." : - "See app_log."); - return json(); - } - if (format == "gcode") { - Ops::ExportGcodeArgs gcode; - gcode.path = *path; - gcode.plate = index; - const Ops::Outcome started = Ops::start_gcode_export(gcode); - if (!started) { - const std::string code = started.refusal().code; - throw refused(started.refusal(), code == "slicing_in_progress" ? "app_wait {for:\"idle\"} waits for it." : - code == "export_not_started" ? "Check app_state.notifications." : - ""); - } - ticket = started.value(); - return json(); - } - Ops::ExportSlicedArgs sliced; - sliced.path = *path; - sliced.all_plates = all; - sliced.plate = index; - Ops::ExportFileArgs file; - file.path = *path; - file.plate = index; - const Ops::Outcome done = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) : Ops::export_model_3mf(file); - if (!done) - throw refused(done.refusal(), std::string(done.refusal().code) == "file_not_written" ? "See app_log." : ""); - return json(); - }); - if (ticket) - return await_gcode_export(ctx, *ticket); - settle(ctx); - json reply{{"path", path_to_utf8(*path)}}; - if (!per_object) - reply["bytes"] = fs::file_size(*path); - reply.update(written); - return ToolResult::ok(reply); - }))); - // The File > Export menu items, each with the dialog it asks for the file or folder in. - export_.actions = json::array({ - NativeCommands::action("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", {{"format", "gcode"}}, - "Export the current plate's G-code through the export dialog, in the background. project_export " - "with a path exports the sliced plate there without a dialog, and the call returns when the file " - "is written; a plate that is not sliced is refused (slice first)."), - NativeCommands::action("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", {{"format", "sliced_3mf"}}, - "Export the current plate's sliced file (.gcode.3mf) through a file dialog; project_export with a " - "path writes there without one."), - NativeCommands::action("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", - {{"format", "sliced_3mf"}, {"plates", "all"}}, - "Export every plate's sliced file into one .gcode.3mf through a file dialog; project_export with a " - "path writes there without one."), - NativeCommands::action("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", {{"format", "3mf"}}, - "Export the model as a .3mf without slicing data, through a file dialog; project_export with a path " - "writes there without one."), - NativeCommands::action("export_stl", L("Export STL"), L("Slice & Export"), "save", {{"format", "stl"}}, - "Export all objects as one STL through a file dialog; project_export with a path writes there " - "without one."), - NativeCommands::action("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", - {{"format", "stl"}, {"per_object", true}}, - "Export each object as its own STL into the folder a dialog asks for; project_export with a folder " - "as path writes there without one."), - NativeCommands::action("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", {{"format", "drc"}}, - "Export all objects as one Draco (.drc) file."), - NativeCommands::action("export_drc_multi", L("Export All Objects as DRCs"), L("Export"), "save", - {{"format", "drc"}, {"per_object", true}}, - "Export each object as its own Draco (.drc) file."), - NativeCommands::action("export_toolpaths_obj", L("Export Toolpaths as OBJ"), L("Export"), "custom-gcode_gcode", - {{"format", "toolpaths_obj"}}, "Export the sliced toolpaths as an OBJ."), - }); - catalog.add(NativeCommands::with_person_form(std::move(export_), [](const json& action_args) { - const std::string format = action_args.at("format"); - const bool per_object = action_args.value("per_object", false); - if (format == "gcode") - return MenuItems::export_gcode(); - if (format == "sliced_3mf") - return MenuItems::export_sliced_file(action_args.value("plates", std::string()) == "all"); - if (format == "3mf") - return MenuItems::export_3mf(); - if (format == "stl") - return per_object ? MenuItems::export_stl_multi() : MenuItems::export_stl(); - if (format == "drc") - return per_object ? MenuItems::export_drc_multi() : MenuItems::export_drc_single(); - return MenuItems::export_toolpaths_obj(); - })); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp deleted file mode 100644 index 2d9d8b3f87..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// script_run, script_list_api and script_describe_api: Python scripts against orca.host, the plugin API, and the orca -// package's reference, read one module or class at a time. - -#include "JobRegistry.hpp" -#include "McpArguments.hpp" -#include "McpCore.hpp" -#include "McpPaths.hpp" -#include "McpPersonRun.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" - -#include "slic3r/GUI/ActionRegistry.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/NativeCommandMenuItems.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/plugin/PluginAuditManager.hpp" -#include "slic3r/plugin/PythonInterpreter.hpp" -#include "slic3r/plugin/PythonScriptRunner.hpp" -#include "slic3r/plugin/PythonSession.hpp" -#include "slic3r/plugin/host/PluginHostTools.hpp" - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; -namespace py = pybind11; - -namespace { - -// A run's orca.host.tools calls, as child calls of the script_run job, so each has its tool's guards, -// admission and undo, and a cancel of the run reaches them. -class RunBridge final : public ToolBridge -{ -public: - explicit RunBridge(ToolContext& ctx) : m_ctx(ctx) {} - json call(const std::string& tool, const json& args) override - { - ToolResult r = m_ctx.call_child(tool, args); - if (r.is_error) - throw ToolCallError(r.message, r.data); - return r.data; - } - -private: - ToolContext& m_ctx; -}; - -// The Run Script panel's session's orca.host.tools calls: child calls under a lineage node of the session's job, so a -// stop cancels every call in flight, inline ones (app_wait) included, without stopping the session, and the next work's -// calls run under a fresh node. -class SessionBridge final : public ToolBridge -{ -public: - SessionBridge(AutomationRuntime& runtime, const std::string& session_job) - : m_runtime(runtime), m_node(runtime.jobs(), "script_run", session_job) - {} - json call(const std::string& tool, const json& args) override - { - ToolResult r = m_runtime.core().call_child_named(tool, args, m_node.id()); - if (r.is_error) - throw ToolCallError(r.message, r.data); - return r.data; - } - // A stop or time-out, from the session's watcher: the node's calls are cancelled, and its operations, as the - // job_cancel cancels them. - void stop_calls() - { - const std::string node = m_node.id(); - m_stopped = true; - m_runtime.jobs().request_stop(node); - // Found again on the UI thread: the runtime may be gone by the time the closure runs. - m_runtime.post_ui([node] { - if (AutomationRuntime* runtime = wxGetApp().automation_if_started()) - runtime->cancel_operations_of(node); - }); - } - // As a work starts: after a stop its calls get a node no stop was asked for. - void renew_after_stop() - { - if (m_stopped.exchange(false)) - m_node.renew(); - } - -private: - AutomationRuntime& m_runtime; - LineageNode m_node; - std::atomic m_stopped{false}; -}; - -// python_api_reference()'s walk over the orca package. -constexpr const char* kReferenceSource = R"PY( -import inspect, re, types - -# A signature line pybind11 starts a docstring with: "name(...) -> T", numbered after "Overloaded function.", -# and without a name for a property's getter. -_SIGNATURE = re.compile(r"^(?:\d+\. )?(\w*)\(.*\)(?: -> .+)?$") -_SELF = re.compile(r"\bself: [\w.]+") -# The types of a module's constants, such as orca.host.ui.PD_CAN_ABORT. -_CONSTANTS = (bool, int, float, str) - -def _split(names, doc): - """The signature lines of a docstring whose function is called one of names, and the rest of it.""" - signatures, text = [], [] - for line in (doc or "").splitlines(): - stripped = line.strip() - match = _SIGNATURE.match(stripped) - if match and match.group(1) in names: - signatures.append(_SELF.sub("self", re.sub(r"^\d+\. ", "", stripped))) - elif stripped != "Overloaded function.": - text.append(line) - # An overloaded function's first line, name(*args, **kwargs), stands for the numbered overloads after it. - if len(signatures) > 1: - signatures = [s for s in signatures if not s.endswith("(*args, **kwargs)")] - return signatures, "\n".join(text).strip() - -def _entry(name, obj, kind): - short = name.rsplit(".", 1)[-1] - if kind == "class": - # A class's own docstring, not one inherited from a base, then what its constructors say of their - # arguments; the constructors' signatures are the class's. - init = vars(obj).get("__init__") - signatures, made = _split(("__init__",), init.__doc__ if init is not None else None) - signatures = [short + s[len("__init__"):].replace("(self, ", "(").replace("(self)", "()").replace(" -> None", "") - for s in signatures] - doc = inspect.cleandoc(obj.__doc__ or "") - if made and made != doc: - doc = (doc + "\n\n" + made).strip() - return {"name": name, "kind": kind, "signature": " | ".join(signatures) or short, "doc": doc} - if kind == "property": - getter = obj.fget.__doc__ if obj.fget is not None else "" - returns = re.match(r"^\w*\(.*\) -> (.+)$", (getter or "").strip().split("\n")[0]) - _, doc = _split((short, ""), inspect.getdoc(obj)) - return {"name": name, "kind": kind, "signature": short + (": " + returns.group(1) if returns else ""), "doc": doc} - signatures, doc = _split((short, ""), inspect.getdoc(obj)) - if not signatures: - try: - signatures = [short + str(inspect.signature(obj))] - except (TypeError, ValueError): - signatures = [short] - return {"name": name, "kind": kind, "signature": " | ".join(signatures), "doc": doc} - -def reference(package): - out, seen, constants = [], set(), [] - def walk(module, prefix): - if id(module) in seen: - return - seen.add(id(module)) - out.append(_entry(prefix.rstrip("."), module, "module")) - for name, value in sorted(vars(module).items()): - if name.startswith("_"): - continue - full = prefix + name - if isinstance(value, types.ModuleType): - if value.__name__.startswith(package.__name__): - walk(value, full + ".") - elif inspect.isclass(value): - out.append(_entry(full, value, "class")) - # An enum lists its values in its docstring; name and value are every enum's. - values = getattr(value, "__members__", None) - for member, attr in sorted(vars(value).items()): - if member.startswith("_") or (values is not None and (member in values or member in ("name", "value"))): - continue - # A class holds a static method as a staticmethod object, whose documentation is the - # staticmethod type's; pybind11 documented the function inside it. - if isinstance(attr, (staticmethod, classmethod)): - attr = attr.__func__ - kind = "property" if isinstance(attr, property) else "method" if callable(attr) else None - if kind: - out.append(_entry(full + "." + member, attr, kind)) - elif callable(value): - out.append(_entry(full, value, "function")) - elif isinstance(value, _CONSTANTS): - constants.append(len(out)) - out.append({"name": full, "kind": "constant", "signature": name + " = " + repr(value), "doc": ""}) - elif type(value).__module__.startswith(package.__name__) and not hasattr(type(value), "__members__"): - # An instance the package offers by name, such as orca.host.preset.process; enum values - # exported into a module are their enum's. - kind_of = type(value) - out.append({"name": full, "kind": "attribute", "signature": name + ": " + kind_of.__module__ + "." + kind_of.__name__, - "doc": inspect.cleandoc(kind_of.__doc__ or "")}) - walk(package, package.__name__ + ".") - # A constant has no docstring of its own: the documentation of what takes it says what it means. - for i in constants: - word = re.compile(r"\b" + re.escape(out[i]["name"].rsplit(".", 1)[-1]) + r"\b") - users = [e["name"] for e in out if e["kind"] != "constant" and word.search(e["doc"])] - if users: - out[i]["doc"] = "See " + ", ".join(users) + "." - return out -)PY"; - -} // namespace - -json python_api_reference() -{ - py::gil_scoped_acquire gil; - try { - py::dict scope; - py::exec(kReferenceSource, scope); - json entries = json::array(); - for (const auto item : scope["reference"](py::module_::import("orca")).cast()) { - json entry = json::object(); - for (const auto field : item.cast()) - entry[field.first.cast()] = field.second.cast(); - entries.push_back(std::move(entry)); - } - return entries; - } catch (py::error_already_set& e) { - throw ToolFailure(std::string("Cannot read the Python API: ") + e.what()); - } -} - -json python_api_children(const json& reference, const std::string& within) -{ - const auto is_scope = [&within](const json& e) { - return e["name"] == within && (e["kind"] == "module" || e["kind"] == "class"); - }; - if (std::none_of(reference.begin(), reference.end(), is_scope)) { - json modules = json::array(); - std::string names; - for (const json& e : reference) - if (e["kind"] == "module") { - modules.push_back(e["name"]); - names += (names.empty() ? "" : ", ") + e["name"].get(); - } - throw ToolFailure(within + " is no module or class of the orca package; its modules are " + names, - {{"code", "invalid_argument"}, {"modules", std::move(modules)}}); - } - // An entry is directly inside `within` when its name is `within`, a dot and one more part. - const std::string prefix = within + '.'; - json items = json::array(); - for (const json& e : reference) { - const std::string& name = e["name"].get_ref(); - if (boost::algorithm::starts_with(name, prefix) && name.find('.', prefix.size()) == std::string::npos) - items.push_back({{"name", name}, {"kind", e["kind"]}, {"signature", e["signature"]}, - {"summary", first_sentence(e["doc"].get())}}); - } - return items; -} - -json python_api_entry(const json& reference, const std::string& name) -{ - std::vector> scored; // {distance, index}, the reference's order among equals - for (std::size_t i = 0; i < reference.size(); ++i) { - const std::string& candidate = reference[i]["name"].get_ref(); - if (candidate == name) - return reference[i]; - scored.emplace_back(edit_distance(name, candidate), i); - } - std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); - json closest = json::array(); - std::string names; - for (std::size_t i = 0; i < scored.size() && closest.size() < 3; ++i) { - closest.push_back(reference[scored[i].second]["name"]); - names += (names.empty() ? "" : ", ") + closest.back().get(); - } - throw ToolFailure("No entry " + name + " in the orca package; the closest are " + names, - {{"code", "invalid_argument"}, {"did_you_mean", std::move(closest)}}); -} - -bool python_has_numpy() -{ - py::gil_scoped_acquire gil; - try { - return !py::module_::import("importlib.util").attr("find_spec")("numpy").is_none(); - } catch (py::error_already_set&) { - return false; - } -} - -ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename) -{ - const std::string job = ctx.job_id(); - // The session waits for the person between works: `app_wait {for: "idle"}` counts only the calls it makes. - runtime.jobs().set_idle(job); - // What its calls leave behind is the session's, as a run's is; its rules act only while a work runs. - runtime.begin_run_scope(job); - runtime.set_run_scope_paused(job, true); - struct ScopeEnd - { - AutomationRuntime& runtime; - std::string job; - ~ScopeEnd() { runtime.end_run_scope(job); } - } scope_end{runtime, job}; - - SessionBridge bridge(runtime, job); - ScopedToolBridge bound(bridge); - PythonSessionRequest request; - request.identity = kScriptIdentityPerson; - request.filename = filename; - request.cancelled = [&ctx] { return ctx.cancelled(); }; - request.stop_calls = [&bridge] { bridge.stop_calls(); }; - request.work_started = [&runtime, &bridge, job] { - bridge.renew_after_stop(); - runtime.set_run_scope_paused(job, false); - }; - request.work_ended = [&runtime, job] { - runtime.set_run_scope_paused(job, true); - runtime.release_run_presses(job); - }; - host_python_session(request, session); - return ToolResult::ok({{"status", "ended"}}); -} - -std::shared_ptr start_python_session(AutomationRuntime& runtime, std::shared_ptr session, - const boost::filesystem::path& file, PersonRun::Events events) -{ - const NativeCommand* script_run = NativeCommands::instance().find("script_run"); - if (script_run == nullptr || runtime.stopping() || !session) - return nullptr; - auto run = std::make_shared(runtime, std::move(events)); - auto hosted = std::make_shared>(false); - auto filename = file.empty() ? std::string("") : path_to_utf8(file); - // script_run's properties, outside the session journal, as a person's run. - NativeCommand def = *script_run; - def.journal = false; - def.run = [&runtime, run, session, hosted, filename](const json&, ToolContext& ctx) { - run->set_job(ctx.job_id()); - hosted->store(true); - // A handler that refuses never hosts the session: it ends here all the same. - struct Ended - { - PythonSession& session; - ~Ended() - { - if (!session.ended()) - session.host_returned(); - } - } ended{*session}; - return run_python_session_job(runtime, ctx, *session, filename); - }; - - FollowedCall call; - call.command = std::move(def); - call.origin = {{"source", "run_script"}}; - call.person = true; - call.ended = [&runtime, run, session, hosted](const std::optional& r) { - run->mark_ended(); - // Refused before its handler ran: the session was never hosted. - if (r && !hosted->load()) - session->host_returned(); - if (!r || runtime.stopping() || !r->is_error) - return; - run->post_finished(json{{"error", r->message}}, json()); - }; - call.stop = [run] { run->stop(); }; - if (!runtime.follow(std::move(call))) - return nullptr; - return run; -} - -void register_python_tools(CommandCatalog& catalog) -{ - NativeCommand run = mutate_tool( - "script_run", L("Run a Python script"), - "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against `orca.host`, the whole plugin " - "API (`script_list_api` lists it): read objects, meshes and settings, compute, use `orca.host.ui` and the preset " - "API, and call these same tools, with their guards and undo, through `orca.host.tools.call`(name, args). Mesh and " - "matrix arrays need numpy, which " - "`script_list_api` says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " - "thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon " - "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " - "to a JSON value to return it; print() output comes back as output. Reply: `{status: finished | raised | cancelled | " - "timed_out, result, output, traceback?, message?}`; a script that raised changed what it changed before. The code's " - "own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a " - "file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises " - "PermissionError, unless a person has let Python scripts run unrestricted in Preferences " - "(`app_state.python.scripts_unrestricted`), when the threads and pool tasks it starts call the tools too while " - "the run lasts; the tools it calls work as they do for you. Recorded " - "by `replay_export` as one step with its code, which a replay runs again against the project as it is then.", - object_schema({{"code", prop("string", "Python source, run as a module body.")}, - {"args", {{"type", "object"}, {"description", "Bound to the name `args` in the code."}}}, - {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 3600}, - {"description", "The run is stopped as `timed_out` after this many seconds (default 300)."}}}, - {"filename", prop("string", "The name tracebacks show for the code (default ). An existing file's " - "path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports " - "from its folder and its PEP 723 dependencies; any other name only names it. " - "What runs is still `code`: pass the file's text there.")}}, - {"code"}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - // A plugin's script is the plugin's own code: its identity and grants. - const std::string& plugin = ctx.caller_plugin(); - const std::string identity = !plugin.empty() ? plugin : - runtime.jobs().person_in(ctx.lineage()) ? kScriptIdentityPerson : - kScriptIdentityAgent; - - // A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON - // script does: it all ends with the run. - const std::string job = ctx.job_id(); - // A run may wait for a person in its window: `app_wait {for: "idle"}` counts only the calls it makes. - runtime.jobs().set_idle(job); - runtime.begin_run_scope(job); - struct ScopeEnd - { - AutomationRuntime& runtime; - std::string job; - ~ScopeEnd() { runtime.end_run_scope(job); } - } scope_end{runtime, job}; - - RunBridge bridge(ctx); - ScopedToolBridge bound(bridge); - PythonRunRequest request; - request.code = arg_string(args, "code"); - request.args = args.value("args", json::object()); - request.identity = identity; - request.filename = arg_string(args, "filename", ""); - // 0, below the schema's minimum, is passed only in process, by the Run Script dialog, whose Stop ends a run: - // every external path validates the arguments. It means no time limit. - request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300)); - request.cancelled = [&ctx] { return ctx.cancelled(); }; - // A stop or time-out cancels the run's tool calls in flight too, so one that waits returns at once. - request.stop_calls = [&runtime, job] { runtime.jobs().request_stop(job); }; - const PythonRunOutcome out = run_python_code(request); - if (out.status == "unavailable") - throw ToolFailure(out.message); - - json data{{"status", out.status}, {"result", out.result}, {"output", out.output}}; - if (!out.traceback.empty()) - data["traceback"] = out.traceback; - if (!out.message.empty()) - data["message"] = out.message; - // A run that did not finish is reported, not failed, as replay_run reports a failed step: the - // journal keeps it, and a replay of it fails again (D7). - return ToolResult::ok(std::move(data)); - }); - // job_cancel {job} stops a run: its code is interrupted at its next bytecode. - run.cancellable = true; - // A script reaches outside the app: files, programs and the network. - run.open_world = true; - catalog.add(run); - - // Both read the package as Python runs it now, holding its runtime for the read as script_run does. - const auto while_python_runs = [](const auto& read) { - if (!PythonInterpreter::instance().is_initialized()) - throw ToolFailure("Python is not available in this OrcaSlicer"); - PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); - if (!lease) - throw ToolFailure("Python is shutting down"); - return read(); - }; - catalog.add(inspect_tool( - "script_list_api", L("List the Python API"), - "List `orca`, the Python API of `script_run` scripts and plugins, in the running build, one module or class at a time: " - "`orca.host` (the project's model and meshes, presets and their editors, slicing data, `orca.host.ui` windows and " - "dialogs, `orca.host.tools` calling these tools) and the classes, events and pages plugins build on. It lists what is " - "directly inside `within`, a module or a class (default `orca`): each entry's `name`, `kind`, `signature` (a " - "class's constructors) and the first sentence of its documentation. A module or class it lists is listed with " - "`within` set " - "to its name, and `script_describe_api {name}` gives an entry's whole documentation. Page with `offset`. `numpy` says " - "whether numpy is installed, which mesh and matrix arrays need.", - object_schema({{"within", {{"type", "string"}, {"default", kPythonApiRoot}, - {"description", "A module's or class's dotted name, e.g. \"orca.host\" or " - "\"orca.host.TriangleMesh\"."}}}, - {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}, - {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [while_python_runs](const json& args, ToolContext&) { - return ToolResult::ok(while_python_runs([&args] { - json out = page(python_api_children(python_api_reference(), arg_string(args, "within", kPythonApiRoot)), args, 20); - out["numpy"] = python_has_numpy(); - return out; - })); - })); - catalog.add(inspect_tool( - "script_describe_api", L("Describe a Python API entry"), - "Read one entry of `orca`, the Python API of `script_run` scripts and plugins, by its dotted name as `script_list_api` " - "lists it (`orca.host.TriangleMesh.face_normals`): its `kind`, its `signature` (a class's constructors) and its whole " - "documentation. A name no entry has is refused with the closest names.", - object_schema({{"name", prop("string", "An entry's dotted name, as `script_list_api` lists it.")}}, {"name"}), - [while_python_runs](const json& args, ToolContext&) { - return ToolResult::ok( - while_python_runs([&args] { return python_api_entry(python_api_reference(), arg_string(args, "name")); })); - })); - - // The Run Script panel's menu item, which has no argument form. - const std::string panel = "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents " - "run Python with the script_run tool instead."; - NativeCommand toggle_panel = menu_command("script_toggle_panel", L("Run Script"), panel, object_schema({}), - json::array({NativeCommands::action("toggle_run_script_panel", L("Run Script"), - L("Commands"), "media_play", json::object(), panel)}), - [](const json&) { return MenuItems::toggle_run_script_panel(); }); - // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. - toggle_panel.listed = false; - catalog.add(std::move(toggle_panel)); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp deleted file mode 100644 index 48cf3d93bf..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp +++ /dev/null @@ -1,454 +0,0 @@ -// recording_start, recording_stop and recording_encode: a video of what OrcaSlicer shows, optionally captioned -// with the current tool call and its pointer highlighted, and its encode to MP4. - -#include "McpCore.hpp" -#include "McpPaths.hpp" -#include "McpRecorder.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" -#include "RecordingSettings.hpp" -#include "VideoEncode.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/NativeCommands.hpp" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#else -#include -#endif - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; -namespace fs = boost::filesystem; - -namespace { - -// The recording tools only read the app, so they run behind dialogs and during operations, but each -// is a job: ownership is read from the job's ancestry, and an encode outlives the reply budget. -NativeCommand record_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) -{ - NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler)); - d.description = std::move(description); - d.listed = true; - d.guard = GuardClass::Inspect; - d.journal = true; - return d; -} - -json int_prop(int minimum, int maximum, const std::string& description) -{ - return {{"type", "integer"}, {"minimum", minimum}, {"maximum", maximum}, {"description", description}}; -} - -std::string read_text(const fs::path& path) -{ - boost::nowide::ifstream in(path_to_utf8(path).c_str(), std::ios::binary); - std::ostringstream ss; - ss << in.rdbuf(); - return ss.str(); -} - -void remove_quietly(const fs::path& path) -{ - boost::system::error_code ec; - fs::remove(path, ec); -} - -int process_id() -{ -#ifdef _WIN32 - return _getpid(); -#else - return int(getpid()); -#endif -} - -std::vector encode_preset_keys() -{ - std::vector keys; - for (const EncodePreset& p : encode_presets()) - keys.emplace_back(p.key); - return keys; -} - -} // namespace - -ToolResult start_encode(AutomationRuntime& runtime, const json& args, const std::string& stop_job) -{ - const NativeCommand* encode = NativeCommands::instance().find("recording_encode"); - if (encode == nullptr || runtime.stopping()) - return ToolResult::error("OrcaSlicer is shutting down"); - NativeCommand def = *encode; - def.journal = false; - def.budget_ms = 0; // the envelope at once; the result comes from app_wait - return runtime.core().call(def, args, {{"source", "agent"}, {"under", stop_job}}); -} - -void register_record_tools(CommandCatalog& catalog) -{ - // The Speed Dial's Start Recording is its action: with no arguments it opens the action's dialog. - NativeCommand start = record_tool( - "recording_start", L("Start Recording"), - "Record a video of OrcaSlicer until `recording_stop`: MJPEG frames with their real timestamps in a Matroska (.mkv) " - "file. Captions show the tool call acting on the app at the bottom (secret setting values never show); pointer " - "highlights the pointer, its clicks rippling. Capture takes at most about a third of the UI thread, so the frame " - "rate drops where capturing is slow. One recording at a time: a replay's or script's ends with it, a client's when " - "the server is turned off. With encode, the `recording_stop` that reports it also writes an MP4 beside it and " - "deletes the .mkv unless `keep_raw_video_file`; `recording_encode` encodes any recording later. With no arguments it " - "opens the Start Recording dialog (`blocked_by_dialog`), whose controls are named after their settings for " - "`widget_set_value`; its \"Start recording\" starts the person's recording, which neither a replay's or script's end " - "nor the server turning off ends, and the dialog remembers the settings. `silent: true` starts one at once with the " - "defaults.", - object_schema({{"target", enum_prop({"main", "canvas"}, "main (default): the main window and its dialogs; canvas: the 3D view shown.")}, - {"fps", int_prop(1, 30, "Frames per second at most (default 10).")}, - {"max_dim", int_prop(320, 3840, "Long edge of the video in pixels (default 1920).")}, - {"jpeg_quality", int_prop(30, 95, "JPEG quality of the frames (default 80).")}, - {"max_seconds", int_prop(1, 3600, "The recording ends on its own after this long (default 3600).")}, - {"captions", prop("boolean", "Caption the tool call acting on the app (default false).")}, - {"pointer", prop("boolean", "Highlight the pointer and show its clicks (default false).")}, - {"encode", prop("boolean", "Encode it to an MP4 once stopped; needs an ffmpeg (default false).")}, - {"encode_preset", enum_prop(encode_preset_keys(), "With encode: the settings the fields below change " - "(default balanced: h265, crf 28, medium, main).")}, - {"codec", enum_prop({"h265", "h264"}, "With encode: the codec (default the preset's).")}, - {"crf", int_prop(0, 51, "With encode: constant rate factor, lower is better and larger (default the preset's).")}, - {"speed", enum_prop(encoder_speeds(), "With encode: slower makes a smaller file (default the preset's).")}, - {"profile", enum_prop({"high", "main", "baseline", "main10"}, - "With encode: h264 high, main or baseline; h265 main or main10 (default the preset's, else " - "the codec's first).")}, - {"keep_raw_video_file", prop("boolean", "With encode: keep the .mkv beside the MP4 (default false).")}, - {"save_path", prop("string", "Absolute .mkv path; default the session's output folder.")}, - {"overwrite", prop("boolean", "Replace an existing `save_path`, and with encode its MP4.")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - RecordingOptions o; - o.target = arg_string(args, "target", "main"); - o.fps = arg_int(args, "fps", 10); - o.max_dim = arg_int(args, "max_dim", 1920); - o.quality = arg_int(args, "jpeg_quality", 80); - o.max_seconds = arg_int(args, "max_seconds", 3600); - o.captions = arg_bool(args, "captions", false); - o.pointer = arg_bool(args, "pointer", false); - // The encode with the Start Recording dialog's defaults, the Balanced preset. - RecordingSettings settings; - if (const std::string err = apply_recording_overrides(settings, args); !err.empty()) - throw ToolFailure(err); - if (std::string err; settings.encode && !find_ffmpeg(err)) - throw ToolFailure("Cannot encode: " + err); - if (args.contains("save_path")) { - const std::string path = arg_string(args, "save_path"); - if (!boost::algorithm::iends_with(path, ".mkv")) - throw ToolFailure("save_path must end with .mkv: the recording is Matroska"); - std::string err; - auto p = resolve_output_path(path, arg_bool(args, "overwrite", false), err); - if (!p) - throw ToolFailure(err); - o.path = *p; - } else { - o.path = timestamped_path(output_dir(), "recording", ".mkv", {".mp4"}); - } - if (settings.encode) { - o.encode = encode_arguments(settings, path_to_utf8(o.path)); - if (arg_bool(args, "overwrite", false)) - o.encode["overwrite"] = true; - } - // Like auto-answer rules: a run's recording ends with the run, a client's with the endpoint. - const std::vector ancestry = runtime.jobs().ancestry(ctx.job_id()); - o.owner = runtime.run_owner(ancestry); - // A call of a run that has ended (its scope gone before this ran): not a client's call. - if (o.owner.empty() && runtime.recorder().owner_ended_in(ancestry)) - throw ToolFailure("The replay or script that started the recording has ended"); - // Reserved here, off the UI thread: comparing paths may touch the disk. start() keeps the - // reservation for the recording or releases it. - const std::shared_ptr& files = runtime.recorder().files(); - const uint64_t owner = files->new_owner(); - if (const std::string why = files->reserve(owner, {{o.path, RecordingFiles::Use::Recording}}); !why.empty()) - throw ToolFailure("Cannot record there: " + why); - bool handed_over = false; - struct Release - { - RecordingFiles& files; - uint64_t owner; - const bool& handed_over; - ~Release() - { - if (!handed_over) - files.release(owner); - } - } release{*files, owner, handed_over}; - json out = ctx.run_ui([&] { - ui_plater(); // refuses while OrcaSlicer starts or closes - // On the UI thread, as close_client_scope() runs: a client's start queued while the endpoint - // closed must not begin a recording nothing would end. - if (o.owner.empty() && !runtime.client_scope_open()) - throw ToolFailure("The MCP server was turned off; the recording was not started"); - handed_over = true; // start() owns the reservation from here, success or not - return runtime.recorder().start(o, owner); - }); - if (settings.encode) - out["encode"] = {{"codec", settings.codec}, - {"crf", settings.crf}, - {"speed", settings.speed}, - {"profile", settings.profile}, - {"keep_raw_video_file", settings.keep_raw_video_file}}; - // The limit it runs under, which a call that leaves it out did not choose. - out["max_seconds"] = o.max_seconds; - // The path used, so a replay records into its own output folder under the same name and its - // encode finds it there. - json recorded = args; - recorded["save_path"] = out["path"]; - ctx.set_journal_args(std::move(recorded)); - return ToolResult::ok(out); - }); - start.actions = json::array({NativeCommands::action("start_recording", L("Start Recording"), L("Commands"), "recording_start", - json::object(), - "Runs recording_start with no arguments, as Start Recording does: the Start " - "Recording dialog, whose Start recording starts the person's recording, " - "which neither the end of a replay or script nor the server turning off ends.")}); - catalog.add(NativeCommands::with_person_form(std::move(start), [](const json&) { return NativeCommands::start_person_recording(); })); - - // The Speed Dial's Stop Recording is its action: with no arguments it stops as the action does. - NativeCommand stop = record_tool("recording_stop", L("Stop Recording"), - "Stop the running recording. Call it with `silent: true` for the report: it waits for the file and " - "returns it with its seconds, frames captured and " - "written, frames dropped when encoding fell behind, failed when they could not be encoded, or " - "skipped when the window could not be captured, " - "the size, the mean UI-thread time a capture took (`capture_ms`), and why it ended. A recording that ended on its own (`max_seconds`, the replay or script that started it ended, a " - "write error) is reported once by the next `recording_stop`. For a recording started with encode, it then " - "starts the MP4 encode and returns it under encode: a job, whose `app_wait {for: \"job\"}` returns " - "`recording_encode`'s result, whose `raw_video_file_deleted` says whether the .mkv was deleted. " - "Called with no arguments, it stops " - "the recording as Stop Recording does, whoever started it: without waiting for its " - "file, it shows the person a notification naming it and replies with its path; the next " - "`recording_stop` with `silent: true` reports it as ended `stopped_in_app`.", - object_schema({}), [](const json&, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - // The last state too, even if the timer has not ticked since the last call. Without the - // UI thread (a native dialog holds it), the recording ends with its last frame. - try { - ctx.run_ui([&] { - runtime.recorder().capture_now(); - return json(); - }); - } catch (const ToolFailure&) { - } - json encode; - json report = runtime.recorder().stop_and_report(std::chrono::seconds(60), encode); - if (report.is_null()) - throw ToolFailure("No recording is running"); - if (!encode.is_null()) { - const ToolResult r = start_encode(runtime, encode, ctx.job_id()); - report["encode"] = r.is_error ? json{{"error", r.message}} : r.data; - } - return ToolResult::ok(report); - }); - stop.actions = json::array({NativeCommands::action("stop_recording", L("Stop Recording"), L("Commands"), "recording_stop", - json::object(), - "Runs recording_stop with no arguments, as Stop Recording does: it stops the " - "recording, whoever started it, and shows the person a notification naming its " - "file.")}); - // The person's stop opens nothing: like the silent one, it stops a recording behind a dialog. - stop = NativeCommands::with_person_form(std::move(stop), [](const json&) { return NativeCommands::stop_recording_in_app(); }, - /*person_form_behind_dialogs=*/true); - // It has no other argument, and neither form asks: silent picks the form that waits and reports. - stop.input_schema["properties"]["silent"]["description"] = - "true waits for the file and returns the report, and the encode job when the recording has one; a call with no " - "arguments stops as Stop Recording does."; - catalog.add(stop); - - NativeCommand encode = record_tool( - "recording_encode", L("Encode a recording"), - "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it " - "needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names " - "one, and writes beside it unless `save_path` says where. A long encode returns a job: `app_wait` waits for it, or `job_cancel {job}` " - "stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless `keep_raw_video_file`; " - "any other .mkv is kept. `raw_video_file_deleted` in the reply says which.", - object_schema({{"path", prop("string", "Absolute .mkv of a finished recording; default this session's last.")}, - {"save_path", prop("string", "Absolute .mp4 path; default the recording's, with .mp4.")}, - {"overwrite", prop("boolean", "Replace an existing `save_path`.")}, - {"codec", enum_prop({"h265", "h264"}, "Default h265.")}, - {"crf", int_prop(0, 51, "Constant rate factor, lower is better and larger (default 28 for h265, 23 for h264).")}, - {"speed", enum_prop(encoder_speeds(), "The encoder's preset: slower makes a smaller file of the same quality (default medium).")}, - {"profile", enum_prop({"high", "main", "baseline", "main10"}, - "h264: high, main or baseline; h265: main, or main10 for 10 bits per sample. Default the " - "encoder's (high, main).")}, - {"keep_raw_video_file", prop("boolean", "Keep the .mkv beside the MP4 (default false: a recording this " - "session made is deleted once the MP4 is written).")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - const std::shared_ptr& files = runtime.recorder().files(); - std::string err; - fs::path source; - if (args.contains("path")) { - auto p = resolve_input_path(arg_string(args, "path"), err); - if (!p) - throw ToolFailure(err); - source = *p; - } else if (auto last = files->last_finished()) { - source = *last; - } else { - throw ToolFailure("No recording of this session has finished; give path"); - } - if (!boost::algorithm::iends_with(path_to_utf8(source), ".mkv")) - throw ToolFailure("path must be a .mkv recording"); - if (boost::system::error_code ec; !fs::is_regular_file(source, ec)) - throw ToolFailure("No such recording: " + path_to_utf8(source)); - - const bool overwrite = arg_bool(args, "overwrite", false); - fs::path dest; - if (args.contains("save_path")) { - auto p = resolve_output_path(arg_string(args, "save_path"), overwrite, err); - if (!p) - throw ToolFailure(err); - dest = *p; - } else { - dest = source; - dest.replace_extension(".mp4"); - if (boost::system::error_code ec; fs::exists(dest, ec) && !overwrite) - throw ToolFailure(path_to_utf8(dest) + " exists; set overwrite or give save_path"); - } - if (RecordingFiles::same_file(source, dest)) - throw ToolFailure("save_path is the recording itself"); - // The .mkv goes once the MP4 is written unless it is to be kept, and only a recording this session made: - // any other .mkv is the person's own file, so it stays. - const bool keep_asked = arg_bool(args, "keep_raw_video_file", false); - const bool ours = files->is_finished(source); - const bool remove = !keep_asked && ours; - - const std::string codec = arg_string(args, "codec", "h265"); - const std::string encoder = encoder_for(codec); - const int crf = arg_int(args, "crf", codec == "h265" ? 28 : 23); - const std::string profile = arg_string(args, "profile", ""); - if (const std::vector profiles = codec_profiles(codec); - !profile.empty() && std::find(profiles.begin(), profiles.end(), profile) == profiles.end()) - throw ToolFailure(codec + " has no " + profile + " profile"); - const auto ffmpeg = find_ffmpeg(err); - if (!ffmpeg) - throw ToolFailure(err); - - const uint64_t owner = files->new_owner(); - if (const std::string why = files->reserve(owner, {{source, remove ? RecordingFiles::Use::ExclusiveSource : RecordingFiles::Use::Source}, - {dest, RecordingFiles::Use::Destination}}); - !why.empty()) - throw ToolFailure("Cannot encode now: " + why); - // Every file this call makes is its own, so failing or a cancel removes only those. - const std::string tag = "." + std::to_string(process_id()) + "-" + std::to_string(owner); - const fs::path part = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".part").native()); - const fs::path log = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".log").native()); - const fs::path probe = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".probe").native()); - struct Cleanup - { - RecordingFiles& files; - uint64_t owner; - std::vector paths; - bool release = true; - ~Cleanup() - { - for (const fs::path& p : paths) - remove_quietly(p); - if (release) - files.release(owner); - } - } cleanup{*files, owner, {part, log, probe}}; - const auto cancelled = [&ctx] { return ctx.cancelled(); }; - - // What this ffmpeg is: the options that keep the timing depend on its version, and the encoder - // must be built in. - auto listing = [&](const char* what) { - const ProcessOutcome r = run_process(*ffmpeg, {"-hide_banner", what}, probe, {}, cancelled, std::chrono::seconds(20)); - if (ctx.cancelled()) - throw ToolFailure("The encode was cancelled"); - if (!r.started || r.timed_out || r.exit_code != 0) - throw ToolFailure("Cannot run " + path_to_utf8(*ffmpeg) + " " + what); - return read_text(probe); - }; - const FfmpegVersion version = parse_ffmpeg_version(listing("-version")); - if (parse_encoders(listing("-encoders")).count(encoder) == 0) - throw ToolFailure(path_to_utf8(*ffmpeg) + " has no " + encoder + - " encoder. Install an ffmpeg built with it (Homebrew, winget Gyan.FFmpeg, Debian/Ubuntu ffmpeg) or " - "point ORCA_FFMPEG at one"); - - EncodeSpec spec; - spec.input = path_to_utf8(source); - spec.output = path_to_utf8(part); - spec.codec = codec; - spec.crf = crf; - spec.speed = arg_string(args, "speed", "medium"); - spec.profile = profile; - ProcessOutcome run; - // A build whose version is unknown may refuse the current spelling of the timing options: the next. - const std::vector timings = timing_candidates(version); - for (std::size_t i = 0; i < timings.size(); ++i) { - spec.timing = timings[i]; - run = run_process(*ffmpeg, encode_args(spec), {}, log, cancelled, std::chrono::hours(4)); - const bool refused = run.started && run.gone && !run.cancelled && !run.timed_out && run.exit_code != 0 && - refused_timing_option(file_tail(log, 6)); - if (!refused || i + 1 == timings.size()) - break; - } - if (!run.gone) { - // It may still read the source and write its files: they are left for it, and the source and - // destination stay reserved for the session, so no later encode deletes or writes them under it. - cleanup.paths = {probe}; - cleanup.release = false; - throw ToolFailure("ffmpeg did not exit after it was stopped; " + path_to_utf8(part) + " and " + path_to_utf8(log) + - " are left, and " + path_to_utf8(source) + " stays in use until OrcaSlicer restarts"); - } - if (run.cancelled) - throw ToolFailure("The encode was cancelled"); - if (!run.started) - throw ToolFailure("Cannot run " + path_to_utf8(*ffmpeg)); - if (run.timed_out || run.exit_code != 0) { - const std::string tail = file_tail(log, 6); - throw ToolFailure(run.timed_out ? "ffmpeg did not finish within 4 hours" : - "ffmpeg failed" + (tail.empty() ? std::string() : ":\n" + tail)); - } - const double seconds = mp4_duration(part).value_or(0.); - - boost::system::error_code ec; - if (!overwrite && fs::exists(dest, ec)) - throw ToolFailure(path_to_utf8(dest) + " appeared while encoding; set overwrite to replace it"); - fs::rename(part, dest, ec); // replaces an existing file on every platform - if (ec) - throw ToolFailure("Cannot write " + path_to_utf8(dest) + ": " + ec.message()); - if (remove && fs::remove(source, ec)) - files->forget(source); - const uintmax_t size = fs::file_size(dest, ec); - json out{{"path", path_to_utf8(dest)}, - {"source", path_to_utf8(source)}, - {"codec", codec}, - {"encoder", encoder}, - {"seconds", std::round(seconds * 10.) / 10.}, - {"size_bytes", ec ? 0 : size}}; - out["raw_video_file_deleted"] = remove && !fs::exists(source, ec); - if (!keep_asked && !ours) - out["note"] = "The .mkv was kept: an encode deletes only a recording this session made"; - return ToolResult::ok(out); - }); - encode.cancellable = true; - catalog.add(encode); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp b/src/slic3r/GUI/Mcp/McpToolsReplay.cpp deleted file mode 100644 index eb00e87684..0000000000 --- a/src/slic3r/GUI/Mcp/McpToolsReplay.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// replay_run and replay_export: deterministic replays of tool calls, and turning a session into one. - -#include "JobRegistry.hpp" -#include "slic3r/GUI/CommandCatalog.hpp" -#include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "McpJournal.hpp" -#include "McpPaths.hpp" -#include "McpRecorder.hpp" -#include "McpReplay.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Slic3r { namespace GUI { namespace Mcp { - -using nlohmann::json; -namespace fs = boost::filesystem; - -namespace { - -std::string read_file(const fs::path& path) -{ - boost::nowide::ifstream in(path_to_utf8(path).c_str(), std::ios::binary); - if (!in) - throw ToolFailure("Cannot read " + path_to_utf8(path)); - std::ostringstream ss; - ss << in.rdbuf(); - return ss.str(); -} - -void write_file(const fs::path& path, const std::string& text) -{ - boost::nowide::ofstream out(path_to_utf8(path).c_str(), std::ios::binary | std::ios::trunc); - out << text; - if (!out) - throw ToolFailure("Cannot write " + path_to_utf8(path)); -} - -std::string timestamp() -{ - const std::time_t t = std::time(nullptr); - char buf[32]; - std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", std::localtime(&t)); - return buf; -} - -// An invalid replay is a tool error flagged `invalid`, which --run turns into exit code 2. -ToolResult invalid(const std::string& message) { return ToolResult::error("Invalid replay: " + message, {{"invalid", true}}); } - -} // namespace - -json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options) -{ - boost::system::error_code ec; - fs::create_directories(sctx.out_dir, ec); - if (ec) - throw ToolFailure("Cannot create " + path_to_utf8(sctx.out_dir) + ": " + ec.message()); - - const std::string job = ctx.job_id(); - runtime.begin_run_scope(job); - struct ScopeEnd - { - AutomationRuntime& runtime; - std::string job; - bool recording_waited = false; // the run below waited for the replay's recording already - ~ScopeEnd() { runtime.end_run_scope(job, !recording_waited); } - } scope_end{runtime, job}; - - const auto stopped = [&ctx] { return ctx.cancelled(); }; - - ReplayHost host; - host.call = [&ctx](const std::string& tool, const json& a) { return ctx.call_child(tool, a); }; - host.wait_job = [&runtime, &stopped](const std::string& id, int timeout_s) { - return runtime.jobs().wait(id, std::chrono::seconds(timeout_s), stopped); - }; - host.cancelled = stopped; - host.step_started = options.step_started; - host.step_finished = options.step_finished; - host.open_dialogs = [&runtime] { return runtime.ui().open_dialogs(); }; - - json result = run_replay(replay, sctx, host, options.only_step); - // A recording the replay started ends with it, its file closed before the result is written; one still - // being written after the wait is named, since an encode of it would fail. - std::optional unfinished = runtime.recorder().end_owned_by(job, "run_ended", true); - scope_end.recording_waited = true; - if (unfinished) - result["unfinished_recording"] = *unfinished; - result["out_dir"] = path_to_utf8(sctx.out_dir); - if (options.write_result) { - const fs::path file = sctx.out_dir / "result.json"; - write_file(file, result.dump(2)); - result["result_file"] = path_to_utf8(file); - } - return result; -} - -void register_replay_tools(CommandCatalog& catalog) -{ - NativeCommand run = mutate_tool( - "replay_run", L("Run a replay"), - std::string("Replay a list of tool calls in order and report each step: `{\"orca_replay_version\": \"") + - REPLAY_VERSION + - "\", name, vars, steps: [{tool, args, expect, optional, await, save_as, timeout_s}]}`, JSON with comments. " - "Strings may use `${replay_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and `${jobs.NAME}`. A step that " - "returns a job is awaited unless `await: false`, which stores the job under `save_as` so later steps can answer " - "the dialog it opened. `expect` maps a JSON pointer into the step's result to matchers (`eq` `ne` `gt` `ge` `lt` " - "`le` `contains` `regex` `exists` `empty`); the first failed step or expectation stops the run unless the step is " - "`optional`. Writes `result.json` to `out_dir` (default: a new folder `replay-` in " - "`orca_action_replay` in the temp folder, or in the `--outputdir` folder of a `--run` launch). Reply: `passed`, " - "`steps`, `failed_step`, `out_dir` and `result_file`. `dialog_auto_answer` rules a replay registers end with it. " - "`replay_export` turns this session into one.", - object_schema({{"path", prop("string", "Absolute path of a replay file.")}, - {"replay", {{"type", json::array({"object", "string"})}, - {"description", "The replay itself, as an object or as its JSON text, instead of `path`."}}}, - {"out_dir", prop("string", "Absolute directory for result.json and screenshots; created if missing.")}, - {"vars", {{"type", "object"}, {"description", "Values that override the replay's vars."}}}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - const bool has_path = args.contains("path"), has_replay = args.contains("replay"); - if (has_path == has_replay) - return invalid("give exactly one of path and replay"); - - std::optional replay; - ReplayContext sctx; - std::string err; - if (has_path) { - const auto path = resolve_input_path(arg_string(args, "path"), err); - if (!path) - return invalid(err); - std::string text; - try { - text = read_file(*path); - } catch (const ToolFailure& f) { - return invalid(f.what()); - } - replay = parse_replay(text, err); - sctx.replay_dir = path->parent_path(); - } else - replay = parse_replay(inline_replay_text(args["replay"]), err); - if (!replay) - return invalid(err); - for (const ReplayStep& step : replay->steps) - if (NativeCommands::instance().lookup(step.tool) == nullptr) - return invalid("unknown tool " + step.tool); - if (args.contains("vars")) - for (const auto& [key, value] : args["vars"].items()) - replay->vars[key] = value; - - sctx.out_dir = args.contains("out_dir") ? path_from_utf8(arg_string(args, "out_dir")) : replay_output_dir(); - if (!sctx.out_dir.is_absolute()) - return invalid("out_dir must be an absolute path"); - if (!has_path) - sctx.replay_dir = sctx.out_dir; - json result = run_replay_job(runtime, ctx, *replay, sctx, ReplayRunOptions{}); - return ToolResult::ok(std::move(result)); - }); - // Its steps call any tool, script_run included. - run.open_world = true; - catalog.add(run); - - NativeCommand exp = inspect_tool( - "replay_export", L("Export this session as a replay"), - "Turn the calls this session made into a replay that `replay_run` runs: mutating calls, `app_wait`, `window_screenshot` and the " - "recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and `window_screenshot` " - "and recording paths moved under `${out_dir}`. " - "Calls that failed, at once or as a job later, are left out (a `script_run` that raised or timed out replied, so it " - "stays); so is a call whose job is still running (unless it " - "waits on a dialog), which `left_out_running` lists as `{tool, job}`. " - "Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.", - object_schema({{"name", prop("string", "Replay name.")}, - {"path", prop("string", "Absolute .json path to write.")}, - {"overwrite", prop("boolean", "Replace an existing file.")}, - {"clear", prop("boolean", "Forget the calls recorded so far once exported.")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - if (!ctx.caller_plugin().empty()) - throw ToolFailure("replay_export exports the agent's session, which a plugin's calls are not part of"); - json running; - json replay = runtime.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running); - json out{{"steps", replay["steps"].size()}}; - if (!running.empty()) - out["left_out_running"] = std::move(running); - if (args.contains("path")) { - std::string err; - const auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); - if (!path) - throw ToolFailure(err); - write_file(*path, replay.dump(2)); - out["path"] = path_to_utf8(*path); - } - if (arg_bool(args, "clear", false)) - runtime.journal().clear(); - out["replay"] = std::move(replay); - return ToolResult::ok(std::move(out)); - }); - exp.read_only = false; - // clear empties the journal, so a second call exports less. - exp.idempotent = false; - catalog.add(exp); -} - -}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/Tools/AppTools.cpp similarity index 63% rename from src/slic3r/GUI/Mcp/McpToolsApp.cpp rename to src/slic3r/GUI/Mcp/Tools/AppTools.cpp index 5821942039..7fa5a69122 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/Tools/AppTools.cpp @@ -1,73 +1,94 @@ -// app_state, app_wait and app_log: what an agent reads before and after acting; undo and redo; and the app's -// commands made from the Help menu's items. +// The place The app: app_state, app_wait and app_log, what an agent reads before and after acting; undo and redo; +// job_cancel; the app's commands made from the Help menu's items; and preferences_get and preferences_set, the +// app's preferences as the Preferences dialog shows them, read from and written through the table of +// GUI/Operations/PreferenceOps.hpp, which the dialog builds its rows from too. -#include "JobRegistry.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "McpEndpoint.hpp" -#include "McpPaths.hpp" -#include "McpRecorder.hpp" -#include "libslic3r/Config.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" -#include "ModalTracker.hpp" -#include "PythonScriptsDialog.hpp" -#include "ScreenCapture.hpp" -#include "UiInspector.hpp" -#include "WindowControl.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/McpRecorder.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" +#include "slic3r/GUI/Mcp/ScreenCapture.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/Mcp/WindowControl.hpp" +#include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Notebook.hpp" #include "slic3r/GUI/NotificationManager.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PreferenceOps.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/PrintHostDialogs.hpp" +#include "slic3r/GUI/Selection.hpp" +#include "slic3r/plugin/PythonInterpreter.hpp" +#include "slic3r/Utils/bambu_networking.hpp" #include "slic3r/Utils/CloudProvider.hpp" #include "slic3r/Utils/NetworkAgent.hpp" -#include "slic3r/Utils/bambu_networking.hpp" -#include "slic3r/plugin/PythonInterpreter.hpp" -#ifdef SLIC3R_CAD -#include "McpToolsCad.hpp" -#endif -#if defined(__WXGTK__) -#include "slic3r/GUI/LinuxDisplayBackend.hpp" -#endif +#include "slic3r/Utils/UndoRedo.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/Config.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/Utils.hpp" #include "libslic3r_version.h" -#include -#include - #include #include #include #include -#include +#include + +#include +#include + +#include #include #include #include +#include +#include #include +#include +#include #include -#include +#include +#include #include +#include #include #include #include +#ifdef SLIC3R_CAD +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#endif + +#if defined(__WXGTK__) +#include "slic3r/GUI/LinuxDisplayBackend.hpp" +#endif + namespace Slic3r { namespace GUI { namespace Mcp { using nlohmann::json; @@ -314,6 +335,139 @@ std::vector log_tail(std::istream& in, const std::string& min_level return out; } +namespace { + +const char* kind_name(Ops::PreferenceKind kind) +{ + switch (kind) { + case Ops::PreferenceKind::Checkbox: return "checkbox"; + case Ops::PreferenceKind::Choice: return "choice"; + case Ops::PreferenceKind::Number: return "number"; + case Ops::PreferenceKind::Text: return "text"; + } + return "text"; +} + +// A bound of a number's range, whole where the row takes whole numbers. +json bound(const Ops::Preference& p, double value) +{ + if (p.decimals == 0) + return std::int64_t(value); + return value; +} + +// What a call learns of `p`'s refusal to be written: its reason, in English. +std::string refused_reason(const Ops::Preference& p) +{ + return Ops::Refusal{Ops::RefusalKind::Precondition, "preference_refused", p.refused, {p.key}}.english(); +} + +// preferences_get's item for `p`: its row, and the value the dialog shows: `shown` where the dialog shows a value of its +// own (Ops::shown_texts()), else the stored one, else the fallback. +json preference_item(const AppConfig& config, const Ops::Preference& p, const std::map& shown) +{ + std::string stored; + const bool is_stored = config.get("app", p.key, stored); + const auto own = shown.find(p.key); + const std::string text = own != shown.end() ? own->second : is_stored ? stored : p.fallback; + json item{{"key", p.key}, {"tab", p.tab}, {"section", p.section}, + {"label", p.label}, {"kind", kind_name(p.kind)}, + {"value", Ops::preference_value(p, text)}}; + if (!p.choices.empty()) { + json choices = json::array(); + for (const auto& [value, label] : p.choices) + choices.push_back({{"value", value}, {"label", label}}); + item["choices"] = std::move(choices); + } + if (p.min) + item["min"] = bound(p, *p.min); + if (p.max) + item["max"] = bound(p, *p.max); + if (!is_stored) + item["stored"] = false; + if (p.restart_needed) + item["restart_needed"] = true; + if (p.refused != nullptr) + item["refused"] = refused_reason(p); + return item; +} + +// What preferences_set replies when the operation refuses: the names the refusal carries under the key that says what +// they are, and where a refused preference changes instead. +ToolFailure preferences_refused(const Ops::Refusal& refusal, const std::vector& table) +{ + const std::string code = refusal.code; + if (code == "not_a_preference") + return refused(refusal, "preferences_get lists the Preferences dialog's preferences.", "similar"); + if (code == "no_such_choice") + return refused(refusal, "", "choices"); + if (code == "out_of_range") + return refused(refusal, "", "range"); + if (code == "preference_refused" && !refusal.args.empty()) + if (const Ops::Preference* p = Ops::find_preference(table, refusal.args.front())) + return refused(refusal, "It changes in the Preferences dialog: window_open {\"window\": \"preferences\", \"tab\": \"" + p->tab + + "\", \"key\": \"" + p->key + "\"}, then widget_set_value on the control named " + p->key + + " within Preferences.", + "keys"); + return refused(refusal); +} + +// preferences_set's reply: each preference changed, with its value before and after, typed as preferences_get gives it, +// stored_before: false where `before` is the fallback, restart_needed where the value is read at the next start; and +// those already so. +json changes_json(const Ops::PreferenceChanges& changes, const std::vector& table) +{ + json changed = json::array(); + for (const Ops::PreferenceChange& c : changes.changed) { + const Ops::Preference& p = *Ops::find_preference(table, c.key); + json item{{"key", c.key}, {"before", Ops::preference_value(p, c.before)}, {"after", Ops::preference_value(p, c.after)}}; + if (!c.stored_before) + item["stored_before"] = false; + if (p.restart_needed) + item["restart_needed"] = true; + changed.push_back(std::move(item)); + } + return {{"changed", std::move(changed)}, {"unchanged", changes.unchanged}}; +} + +} // namespace + +json preferences_settings(const AppConfig& config, const std::vector& shown, const json& args, + const std::map& shown_texts) +{ + const std::string tab = arg_string(args, "tab"); + std::vector asked; + if (args.contains("keys")) + for (const json& key : args["keys"]) + asked.push_back(key.get()); + const auto named = [&asked](const std::string& key) { return std::find(asked.begin(), asked.end(), key) != asked.end(); }; + const auto matches = [&](const Ops::Preference& p) { + return (tab.empty() || p.tab == tab) && (!args.contains("keys") || named(p.key)); + }; + + json items = json::array(), unknown = json::array(); + for (const Ops::Preference& p : shown) + if (matches(p)) + items.push_back(preference_item(config, p, shown_texts)); + // A named key the dialog does not show is read as the app configuration stores it. + for (const std::string& key : asked) { + if (Ops::find_preference(shown, key) != nullptr) + continue; + std::string value; + if (config.get("app", key, value)) + items.push_back({{"key", key}, {"value", value}}); + else + unknown.push_back(key); + } + json out{{"total", items.size()}, {"items", std::move(items)}}; + if (!unknown.empty()) { + out["unknown_keys"] = std::move(unknown); + // Some preferences are stored only once they are changed. + out["note"] = "unknown_keys are not stored and are no preference the Preferences dialog shows now."; + } + return out; +} + void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad) { catalog.add(inspect_tool( @@ -426,10 +580,7 @@ void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad) command.run = [picked, automated = std::move(command.run)](const json& args, ToolContext& ctx) { return ctx.person() ? picked(args, ctx) : automated(args, ctx); }; - command.has_own_action = true; - command.action_group = L("Commands"); - command.icon = std::move(icon); - return command; + return own_action(std::move(command), L("Commands"), std::move(icon)); }; NativeCommand undo = history_command( "undo", L("Undo"), "menu_undo", @@ -511,17 +662,123 @@ void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad) benchmark)}), [](const json&) { return MenuItems::benchmark_3d_scene(); })); - // The Agent Activity pane's menu item, which has no argument form. - const std::string activity = "Show or hide the Agent Activity pane, where a person watches what agents, Action Replay, Run Script, " - "the command line's run and plugins do in the app, call by call. It is the person's: it lists your " - "calls, and you never need it."; - NativeCommand toggle_activity = menu_command("view_toggle_activity_panel", L("Agent Activity"), activity, object_schema({}), - json::array({action("toggle_agent_activity_panel", L("Agent Activity"), L("View"), "", - json::object(), activity)}), - [](const json&) { return MenuItems::toggle_agent_activity_panel(); }); - // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. - toggle_activity.listed = false; - catalog.add(std::move(toggle_activity)); + catalog.add(inspect_tool( + "preferences_get", L("Read preferences"), + "Read the app's preferences as the Preferences dialog shows them. With no argument, every preference it shows, " + "tab by tab in its order, each with key (its control is named after it), tab, section and label (the row's title, " + "in English), kind (checkbox, choice, number or text), value (what the dialog shows: `true` or `false` for a checkbox, " + "a number for a number field), a choice's choices (`{value, label}`; `preferences_set` takes the value), a number's " + "min and max, `stored: false` where nothing is stored and the value is the one the dialog shows then, " + "`restart_needed: true` for a preference read at the next start, which a write changes nothing before, and " + "refused, the reason, for a preference `preferences_set` does not write. The MCP server's switch and port read as " + "the dialog shows them: on while the server runs, and the port it is on, also where this session's launch " + "arguments set them without storing them; their stored says whether a value is stored. keys and tab narrow " + "the list together; a " + "named key the dialog does not show is read as the app configuration stores it (`{key, value}`), and one that is " + "neither is listed under `unknown_keys`. The app configuration also holds account and device state, which is read " + "only by name.", + object_schema({{"keys", array_prop({{"type", "string"}}, "Preference keys, e.g. [\"project_load_behaviour\"].")}, + {"tab", enum_prop({"general", "files", "behaviour", "control", "graphics", "online", "developer"}, + "The dialog's tab, as `window_open` names it.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return preferences_settings(*wxGetApp().app_config, Ops::shown_preferences(), args, Ops::shown_texts()); + })); + })); + + NativeCommand write = reaching( + {"set_preferences"}, + mutate_tool( + "preferences_set", L("Change preferences"), + "Change preferences as their controls in the Preferences dialog do: values `{key: value}`, a checkbox as true or " + "false, a choice as one of its values, a number within its range, as `preferences_get` lists them, and the " + "downloads folder (`download_path`) as the absolute path of an existing folder. All are checked first and written " + "together, so nothing changes if one is refused; then each does what its control does in the app, in the keys' " + "order (the preview redrawn, the sidebar's lists, the settings' mode, the theme, preset sync started or " + "stopped, stealth mode's sign-out of the cloud accounts), and those `preferences_get` marks `restart_needed` are " + "stored and take effect at the next start. A key whose value is already the one given is left as it is. " + "Refused, by name and with the reason: a key the dialog does not show, and those `preferences_get` marks " + "refused, whose control opens a dialog, restarts OrcaSlicer, signs out, or reaches outside it (the language, " + "the login region, the network plug-in, file associations, the mixed-temperature warning, the MCP server's " + "switch and port); those change in the dialog: `window_open {\"window\": \"preferences\", \"tab\", " + "\"key\"}`, then `widget_set_value`. Not in the undo history. Reply: changed, [`{key, before, after}`] typed as " + "`preferences_get` gives them, with `stored_before: false` where nothing was stored and before is the value the " + "dialog showed, and `restart_needed: true` where `preferences_get` gives it; and unchanged, the keys already so.", + object_schema({{"values", {{"type", "object"}, + {"description", "`{key: value}`, e.g. `{\"auto_arrange\": false, \"auto_calculate_flush\": " + "\"color change\"}`."}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { + const json values = args.value("values", json::object()); + if (values.empty()) + throw ToolFailure("values names no preference: give {key: value}, e.g. {\"auto_arrange\": false}"); + std::map asked; + for (const auto& [key, value] : values.items()) + asked[key] = value; + json result = ctx.run_ui([&]() -> json { + ui_plater(); + const std::vector table = Ops::shown_preferences(); + const Ops::Outcome done = Ops::set_preferences(asked); + if (!done) + throw preferences_refused(done.refusal(), table); + return changes_json(done.value(), table); + }); + settle(ctx); + return ToolResult::ok(result); + })); + write.examples = json::parse(R"json([ + {"title": "Read the Behaviour tab's preferences and turn one off", "calls": [ + {"tool": "preferences_get", "args": {"tab": "behaviour"}}, + {"tool": "preferences_set", "args": {"values": {"auto_arrange": false}}}]}, + {"title": "Set a choice and a number", "calls": [ + {"tool": "preferences_set", "args": {"values": {"auto_calculate_flush": "color change", "opengl_fps_cap": 60}}}]}])json"); + catalog.add(std::move(write)); + + NativeCommand cancel = mutate_tool( + "job_cancel", L("Cancel a job"), + "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button does, or a " + "background job an MCP call started (an arrange, orient or fill bed). Its job then reports cancelled; a background " + "job keeps other changes out until it has really stopped. With job, only that job is stopped: the running " + "operation, an `object_fix`, a `script_run` run or a `recording_encode`. Allowed while an operation holds the project. Reply: " + "`was_running`, and job when one was stopped.", + object_schema({{"job", prop("string", "The operation's job to cancel, e.g. \"j12\".")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + const auto ops = runtime.jobs().running_operations(); + // A plugin stops only what its own calls started, so it names the job. + if (!ctx.caller_plugin().empty() && !args.contains("job")) + throw ToolFailure("A plugin cancels only the jobs of its own calls: give the job"); + if (args.contains("job")) + require_own_job(ctx, runtime.jobs(), arg_string(args, "job"), "cancels"); + if (args.contains("job")) { + const std::string job = arg_string(args, "job"); + if (std::find(ops.begin(), ops.end(), job) == ops.end()) { + // A call that is no operation but can be stopped: its handler watches for the stop. + const NativeCommand* def = NativeCommands::instance().find(runtime.jobs().running_tool(job)); + if (def == nullptr || !def->cancellable) + throw ToolFailure("Job " + job + " is not a running operation", {{"running", ops}}); + runtime.jobs().request_stop(job); + return ToolResult::ok({{"was_running", true}, {"job", job}}); + } + } + json out = ctx.run_ui([&]() -> json { + // Only a job an MCP call started: a person's (Text typing) is theirs to stop. + for (const std::string& op : ops) + if ((!args.contains("job") || op == arg_string(args, "job")) && runtime.core().cancel_worker(op)) + return {{"was_running", true}, {"job", op}}; + Plater& plater = ui_plater(); + // A slice operation still waiting to request its slice counts: the cancel keeps it from starting. + const bool running = plater.is_slicing_any() || !ops.empty(); + plater.cancel_slicing(); + return json{{"was_running", running}}; + }); + return ToolResult::ok(out); + }); + cancel.allowed_during_operation = true; + // Recovery: it must get through a dialog the operation opened and another call's nested loop. + cancel.guard = GuardClass::Recover; + catalog.add(cancel); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/Tools/CatalogTools.cpp similarity index 72% rename from src/slic3r/GUI/Mcp/McpToolsApi.cpp rename to src/slic3r/GUI/Mcp/Tools/CatalogTools.cpp index 7169832239..082890964d 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/Tools/CatalogTools.cpp @@ -1,16 +1,21 @@ -// tool_list, tool_describe and tool_call: a way to every command of the catalog, those tools/list does not show among -// them: the menu items that take no arguments, the Design tab's commands and the operations plugins offer -// (plugin..). tool_list lists those, tool_describe gives any command's manual, built from its schema, and -// tool_call runs any of them. - -#include "McpArguments.hpp" -#include "McpTools.hpp" +// The place Tools and actions: tool_list, tool_describe and tool_call, a way to every command of the catalog, those +// tools/list does not show among them: the menu items that take no arguments, the Design tab's commands and the +// operations plugins offer (plugin..). tool_list lists those, tool_describe gives any command's manual, +// built from its schema, and tool_call runs any of them. action_list and action_run: every Speed Dial action +// (built-in commands, plates, recent projects, plugin scripts and pages, and on request settings) is listed and run +// through these two. +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpPersonContext.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/ActionIds.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/PluginOperations.hpp" @@ -170,7 +175,9 @@ json unlisted_commands(const CommandCatalog& catalog, const std::string& group) namespace { ParameterClass source(std::vector tools) { return {ParameterClass::Source, std::move(tools)}; } + const ParameterClass kDescribed{ParameterClass::Described, {}}; + const ParameterClass kFree{ParameterClass::Free, {}}; // The classes of a command's own parameters, which come before a name's: a name that means something else there, or @@ -647,7 +654,163 @@ void register_plugin_operations(CommandCatalog& catalog) catalog.add_source(std::make_unique()); } -void register_api_tools(CommandCatalog& catalog, const std::string& design_index) +namespace { + +ActionRegistry& registry_or_fail() +{ + ActionRegistry* reg = wxGetApp().m_action_registry.get(); + if (reg == nullptr) + throw ToolFailure("The action catalog is not available yet; app_wait {for:\"ready\"} first"); + return *reg; +} + +// The name inside a "::" id (view_front in orca_command:view_front:orca), which +// is what agents and the tools' own messages call an action. +std::string short_id(const std::string& id) +{ + const std::size_t first = id.find(':'), last = id.rfind(':'); + return first == std::string::npos || first == last ? id : id.substr(first + 1, last - first - 1); +} + +// The action `id` names: its full id, or a name only one action has, among the actions of the app's state now +// (find_live(): the call before may have opened a sketch, added a plate or switched the tab). Otherwise +// ToolFailure with the ids closest to it, scored against both forms, a name containing it (delete_all in +// obj_delete_all) counting as closest. +const AppAction& find_action(ActionRegistry& actions, std::string& id) +{ + if (const AppAction* action = actions.find_live(id)) + return *action; + ActionRegistry::Query q; + q.limit = 100000; + std::vector named; + std::vector> scored; + const json all = actions.describe(q); + for (const json& a : all["items"]) { + const std::string candidate = a["id"]; + const std::string name = short_id(candidate); + if (name == id) + named.push_back(candidate); + const bool contains = id.size() >= 3 && name.find(id) != std::string::npos; + scored.emplace_back(contains ? 0 : std::min(edit_distance(id, candidate), edit_distance(id, name)), candidate); + } + if (named.size() == 1) { + id = named.front(); + return *actions.by_id(id); + } + std::sort(scored.begin(), scored.end()); + json similar = json::array(); + for (std::size_t i = 0; i < scored.size() && similar.size() < 3 && scored[i].first <= id.size() / 3 + 2; ++i) + similar.push_back(scored[i].second); +#ifdef SLIC3R_CAD + const bool cad_on = wxGetApp().is_enable_cad_feature(); +#else + const bool cad_on = false; +#endif + ToolFailure refused = unknown_action(id, NativeCommands::instance(), cad_on); + refused.details["similar"] = std::move(similar); + throw refused; +} + +} // namespace + +std::string action_args_error(const AppAction& action, const json& args) +{ + // An action that collects a value takes that value alone, as the Speed Dial's second phase gives it. + if (!action.input.empty()) + return args.is_object() && args.size() == 1 && args.contains(action.input) ? + std::string() : + "The action " + action.id() + " takes exactly its " + action.input + ": run it with args {\"" + action.input + + "\": ...} (its input_schema)"; + if (person_form(args)) + return {}; + // A command's action runs its command with the action's arguments, which it takes as well as none; other arguments + // are the command's to take. + if (!action.preset.is_null()) { + if (args == action.preset) + return {}; + if (action.preset.empty()) + return "The action " + action.id() + " takes no arguments: run it without args, or call " + action.command + + " with them"; + return "The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() + + ": run it without args or with exactly those, or call " + action.command + " with other arguments"; + } + // A Design command's own action takes the command's arguments, which the command checks. + if (!action.command.empty()) + return {}; + return "The action " + action.id() + " takes no arguments: run it without args"; +} + +json action_journal_args(const AppAction& action, const json& args) +{ + if (action.preset.is_null()) + return nullptr; + return action.input.empty() ? action.preset : args; +} + +ToolFailure unknown_action(const std::string& id, const CommandCatalog& catalog, bool cad_on) +{ + // A Design tab action is in the registry only while it is live (ActionRegistry::materialize_design_actions()), which + // none is while the CAD feature is off; its command is in the catalog, unless the catalog was built without the + // Design commands. Its id is right then, and the code says what keeps it from running. + const std::string action_id = id.find(':') != std::string::npos ? id : AppAction::compose_id(kCommandPrefix, id, kOrcaSourceKey); + if (is_design_action_id(action_id)) { + const std::string key = short_id(action_id); + if (const std::string* why = catalog.left_out(key)) + return ToolFailure(id + " is a Design tab action, and " + *why, {{"code", catalog.unknown_command_code(key)}}); + if (!cad_on) + return ToolFailure(id + " is a Design tab action, and the CAD feature is off: a person enables it in Preferences > " + "Features and restarts OrcaSlicer", + {{"code", "design_unavailable"}}); + // A folded item's action is a call of the command it is folded into with the item's arguments, written as the + // rest of the call is, a space after each colon and comma. + const auto [command, folded] = find_command_action(catalog, short_id(action_id)); + std::string call = "{\"tool\": \"" + (command != nullptr ? command->key : short_id(action_id)) + "\""; + if (folded != nullptr && !folded->at("args").empty()) { + std::string args; + for (const auto& [name, value] : folded->at("args").items()) + args += (args.empty() ? "" : ", ") + json(name).dump() + ": " + value.dump(); + call += ", \"args\": {" + args + "}"; + } + return ToolFailure(id + " is a Design tab action, there only while the Design tab is shown in its mode (a sketch's or " + "the model's) with the CAD feature on; tool_call " + call + "} runs its command from any tab", + {{"code", "wrong_mode"}}); + } + // The name may be a command's that has no action, which tool_call runs. + return ToolFailure("Unknown action id " + id + "; find an action with action_list, or a command in tools/list or with tool_list", + {{"code", "invalid_argument"}}); +} + +namespace { + +// What `actions` lists for `q`. A section no action is in now is a name to correct, refused with the sections there +// are, as tool_list refuses a group. Recent Projects and Design hold actions only while there are recent projects +// and while the Design tab is shown, so either one empty is an answer, not a wrong name. +json described(ActionRegistry& actions, const ActionRegistry::Query& q) +{ + json listed = actions.describe(q); + if (q.section.empty() || listed.value("total", 0) != 0) + return listed; + for (const char* comes_and_goes : {"Recent Projects", kDesignGroup}) + if (boost::algorithm::iequals(q.section, comes_and_goes)) + return listed; + ActionRegistry::Query every; + every.include_settings = q.include_settings; + every.limit = 100000; + const json all = actions.describe(every); + json sections = json::array(); + std::string names; + for (const json& item : all["items"]) + if (std::find(sections.begin(), sections.end(), item["section"]) == sections.end()) { + sections.push_back(item["section"]); + names += (names.empty() ? "" : ", ") + item["section"].get(); + } + throw ToolFailure("Unknown section: " + q.section + "; the Speed Dial's sections now are " + names, + {{"code", "invalid_argument"}, {"sections", std::move(sections)}}); +} + +} // namespace + +void register_catalog_tools(CommandCatalog& catalog, const std::string& design_index) { // Its description ends with `design_index`: the Design commands' names, in a catalog that holds them. catalog.add(inspect_tool( @@ -698,6 +861,89 @@ void register_api_tools(CommandCatalog& catalog, const std::string& design_index // It calls any tool, script_run included, and plugin code. call.open_world = true; catalog.add(call); + + catalog.add(inspect_tool( + "action_list", L("List Speed Dial actions"), + "List everything the Speed Dial can run, by section and title: built-in commands (slice, export, views, object " + "operations, plates, calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an `id` for " + "`action_run`, its `section` (where the Speed Dial lists it), a `description`, the `command` of a built-in " + "command, and, when it takes arguments, their `input_schema`. `section` keeps them to one of the Speed Dial's sections, which are not " + "`tool_list`'s groups; one no action is in is refused with the sections there are, but Recent Projects and Design " + "list nothing while there are no recent projects or the Design tab is not shown. `include_settings` also lists " + "settings (each jumps to that setting in the sidebar; use `settings_get` / `settings_set` to read or change values).", + object_schema({{"section", prop("string", "Only this Speed Dial section, in any case, as an entry's `section` names it, " + "e.g. \"Object\", \"View\", \"Slice & Export\".")}, + {"include_settings", prop("boolean", "Also list settings (thousands). Default false.")}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 50."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { + ActionRegistry::Query q; + q.section = arg_string(args, "section"); + q.include_settings = arg_bool(args, "include_settings", false); + q.limit = std::size_t(arg_int(args, "limit", 50)); + q.offset = std::size_t(arg_int(args, "offset", 0)); + return ToolResult::ok(ctx.run_ui([q] { return described(registry_or_fail(), q); })); + })); + + NativeCommand run = mutate_tool( + "action_run", L("Run a Speed Dial action"), + "Run one action by the id `action_list` returned (`orca_command:view_front:orca`, or the name inside it, `view_front`), " + "with `args`, the command's arguments, when it takes some (its `input_schema`). A command's action (`action_list` names " + "the command) runs the command as a call with the action's arguments does: an action that asks in a dialog asks, " + "and the call returns `blocked_by_dialog`; answer it with `dialog_answer`, or, for a native one it can't press (a file " + "picker), register `dialog_auto_answer` before the call. Such an action takes no `args`, or exactly its own; to run a " + "command without asking, call it with its arguments (an absolute path skips a file dialog). Go to layer and Go to " + "tab take their value alone (`{\"percent\": 50}`, `{\"tab\": \"preview\"}`), and a Design command's own action takes " + "the command's arguments. An action that starts a background job (`obj_arrange`, `obj_orient`) completes when the job " + "ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply " + "(the order `object_order` leaves, the object `object_assemble` made). The other actions (plates, recent projects, " + "plugin scripts and pages, settings) run only here.", + object_schema({{"id", prop("string", "Action id from `action_list`, or the name inside it.")}, + {"args", {{"type", "object"}, {"description", "The command's arguments, as its `input_schema` gives them."}}}}, + {"id"}), + [](const json& args, ToolContext& ctx) { + std::string id = arg_string(args, "id"); + json command_args = args.contains("args") ? args["args"] : json::object(); + std::string key; // the command of a command's action + json action_args; // what its journal step keeps for an action of fixed arguments + AppActionRunResult result; // of any other action + ctx.run_ui([&]() -> json { + ActionRegistry& actions = registry_or_fail(); + const AppAction& action = find_action(actions, id); + if (const std::string err = action_args_error(action, command_args); !err.empty()) + throw ToolFailure(err, {{"code", "invalid_argument"}}); + key = action.command; + action_args = action_journal_args(action, command_args); + if (key.empty()) { + result = actions.run(id, command_args, /*record_stats=*/false); + } else { + // What a person's pick of the action runs its command with, which the journal records. + const json* command_action = find_command_action(NativeCommands::instance(), short_id(id)).second; + command_args = action_call_args(command_action, command_args); + } + return json(); + }); + if (key.empty()) { + settle(ctx); + return NativeCommands::from_run_result(id, result); + } + // A command's action runs the command's own function, as a call of the command does, inside action_run's + // journal entry. + const NativeCommand* command = NativeCommands::find(key); + if (command == nullptr) + throw ToolFailure("Unknown command " + key); + if (const std::string err = argument_error(*command, command_args); !err.empty()) + throw argument_refusal(key, err); + ActionContext action_ctx(ctx, id, action_args); + ToolResult reply = command->run(command_args, action_ctx); + if (!reply.is_error && reply.data.is_object()) + reply.data["ran"] = id; + return reply; + }); + // Its actions send G-code to a printer or its print host (printer_send) and sync presets with the cloud account + // (preset_sync). + run.open_world = true; + catalog.add(run); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp new file mode 100644 index 0000000000..49dd1a70d1 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp @@ -0,0 +1,172 @@ +// The place Design, its Bodies heading, the Bodies list's edits of a body: body_set, body_place, body_transform and +// body_delete. body_silent_forms() binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs them +// behind the Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#include "slic3r/GUI/CAD/DesignCanvas.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/Color.hpp" + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +json action_transform(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to transform"); + int bi = target_body_arg(params, doc); + Vec3d translate(params.value("dx", 0.0), params.value("dy", 0.0), params.value("dz", 0.0)); + Vec3d axis(params.value("axis_x", 0.0), params.value("axis_y", 0.0), params.value("axis_z", 1.0)); + Vec3d pivot(params.value("pivot_x", 0.0), params.value("pivot_y", 0.0), params.value("pivot_z", 0.0)); + double angle = params.value("angle", 0.0); + bool copy = params.value("copy", false); + doc.checkpoint(); + int idx = doc.add_transform(bi, translate, axis, pivot, angle, copy, panel->mcp_feature_name(_L("Transform"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"transform_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// The `body` param: an index into describe_design's bodies. +int body_arg(const json& params, const CadDocument& doc) +{ + const json v = param(params, "body"); + if (!v.is_number_integer()) throw std::runtime_error("body must be a body index (describe_design's bodies[].index)"); + const int b = v.get(); + if (b < 0 || b >= int(doc.bodies.size())) + throw std::runtime_error("body " + std::to_string(b) + " is out of range; the design has " + + std::to_string(doc.bodies.size()) + " bodies"); + return b; +} + +// The Bodies row's rename and eye and the Color button, in one call. Every argument is checked +// before anything changes. +json action_body_set(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int b = body_arg(params, doc); + std::optional name; + std::optional color; + std::optional visible; + if (!param(params, "name").is_null()) name = name_arg(params); + if (const json c = param(params, "color"); !c.is_null()) { + const std::string s = c.is_string() ? c.get() : std::string(); + ColorRGBA rgba; + if (s.size() != 7 || s[0] != '#' || + !std::all_of(s.begin() + 1, s.end(), [](unsigned char ch) { return std::isxdigit(ch) != 0; }) || + !decode_color(s, rgba)) + throw std::runtime_error("color must be \"#RRGGBB\""); + color = rgba; + } + if (const json v = param(params, "visible"); !v.is_null()) { + if (!v.is_boolean()) throw std::runtime_error("visible must be true or false"); + visible = v.get(); + } + if (!name && !color && !visible) throw std::runtime_error("body_set needs name, color or visible"); + if (name) panel->rename_body(b, *name); + if (color) panel->set_body_color(b, *color); + if (visible) panel->show_body(b, *visible); + + const CadBody& body = doc.bodies[b]; + json r{{"ok", true}, {"body", b}, {"name", body.has_user_name ? body.user_name : body.name}, + {"visible", panel->mcp_body_shown(b)}}; + if (const DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr) r["color"] = encode_color(vp->body_color(b)); + return r; +} + +json action_body_delete(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int b = body_arg(params, doc); + const int src = doc.bodies[b].source_feature; + if (src < 0 || src >= int(doc.features.size())) + throw CadPrecondition("body " + std::to_string(b) + " has no feature to delete; use new_design to start over"); + const json deleted{{"index", src}, {"type", feature_type_name(doc.features[src].type)}, {"name", doc.features[src].name}}; + const size_t before = doc.features.size(); + if (!panel->delete_body(b)) tree_edit_refused(doc); + return tree_edit_reply(doc, {{"deleted_feature", deleted}, {"removed", before - doc.features.size()}}); +} + +// The Bodies row's Move and Place on Face from arguments: where a body stands, outside the history. Every argument is +// read before the body moves. +json action_body_place(DesignPanel* panel, const json& params) +{ + const int b = body_arg(params, panel->mcp_doc()); + const json move = param(params, "move"); + const json rotate = param(params, "rotate"); + const json face = param(params, "face"); + const json reset = param(params, "reset"); + if (!reset.is_null() && !reset.is_boolean()) throw std::runtime_error("reset must be true or false"); + const bool resets = reset.is_boolean() && reset.get(); + const int forms = int(!move.is_null() || !rotate.is_null()) + int(!face.is_null()) + int(resets); + if (forms == 0) throw std::runtime_error("body_place takes move and rotate, face, or reset: true"); + if (forms > 1) throw std::runtime_error("move and rotate, face and reset are three forms: give one of them"); + + std::string why; + if (!face.is_null()) { + if (!face.is_number_integer() || face.get() < 0) throw std::runtime_error("face must be a face id (body_describe)"); + if (!panel->mcp_place_body_on_face(b, face.get(), why)) throw std::runtime_error(why); + } else if (resets) { + panel->mcp_reset_body_placement(b); + } else { + Vec3d d = Vec3d::Zero(); + if (!move.is_null()) { + if (!move.is_array() || move.size() != 3 || !std::all_of(move.begin(), move.end(), [](const json& v) { return v.is_number(); })) + throw std::runtime_error("move must be [dx, dy, dz] in mm"); + d = Vec3d(move[0].get(), move[1].get(), move[2].get()); + } + int axis = -1; + double angle = 0.0; + if (!rotate.is_null()) { + static const std::map axes{{"x", 0}, {"y", 1}, {"z", 2}}; + const json a = param(rotate, "axis"); + const json g = param(rotate, "angle"); + const auto named = a.is_string() ? axes.find(a.get()) : axes.end(); + if (!rotate.is_object() || named == axes.end() || !g.is_number() || rotate.size() != 2) + throw std::runtime_error("rotate must be {\"axis\": \"x\", \"y\" or \"z\", \"angle\": degrees}"); + axis = named->second; + angle = g.get(); + } + if (!panel->mcp_place_body(b, d, axis, angle, why)) throw std::runtime_error(why); + } + return json{{"ok", true}, {"body", b}, {"moved", panel->mcp_body_moved(b)}, {"placement", placement_json(*panel, b)}}; +} + +} // namespace + +void body_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"body_transform", action_transform}, + {"body_set", action_body_set}, + {"body_delete", action_body_delete}, + {"body_place", action_body_place}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignCommon.hpp b/src/slic3r/GUI/Mcp/Tools/DesignCommon.hpp new file mode 100644 index 0000000000..80e5f2b927 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignCommon.hpp @@ -0,0 +1,192 @@ +#pragma once + +// What the files of the Design commands share, and nothing else uses: the rest of OrcaSlicer and the tests use +// McpToolsDesign.hpp. Each Design heading has its file: DesignTools.cpp for Document, DesignSketchTools.cpp for Sketch, +// DesignSolidTools.cpp for Solid and so on. Each helper here is in the section of the file that defines it: +// DesignTools.cpp's serve every heading, the others' the headings that read the same arguments or describe the same +// things. + +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/Point.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// ---- The helpers every heading uses: DesignTools.cpp's, and the inline ones here ------------ + +// A feature's type as the Design commands name it (describe_design's features[].type): its CadFeatureType +// enumerator's name. +const char* feature_type_name(CadFeatureType t); + +// Where body `b` stands for Commit to Plate and Export STEP (body_place, the Move gizmo, Place on Face): null where the +// model has it, else three rows of four numbers, the rotation and the translation in mm, in the world frame. +nlohmann::json placement_json(const DesignPanel& panel, int b); + +// A vector or point as the Design commands give one: [x, y, z]. +inline nlohmann::json vec3(const Vec3d& v) { return nlohmann::json::array({v.x(), v.y(), v.z()}); } + +// Every reply that used a plane says where it was: a face plane's x axis is not something a caller +// can guess, and the XZ base plane is left-handed (x cross y is -normal), as the GUI stores it. +nlohmann::json frame_json(const SketchPlane& p); + +// A plane's frame, with `base` when it is the XY, XZ or YZ plane through the modeling origin +// (whatever its origin within that plane): the name the plane list gives it. +nlohmann::json plane_json(const SketchPlane& p, const Vec3d& modeling_origin); + +// Adds features as a card's Confirm does: one undo step, a rebuild, the tree and status refreshed. +// `add` creates them and returns the index reported under `index_key`. A rebuild that fails, or an +// `add` that throws, leaves the document as it was with nothing to redo, puts "Edit rejected" on +// the status line as a refused GUI edit does, and fails the call with the kernel's reason, so the +// failed call can be left out of an exported replay. The error's code tells the causes apart, as +// run_guarded() does: rebuild_failed for a rebuild that reports failure, kernel_failure, precondition or +// invalid_argument, or the code of a ToolFailure `add` throws. +// `slow` rebuilds as the cards do, off the UI thread behind the progress dialog (recompute_guarded), +// for features whose helical pipes and skins can take seconds: the window keeps painting and +// inspection calls keep answering meanwhile, while the rebuild refuses every Design call. +nlohmann::json add_feature(DesignPanel* panel, const char* index_key, const std::function& add, bool slow = false); + +// A file the call reads, checked as every path the MCP server takes: absolute UTF-8 (a relative +// one would resolve against the GUI's working directory) and existing. Returns its UTF-8 form. +std::string input_path(const nlohmann::json& value, const std::string& what); + +// The Design commands' names of SketchConstraintType's values, in enum order. SketchConstraintType is +// append-only (recipes store it by position), and so is this list. +inline constexpr const char* kConstraintTypes[] = { + "fix", "coincident", "horizontal", "vertical", "distance", "lock_x", "lock_y", "equal_length", "parallel", + "perpendicular", "concentric", "tangent", "midpoint", "symmetric", "angle", "radius", "diameter", "point_on_line", + "point_on_object", "equal_radius", "collinear", "distance_x", "distance_y", "symmetric_about_y", "symmetric_about_x"}; +static_assert(std::size(kConstraintTypes) == size_t(SketchConstraintType::SymmetricAboutX) + 1, + "every constraint type needs a name"); + +// The name of value `i` of an enum in `names`, one of the Design commands' tables of names (kConstraintTypes, a +// file's own): a recipe is read from a file, so an enum value may be one this build has no name for. +template const char* enum_name(const char* const (&names)[N], int i) +{ + return i >= 0 && i < int(N) ? names[i] : "unknown"; +} + +// The position of `v` in `names`, or an error naming the choices. +template int enum_index(const std::string& key, const nlohmann::json& v, const char* const (&names)[N]) +{ + for (size_t i = 0; i < N; ++i) + if (v.is_string() && v.get() == names[i]) return int(i); + std::string list; + for (const char* n : names) list += (list.empty() ? "" : ", ") + std::string(n); + throw std::runtime_error(key + " must be one of " + list); +} + +// Throws std::runtime_error unless `fi` is the index of one of `doc`'s features. +void check_feature_index(int fi, const CadDocument& doc); + +// params[key], or null when it is absent or params is not an object. +nlohmann::json param(const nlohmann::json& params, const char* key); + +// ---- DesignSketchTools.cpp: a sketch feature as the model's headings describe it ------------ + +// Entity `e` of a sketch, its `index`th, as sketch_describe and feature_describe give it. +nlohmann::json sketch_entity_to(const SketchEntity& e, int index); + +// A constraint's value as the Design commands state it: an angle in degrees (the recipe holds radians), a +// length in mm. Null for the types that carry none. +nlohmann::json constraint_value(SketchConstraintType t, double v); + +// An entity constraint's references, as the solver reads them: a point names its entity and role, +// a whole entity (a line's direction, a circle's radius) only the entity. +nlohmann::json entity_constraint_json(const SketchEntityConstraintDef& c, int index); + +// The `sketch` a Design command reads or builds from: a Sketch feature, or a Project feature, whose +// entities the kernel builds as a sketch's. +int sketch_arg(const nlohmann::json& v, const CadDocument& doc); + +// ---- The names the model's headings share, in enum order ------------------------------------ + +// What a feature's result does to the bodies already there, in BooleanMode order: the commands' `operation`, in the +// words of Fusion's dialogs and the Extrude card. +inline constexpr const char* kOperations[] = {"new_body", "join", "cut", "intersect"}; + +// The names the Solid and Construct headings' commands take and the History heading's feature_describe and +// feature_edit show and set. +inline constexpr const char* kExtrudeEnds[] = {"blind", "symmetric", "two_sided", "through_all", "up_to_face", "up_to_vertex"}; +inline constexpr const char* kFaceGroups[] = {"top", "bottom", "lateral", "all"}; +inline constexpr const char* kPlaneTypes[] = {"offset", "angle", "midplane", "tangent", "two_edges", "coincident"}; +inline constexpr const char* kHoleTypes[] = {"simple", "counterbore", "countersink"}; // CadFeature::hole_style +inline constexpr const char* kAlignTypes[] = {"fastened", "planar", "revolute", "slider", "cylindrical"}; // CadFeature::mate_kind +inline constexpr const char* kPatternTypes[] = {"linear", "circular", "curve"}; // a Pattern's layout + +// kFaceGroups as a refusal lists them. +inline const std::string kFaceGroupWords = "top, bottom, lateral or all"; + +// ---- DesignInspectTools.cpp: the kinds of a body's faces and edges -------------------------- + +// What kind of curve an edge is, for the messages that refuse one. +const char* edge_kind_name(const TopoDS_Edge& e); + +// What kind of surface a face is, for the messages that refuse one. +const char* face_kind_name(const TopoDS_Face& f); + +// ---- DesignConstructTools.cpp: where a datum plane stands ----------------------------------- + +// A shown Plane feature's place among the datum planes: the kernel lists the enabled Plane features +// in order, and a datum reference holds 3 + that position. +int datum_ordinal(const CadDocument& doc, int fi); + +// ---- DesignSolidTools.cpp: the arguments other headings read as Solid's commands do --------- + +// Resolve an optional explicit body target. Default (no `body`, or <0) = last body, which is +// what the kernel picks anyway. Validated BEFORE any checkpoint so a bad index throws clean. +int target_body_arg(const nlohmann::json& params, const CadDocument& doc); + +// The edge group a word names, the Fillet and Chamfer cards' Edges choice, or nothing for any other value. +std::optional face_group_named(const nlohmann::json& v); + +// The `axis` a revolve turns about when it names no line of its sketch: 0 for the sketch plane's X axis, 1 for +// its Y axis. +int revolve_axis_arg(const nlohmann::json& params); + +// Whether entity `e` of `ents`, a sketch's entities, is a line: what a revolve turns about and a rib grows from. +bool revolve_line(const std::vector& ents, int e); + +// The line of sketch `si` a revolve of it turns about, or -1 for the plane axis: params.axis_entity; without one, the +// sketch's only centerline, as a fresh card offers it, unless the caller chose a plane axis. +int revolve_axis_entity_arg(const nlohmann::json& params, const CadDocument& doc, int si); + +// ---- DesignHistoryTools.cpp: what the Feature tree's and the Bodies list's edits share ------ + +// The panel's tree edits put the features back, leave no undo step and say "Edit rejected" when the +// kernel refuses one; the call then fails with the kernel's reason. +[[noreturn]] void tree_edit_refused(const CadDocument& doc); + +// `reply` with what every edit of the Feature tree or the Bodies list reports besides: ok, the feature and body +// counts and the topology generation after it. +nlohmann::json tree_edit_reply(const CadDocument& doc, nlohmann::json reply); + +// A `name` as the rows' rename editor takes it: trimmed, and never empty. +std::string name_arg(const nlohmann::json& params); + +// ---- Each heading's file but DesignTools.cpp: its silent forms ------------------------------ + +// Each adds its heading's silent forms to `forms`, which silent_forms() gathers with Document's. +void sketch_silent_forms(std::vector& forms); +void solid_silent_forms(std::vector& forms); +void surface_silent_forms(std::vector& forms); +void construct_silent_forms(std::vector& forms); +void inspect_silent_forms(std::vector& forms); +void body_silent_forms(std::vector& forms); +void history_silent_forms(std::vector& forms); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp new file mode 100644 index 0000000000..e951fb091d --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp @@ -0,0 +1,316 @@ +// The place Design, its Construct heading: construct_plane, construct_axis, construct_coordinate_system and helix, the +// datum features that sketches and features are placed on, and cad_resolve_plane(), which finds the plane a call names. +// construct_silent_forms() binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs them behind +// the Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/format.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +// ---- Shared with the other Design files (DesignCommon.hpp) ---------------------------------- + +int datum_ordinal(const CadDocument& doc, int fi) +{ + int ordinal = 0; + for (int i = 0; i < fi; ++i) + if (doc.features[i].type == CadFeatureType::Plane && doc.features[i].enabled) ++ordinal; + return ordinal; +} + +namespace { + +json action_construct_axis(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + std::string t = params.value("type", std::string("two_points")); + AxisType at = AxisType::TwoPoints; + if (t == "face_normal") at = AxisType::FaceNormal; + else if (t == "cylinder") at = AxisType::CylinderCenterline; + else if (t == "plane_intersection") at = AxisType::PlaneIntersection; + else if (t == "along_edge") at = AxisType::AlongEdge; + doc.checkpoint(); + int idx = doc.add_axis(at, panel->mcp_feature_name(_L("Axis"))); + CadFeature& f = doc.features[idx]; + if (params.contains("p1") && params["p1"].is_array() && params["p1"].size() >= 3) + f.axis_p1 = Vec3d(params["p1"][0].get(), params["p1"][1].get(), params["p1"][2].get()); + if (params.contains("p2") && params["p2"].is_array() && params["p2"].size() >= 3) + f.axis_p2 = Vec3d(params["p2"][0].get(), params["p2"][1].get(), params["p2"][2].get()); + f.axis_body = params.value("body", -1); + f.axis_face = params.value("face", -1); + f.axis_edge = params.value("edge", -1); + f.axis_plane_a = params.value("plane_a", -1); + f.axis_plane_b = params.value("plane_b", -1); + // Datum features don't produce a body; check for an error returned by resolve. + bool recompute_ok = doc.recompute(); + auto axes = doc.resolve_datum_axes(); + std::string err = doc.error; + if (recompute_ok && err.empty() && !axes.empty() && !axes.back().error.empty()) + err = axes.back().error; + panel->mcp_after_change(); + return json{{"ok", true}, {"axis_index", idx}, {"error", err}}; +} + +json action_construct_coordinate_system(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + std::string t = params.value("type", std::string("point_world")); + CoordSysType ct = CoordSysType::PointWorld; + if (t == "face_and_direction") ct = CoordSysType::FaceAndDirection; + Vec3d pt(0, 0, 0); + if (params.contains("point") && params["point"].is_array() && params["point"].size() >= 3) + pt = Vec3d(params["point"][0].get(), params["point"][1].get(), params["point"][2].get()); + doc.checkpoint(); + int idx = doc.add_coordsys(ct, pt, panel->mcp_feature_name(_L("Coordinate system"))); + CadFeature& f = doc.features[idx]; + f.coordsys_body = params.value("body", -1); + f.coordsys_face = params.value("face", -1); + f.coordsys_edge = params.value("edge", -1); + if (params.contains("x_hint") && params["x_hint"].is_array() && params["x_hint"].size() >= 3) + f.coordsys_x_hint = Vec3d(params["x_hint"][0].get(), params["x_hint"][1].get(), params["x_hint"][2].get()); + bool recompute_ok = doc.recompute(); + auto css = doc.resolve_datum_coordsys(); + std::string err = doc.error; + if (recompute_ok && err.empty() && !css.empty() && !css.back().error.empty()) + err = css.back().error; + panel->mcp_after_change(); + return json{{"ok", true}, {"coordsys_index", idx}, {"error", err}}; +} + +// The Plane card's Confirm (on_add_plane): one undo step, after the card's checks. +json action_construct_plane(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_datum_plane(doc, params); + json r = add_feature(panel, "plane_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Plane", "Design"))); }); + const int fi = r.at("plane_index").get(); + r["name"] = doc.features[fi].name; + r["frame"] = frame_json(doc.resolve_datum_planes().at(datum_ordinal(doc, fi)).second); + return r; +} + +json action_helix(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + CadFeature h; // what add_helix records, built first so a curve the kernel refuses adds nothing + h.type = CadFeatureType::Helix; + h.plane = cad_resolve_plane(params.value("plane", json("XY")), doc, false); + h.helix_radius = params.value("radius", 10.0); + h.helix_pitch = params.value("pitch", 5.0); + h.helix_height = params.value("height", 20.0); + h.helix_left_handed = params.value("left_handed", false); + h.helix_taper_deg = params.value("taper_deg", 0.0); + std::string err; + const TopoDS_Wire curve = doc.build_helix_wire(h, err); + if (curve.IsNull()) throw std::runtime_error("helix: " + (err.empty() ? std::string("the curve could not be built") : err)); + // Where the curve starts and which way it leaves: a sweep's profile is drawn across it there. + BRepAdaptor_CompCurve c(curve); + gp_Pnt start; + gp_Vec tangent; + c.D1(c.FirstParameter(), start, tangent); + doc.checkpoint(); + int idx = doc.add_helix(h.plane, h.helix_radius, h.helix_pitch, h.helix_height, h.helix_left_handed, h.helix_taper_deg, + panel->mcp_feature_name(_L("Helix"))); + panel->mcp_after_change(); + return json{{"ok", true}, {"helix_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, + {"frame", frame_json(h.plane)}, {"start", vec3(Vec3d(start.X(), start.Y(), start.Z()))}, + {"tangent", vec3(Vec3d(tangent.X(), tangent.Y(), tangent.Z()).normalized())}}; +} + +} // namespace + +SketchPlane cad_resolve_plane(const json& plane, const CadDocument& doc, bool drill, int* face_body) +{ + static const std::string kForms = + "plane must be \"XY\", \"XZ\", \"YZ\", {\"datum\": i} or {\"body\": b, \"face\": f}"; + if (plane.is_string()) { + // The base planes through the modeling origin, as the GUI's plane list offers them. + const std::string n = plane.get(); + SketchPlane pl; + if (n == "XY") pl = SketchPlane::XY(); + else if (n == "XZ") pl = SketchPlane::XZ(); + else if (n == "YZ") pl = SketchPlane::YZ(); + else throw std::runtime_error(kForms); + pl.origin += doc.modeling_origin; + return pl; + } + if (plane.is_object() && plane.size() == 1 && plane.contains("datum") && plane["datum"].is_number_integer()) { + // A datum is named by its feature index; the kernel lists the enabled Plane features in + // order, so its position there is the count of enabled Plane features before it. + const int fi = plane["datum"].get(); + if (fi < 0 || fi >= int(doc.features.size())) + throw std::runtime_error("datum " + std::to_string(fi) + " is not a feature (the design has " + + std::to_string(doc.features.size()) + ")"); + const CadFeature& f = doc.features[fi]; + if (f.type != CadFeatureType::Plane) + throw std::runtime_error("feature " + std::to_string(fi) + " (" + feature_type_name(f.type) + + ") is not a datum plane"); + if (!f.enabled) + throw CadPrecondition("datum plane " + std::to_string(fi) + " is hidden; show it first"); + const int ordinal = datum_ordinal(doc, fi); + const auto datums = doc.resolve_datum_planes(); + if (ordinal >= int(datums.size())) + throw CadPrecondition("datum plane " + std::to_string(fi) + " could not be resolved"); + return datums[ordinal].second; + } + if (plane.is_object() && plane.size() == 2 && plane.contains("body") && plane.contains("face") && + plane["body"].is_number_integer() && plane["face"].is_number_integer()) { + const int b = plane["body"].get(), fi = plane["face"].get(); + if (b < 0 || b >= int(doc.bodies.size())) + throw std::runtime_error("body " + std::to_string(b) + " is out of range (have " + + std::to_string(doc.bodies.size()) + ")"); + const TopoDS_Face face = GeometryEngine::face_by_index(doc.bodies[b].shape, fi); + if (face.IsNull()) + throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " does not exist (it has " + + std::to_string(GeometryEngine::face_count(doc.bodies[b].shape)) + " faces)"); + if (BRepAdaptor_Surface(face).GetType() != GeomAbs_Plane) + throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " is " + + face_kind_name(face) + "; a plane needs a planar face"); + SketchPlane pl; + if (!(drill ? doc.inward_plane_of_face(b, fi, pl) : doc.plane_of_face(b, fi, pl))) + throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " has no plane"); + if (face_body != nullptr) *face_body = b; + return pl; + } + throw std::runtime_error(kForms); +} + +std::function cad_datum_plane(CadDocument& doc, const json& params) +{ + using P = PlaneType; + CadFeature f; + f.type = CadFeatureType::Plane; + f.plane_type = P(enum_index("type", params.value("type", json("offset")), kPlaneTypes)); + const P t = f.plane_type; + auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; + const bool on_face = given("face_a"); + + // What each construction reads in resolve_datum_planes(); a param it would ignore is refused. + auto uses = [&](const std::string& k) { + if (k == "face_a") return t != P::TwoEdges; + if (k == "face_b") return t == P::Midplane; + if (k == "edge_a") return t == P::Angle || t == P::TwoEdges; + if (k == "edge_b") return t == P::TwoEdges; + if (k == "base") return (t == P::Offset || t == P::Coincident || t == P::Angle) && !on_face; + if (k == "offset") return t == P::Offset; + if (k == "angle") return (t == P::Offset && !on_face) || t == P::Angle || t == P::Tangent; + return t == P::Offset && !on_face; // axis + }; + for (const char* k : {"face_a", "face_b", "edge_a", "edge_b", "base", "offset", "angle", "axis"}) + if (given(k) && !uses(k)) + throw std::runtime_error(std::string(k) + " is not used by a " + kPlaneTypes[int(t)] + " plane" + + (on_face && std::string(k) != "face_a" ? " on face_a" : "")); + + // {"body": b, "face": f} or {"body": b, "edge": e}, on the current topology. + auto ref = [&](const char* key, const char* kind, int& body, int& id) { + if (!given(key)) return; + const json& v = params.at(key); + if (!v.is_object() || v.size() != 2 || !v.contains("body") || !v.contains(kind) || !v.at("body").is_number_integer() || + !v.at(kind).is_number_integer()) + throw std::runtime_error(std::string(key) + " must be {\"body\": b, \"" + kind + "\": id}"); + body = v.at("body").get(); + id = v.at(kind).get(); + if (body < 0 || body >= int(doc.bodies.size())) + throw std::runtime_error(std::string(key) + ": body " + std::to_string(body) + " is out of range (have " + + std::to_string(doc.bodies.size()) + ")"); + const TopoDS_Shape& s = doc.bodies[body].shape; + const bool face = std::string(kind) == "face"; + if (face ? GeometryEngine::face_by_index(s, id).IsNull() : GeometryEngine::edge_by_index(s, id).IsNull()) + throw std::runtime_error(std::string(key) + ": " + kind + " " + std::to_string(id) + " of body " + std::to_string(body) + + " does not exist (it has " + + std::to_string(face ? GeometryEngine::face_count(s) : GeometryEngine::edge_count(s)) + " " + kind + "s)"); + }; + ref("face_a", "face", f.plane_face_body, f.plane_face); + ref("face_b", "face", f.plane_face2_body, f.plane_face2); + ref("edge_a", "edge", f.plane_edge_body, f.plane_edge); + ref("edge_b", "edge", f.plane_edge2_body, f.plane_edge2); + + // The card's base list: the three base planes, then the shown datum planes in order. + const json base = params.value("base", json("XY")); + if (base.is_object() && !base.contains("datum")) + throw std::runtime_error("base must be \"XY\", \"XZ\", \"YZ\" or {\"datum\": i}; a face goes in face_a"); + cad_resolve_plane(base, doc, false); // refuses what is not a base plane or a shown datum + f.plane_base = base.is_string() ? (base == "XZ" ? 1 : base == "YZ" ? 2 : 0) : 3 + datum_ordinal(doc, base.at("datum").get()); + + // The card's spin controls: their defaults and limits. + auto number = [&](const char* key, double def, double lo, double hi) { + if (!given(key)) return def; + const json& v = params.at(key); + if (!v.is_number() || !(v.get() >= lo && v.get() <= hi)) + throw std::runtime_error(Slic3r::format("%1% must be a number from %2% to %3%", key, lo, hi)); + return v.get(); + }; + f.plane_offset = number("offset", 20.0, -100000, 100000); + f.plane_angle_tilt = number("angle", 0.0, -180, 180); + if (given("axis")) { + if (!params.at("axis").is_number_integer() || (params.at("axis") != 0 && params.at("axis") != 1)) + throw std::runtime_error("axis must be 0 (the base plane's X) or 1 (its Y)"); + f.plane_axis = params.at("axis").get(); + } + if (given("size")) { + const json& sz = params.at("size"); + if (!sz.is_array() || sz.size() != 2 || !sz[0].is_number() || !sz[1].is_number() || + !(sz[0].get() >= 1 && sz[0].get() <= 100000 && sz[1].get() >= 1 && sz[1].get() <= 100000)) + throw std::runtime_error("size must be [u, v], each from 1 to 100000 mm"); + f.plane_u_size = sz[0].get(); + f.plane_v_size = sz[1].get(); + } + if (const std::string why = doc.datum_plane_refusal(f); !why.empty()) throw std::runtime_error(why); + return [&doc, f](const std::string& name) { + const int i = doc.add_plane(f.plane_base, f.plane_offset, f.plane_angle_tilt, f.plane_axis, name); + CadFeature& p = doc.features[i]; + // The references and size the card's apply_plane_refs() copies. + p.plane_type = f.plane_type; + p.plane_face_body = f.plane_face_body; p.plane_face = f.plane_face; + p.plane_face2_body = f.plane_face2_body; p.plane_face2 = f.plane_face2; + p.plane_edge_body = f.plane_edge_body; p.plane_edge = f.plane_edge; + p.plane_edge2_body = f.plane_edge2_body; p.plane_edge2 = f.plane_edge2; + p.plane_u_size = f.plane_u_size; + p.plane_v_size = f.plane_v_size; + return i; + }; +} + +void construct_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"construct_axis", action_construct_axis}, + {"construct_coordinate_system", action_construct_coordinate_system}, + {"construct_plane", action_construct_plane}, + {"helix", action_helix}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp new file mode 100644 index 0000000000..3f112c2f71 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp @@ -0,0 +1,1159 @@ +// The place Design, its History heading: feature_describe and feature_edit, a feature as its card shows and edits it; +// feature_set_expression; and the Feature tree's edits, feature_delete, feature_move, feature_suppress and +// feature_rename. history_silent_forms() binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs +// them behind the Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/format.hpp" + +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// ---- A feature as its card shows it: feature_describe and feature_edit -------------------------- + +// Names in the Design commands' vocabulary, in enum order, that only feature_describe and feature_edit use; those the +// other headings read too, BooleanMode's kOperations among them, are in DesignCommon.hpp. +const char* const kShapes[] = {"rectangle", "circle"}; // SketchShape +const char* const kAxisTypes[] = {"two_points", "face_normal", "cylinder", "plane_intersection", "along_edge"}; +const char* const kCoordSysTypes[] = {"point_world", "face_and_direction"}; + +// A profile sketch's constraint, on the profile's point indices. +json profile_constraint_json(const SketchConstraintDef& c, int index) +{ + json points = json::array(); + for (int p : {c.a, c.b, c.c, c.d}) + if (p >= 0) points.push_back(p); + json j{{"index", index}, {"type", enum_name(kConstraintTypes, int(c.type))}, {"points", std::move(points)}}; + if (json v = constraint_value(c.type, c.value); !v.is_null()) j["value"] = std::move(v); + return j; +} + +// A feature's card as data. `params` is what the card shows; `editable` the fields its Confirm +// writes, named as the CadFeature members (the names feature_set_expression binds), but for the +// members that hold a variant, read and written under their command's argument in its words: mode +// as `operation` (kOperations), and hole_style, mate_kind and pattern_circular as `type`; `ranges` the limits +// its spin controls set on the numeric ones; `refs` what it refers to (feature and body indices, face +// and edge ids, read in the model before it but for a datum's), which feature_edit's refs re-points +// (cad_apply_feature_refs()); `expr` the bindings. +// feature_describe shows it and feature_edit checks against it, so the two cannot disagree. +json feature_card(const CadFeature& f) +{ + json params = json::object(), ranges = json::object(), refs = json::object(), editable = json::array(); + auto show = [&](const char* k, json v) { params[k] = std::move(v); }; + auto edit = [&](const char* k, json v) { params[k] = std::move(v); editable.push_back(k); }; + auto num = [&](const char* k, double v, double lo, double hi) { edit(k, v); ranges[k] = json::array({lo, hi}); }; + auto ref = [&](const char* k, json v) { refs[k] = std::move(v); }; + using T = CadFeatureType; + switch (f.type) { + case T::Sketch: + if (!f.imported_regions.empty()) { + // Text or SVG art, vectorised once: its placement edits, and a Text feature's words, font and height, + // which feature_edit outlines again. + if (f.is_text()) { + edit("text_string", f.text_string); + edit("text_font", f.text_font); + edit("text_height", f.text_height); + } + show("regions", int(f.imported_regions.size())); + // Per region, its closed loops and the area it fills as placed, in mm². A region keeps its + // outer loop first and its holes after it, so it has 1 + holes loops, and it fills the + // outer loop's area less its holes', times the placement's scale. A glyph or path that + // vectorised into a sliver or with a stray hole shows here, where the region count alone + // does not. + json loops = json::array(), areas = json::array(); + for (const auto& region : f.imported_regions) { + loops.push_back(int(region.size())); + double filled = 0.0; + for (size_t c = 0; c < region.size(); ++c) { + const std::vector& loop = region[c]; + double twice = 0.0; // the shoelace sum: twice the signed area + for (size_t i = 0; i < loop.size(); ++i) { + const Vec2d& a = loop[i]; + const Vec2d& b = loop[(i + 1) % loop.size()]; + twice += a.x() * b.y() - b.x() * a.y(); + } + filled += (c == 0 ? 0.5 : -0.5) * std::abs(twice); + } + areas.push_back(filled * std::abs(f.import_scale_x * f.import_scale_y)); + } + show("region_loops", std::move(loops)); + show("region_areas", std::move(areas)); + edit("import_offset", json::array({f.import_offset.x(), f.import_offset.y()})); + num("import_scale_x", f.import_scale_x, 0.001, 1000); + num("import_scale_y", f.import_scale_y, 0.001, 1000); + if (f.import_on_face) ref("import_face_body", f.import_face_body); + } else if (f.entities.empty() && f.profile.points.empty()) { // the Sketch card's shape + edit("shape", enum_name(kShapes, int(f.shape))); + num("width", f.width, 0.1, 1000); + num("height", f.height, 0.1, 1000); + num("radius", f.radius, 0.1, 1000); + } + break; + case T::Extrude: + num("distance", f.distance, -1000, 1000); + num("distance2", f.distance2, 0, 100000); + num("taper_deg", f.taper_deg, -89, 89); + edit("extrude_end", enum_name(kExtrudeEnds, int(f.extrude_end))); + edit("flip", f.flip); + edit("operation", enum_name(kOperations, int(f.mode))); + ref("sketch_ref", f.sketch_ref); + ref("target_body", f.target_body); + ref("up_to_face", f.up_to_face); + ref("extrude_src_face", f.extrude_src_face); + break; + case T::Revolve: + num("revolve_angle", f.revolve_angle, 1, 360); + edit("revolve_axis", f.revolve_axis); + edit("flip", f.flip); + edit("operation", enum_name(kOperations, int(f.mode))); + ref("sketch_ref", f.sketch_ref); + ref("revolve_axis_entity", f.revolve_axis_entity); + ref("target_body", f.target_body); + break; + case T::Sweep: + edit("operation", enum_name(kOperations, int(f.mode))); + ref("sketch_ref", f.sketch_ref); + ref("sweep_path_ref", f.sweep_path_ref); + ref("target_body", f.target_body); + break; + case T::Loft: + edit("operation", enum_name(kOperations, int(f.mode))); + edit("loft_ruled", f.loft_ruled); + ref("loft_profile_refs", f.loft_profile_refs); + ref("target_body", f.target_body); + break; + case T::Fillet: + case T::Chamfer: + num("dressup_size", f.dressup_size, 0.1, 1000); + ref("edges", f.dressup_edge_ids()); + ref("face_group", enum_name(kFaceGroups, int(f.face_group))); + ref("target_body", f.target_body); + break; + case T::Hole: + num("hole_diameter", f.hole_diameter, 0.1, 1000); + num("hole_depth", f.hole_depth, 0.1, 1000); + edit("hole_through", f.hole_through); + num("hole_x", f.hole_x, -1000, 1000); + num("hole_y", f.hole_y, -1000, 1000); + // The seat, which the card does not show; hole's type and designation set it. + edit("type", enum_name(kHoleTypes, f.hole_style)); + num("hole_cbore_diameter", f.hole_cbore_diameter, 0, 1000); + num("hole_cbore_depth", f.hole_cbore_depth, 0, 1000); + num("hole_csink_diameter", f.hole_csink_diameter, 0, 1000); + num("hole_csink_angle", f.hole_csink_angle, 1, 179); + show("hole_standard", f.hole_standard); + ref("target_body", f.target_body); + break; + case T::Thread: + // The card shows the diameter, the size a thread is named by; either one may be set. + num("thread_diameter", 2.0 * f.thread_radius, 0.1, 1000); + num("thread_radius", f.thread_radius, 0.05, 500); + num("thread_pitch", f.thread_pitch, 0.1, 1000); + num("thread_height", f.thread_height, 0.1, 1000); + num("thread_depth", f.thread_depth, 0.1, 1000); + edit("thread_internal", f.thread_internal); + num("thread_x", f.thread_x, -1000, 1000); + num("thread_y", f.thread_y, -1000, 1000); + ref("target_body", f.target_body); + break; + case T::Shell: + num("shell_thickness", f.shell_thickness, 0.01, 100000); + ref("shell_face", f.shell_face); + ref("target_body", f.target_body); + break; + case T::Draft: + num("draft_angle", f.draft_angle, -89, 89); + ref("draft_face", f.draft_face); + ref("target_body", f.target_body); + break; + case T::Thicken: + num("thicken_thickness", f.thicken_thickness, 0.01, 100000); + edit("thicken_flip", f.thicken_flip); + ref("thicken_face", f.thicken_face); + ref("target_body", f.target_body); + break; + case T::ThickenSurface: + num("thicken_thickness", f.thicken_thickness, 0.01, 100000); + edit("thicken_flip", f.thicken_flip); + ref("target_body", f.target_body); + break; + case T::Pattern: + // A pattern along a curve follows its sketch's entity, which no field changes. + if (f.pattern_curve_sketch >= 0) + show("type", enum_name(kPatternTypes, 2)); + else + edit("type", enum_name(kPatternTypes, f.pattern_circular ? 1 : 0)); + num("pattern_count", f.pattern_count, 1, 999); + num("pattern_spacing", f.pattern_spacing, 0.01, 100000); + edit("pattern_dir", f.pattern_dir); + num("pattern_angle", f.pattern_angle, 1, 360); + ref("pattern_curve_sketch", f.pattern_curve_sketch); + ref("pattern_curve_entity", f.pattern_curve_entity); + ref("target_body", f.target_body); + break; + case T::Boolean: + edit("operation", enum_name(kOperations, int(f.mode))); + edit("bool_keep_tool", f.bool_keep_tool); + num("bool_tolerance", f.bool_tolerance, 0, 100); + ref("target_body", f.target_body); + ref("bool_tool_body", f.bool_tool_body); + ref("bool_target_face", f.bool_target_face); + ref("bool_tool_face", f.bool_tool_face); + break; + case T::Cut: + num("cut_offset", f.cut_offset, -10000, 10000); + edit("cut_flip", f.cut_flip); + edit("cut_keep_upper", f.cut_keep_upper); + edit("cut_keep_lower", f.cut_keep_lower); + ref("cut_face_body", f.cut_face_body); + ref("cut_face", f.cut_face); + ref("target_body", f.target_body); + break; + case T::Mirror: + edit("mirror_keep_original", f.mirror_keep_original); + edit("operation", enum_name(kOperations, int(f.mode))); + ref("target_body", f.target_body); + break; + case T::Transform: + edit("xf_translate", vec3(f.xf_translate)); + edit("xf_axis", vec3(f.xf_axis)); + edit("xf_pivot", vec3(f.xf_pivot)); + num("xf_angle_deg", f.xf_angle_deg, -360, 360); + edit("xf_copy", f.xf_copy); + ref("target_body", f.target_body); + break; + case T::Plane: + num("plane_offset", f.plane_offset, -100000, 100000); + num("plane_angle_tilt", f.plane_angle_tilt, -180, 180); + num("plane_u_size", f.plane_u_size, 1, 100000); + num("plane_v_size", f.plane_v_size, 1, 100000); + ref("plane_type", enum_name(kPlaneTypes, int(f.plane_type))); + ref("plane_base", f.plane_base); + ref("plane_axis", f.plane_axis); + ref("plane_face_body", f.plane_face_body); + ref("plane_face", f.plane_face); + ref("plane_face2_body", f.plane_face2_body); + ref("plane_face2", f.plane_face2); + ref("plane_edge_body", f.plane_edge_body); + ref("plane_edge", f.plane_edge); + ref("plane_edge2_body", f.plane_edge2_body); + ref("plane_edge2", f.plane_edge2); + break; + case T::Helix: + num("helix_radius", f.helix_radius, 0.01, 10000); + num("helix_pitch", f.helix_pitch, 0.01, 10000); + num("helix_height", f.helix_height, 0.01, 10000); + num("helix_taper_deg", f.helix_taper_deg, -89, 89); + edit("helix_left_handed", f.helix_left_handed); + break; + case T::Rib: + num("rib_thickness", f.rib_thickness, 0.01, 100000); + num("rib_depth", f.rib_depth, 0.01, 100000); + ref("rib_sketch_ref", f.rib_sketch_ref); + ref("rib_entity", f.rib_entity); + ref("target_body", f.target_body); + break; + case T::SurfaceExtrude: + num("distance", f.distance, 0.1, 1000); + ref("sketch_ref", f.sketch_ref); + break; + case T::SurfaceRevolve: + num("revolve_angle", f.revolve_angle, 1, 360); + edit("revolve_axis", f.revolve_axis); + edit("flip", f.flip); + ref("sketch_ref", f.sketch_ref); + ref("revolve_axis_entity", f.revolve_axis_entity); + break; + case T::SurfaceOffset: + num("plane_offset", f.plane_offset, -100000, 100000); + ref("target_body", f.target_body); + break; + case T::Mate: + edit("type", enum_name(kAlignTypes, f.mate_kind)); + num("mate_offset", f.mate_offset, -100000, 100000); + num("mate_angle", f.mate_angle, -360, 360); + edit("mate_flip", f.mate_flip); + ref("mate_cs_a", f.mate_cs_a); + ref("mate_cs_b", f.mate_cs_b); + break; + case T::Axis: + ref("axis_type", enum_name(kAxisTypes, int(f.axis_type))); + ref("axis_p1", vec3(f.axis_p1)); + ref("axis_p2", vec3(f.axis_p2)); + ref("axis_body", f.axis_body); + ref("axis_face", f.axis_face); + ref("axis_edge", f.axis_edge); + ref("axis_plane_a", f.axis_plane_a); + ref("axis_plane_b", f.axis_plane_b); + break; + case T::CoordSys: + ref("coordsys_type", enum_name(kCoordSysTypes, int(f.coordsys_type))); + ref("coordsys_point", vec3(f.coordsys_point)); + ref("coordsys_body", f.coordsys_body); + ref("coordsys_face", f.coordsys_face); + ref("coordsys_edge", f.coordsys_edge); + ref("coordsys_x_hint", vec3(f.coordsys_x_hint)); + break; + case T::Project: + ref("project_source_body", f.project_source_body); + ref("project_edges", f.project_edges); + ref("project_face", f.project_face); + break; + case T::DeleteFace: + ref("delete_faces", f.delete_faces); + ref("target_body", f.target_body); + break; + case T::SurfaceLoft: + show("loft_ruled", f.loft_ruled); + ref("loft_profile_refs", f.loft_profile_refs); + break; + case T::SurfaceFill: + ref("sketch_ref", f.sketch_ref); + break; + case T::Import: + break; + } + json expr = json::object(); + for (const auto& [field, e] : f.expr) expr[field] = e; + return json{{"params", std::move(params)}, {"editable", std::move(editable)}, {"ranges", std::move(ranges)}, + {"expr", std::move(expr)}, {"refs", std::move(refs)}}; +} + +// Writes one editable field that is not a bindable number: a card's check box, choice or vector. +// Throws for a value of the wrong type or one the card does not offer. +void set_card_choice(CadFeature& f, const std::string& k, const json& v) +{ + auto flag = [&](bool& field) { + if (!v.is_boolean()) throw std::runtime_error(k + " must be true or false"); + field = v.get(); + }; + auto choice = [&](int& field, int hi) { + if (!v.is_number_integer() || v.get() < 0 || v.get() > hi) + throw std::runtime_error(k + " must be an integer from 0 to " + std::to_string(hi)); + field = v.get(); + }; + auto point3 = [&](Vec3d& field, bool direction) { + if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) + throw std::runtime_error(k + " must be [x, y, z]"); + const Vec3d p(v[0].get(), v[1].get(), v[2].get()); + if (direction && !(p.norm() > 1e-9)) throw std::runtime_error(k + " must not be zero"); + if (!direction && !(p.cwiseAbs().maxCoeff() <= 100000)) + throw std::runtime_error(k + " must be between -100000 and 100000 on each axis"); + field = p; + }; + if (k == "flip") return flag(f.flip); + if (k == "hole_through") return flag(f.hole_through); + if (k == "thread_internal") return flag(f.thread_internal); + if (k == "loft_ruled") return flag(f.loft_ruled); + if (k == "bool_keep_tool") return flag(f.bool_keep_tool); + if (k == "cut_flip") return flag(f.cut_flip); + if (k == "cut_keep_upper") return flag(f.cut_keep_upper); + if (k == "cut_keep_lower") return flag(f.cut_keep_lower); + if (k == "mirror_keep_original") return flag(f.mirror_keep_original); + if (k == "thicken_flip") return flag(f.thicken_flip); + if (k == "helix_left_handed") return flag(f.helix_left_handed); + if (k == "xf_copy") return flag(f.xf_copy); + if (k == "mate_flip") return flag(f.mate_flip); + if (k == "pattern_dir") return choice(f.pattern_dir, 1); + if (k == "revolve_axis") { + // Choosing the plane's X or Y axis on the card drops a sketch line chosen as the axis. + choice(f.revolve_axis, 1); + f.revolve_axis_entity = -1; + return; + } + if (k == "xf_translate") return point3(f.xf_translate, false); + if (k == "xf_pivot") return point3(f.xf_pivot, false); + if (k == "xf_axis") return point3(f.xf_axis, true); + if (k == "import_offset") { + if (!v.is_array() || v.size() != 2 || !v[0].is_number() || !v[1].is_number()) + throw std::runtime_error(k + " must be [x, y]"); + const Vec2d p(v[0].get(), v[1].get()); + if (!(p.cwiseAbs().maxCoeff() <= 100000)) throw std::runtime_error(k + " must be between -100000 and 100000 on each axis"); + f.import_offset = p; + return; + } + // A Text feature's words, height and font, as sketch_text takes them. Written here only: the outline is the + // panel's (DesignPanel::mcp_outline_text()), which feature_edit runs on them. + if (k == "text_string") { + if (!v.is_string() || v.get().empty()) throw std::runtime_error("text_string must be the words to outline"); + f.text_string = v.get(); + return; + } + if (k == "text_height") { + if (!v.is_number() || !(v.get() >= 0.5 && v.get() <= 500.0)) + throw std::runtime_error("text_height must be 0.5 to 500 mm"); + f.text_height = v.get(); + return; + } + if (k == "text_font") { + if (!v.is_string() || v.get().empty()) + throw std::runtime_error("text_font must be a font's face name, or the stored value feature_describe reports"); + f.text_font = v.get(); + return; + } + if (k == "shape") { + f.shape = SketchShape(enum_index(k, v, kShapes)); + return; + } + if (k == "type") { + // A hole's seat, an align's kind and a pattern's layout, in their command's words. + if (f.type == CadFeatureType::Hole) { + f.hole_style = enum_index(k, v, kHoleTypes); + return; + } + if (f.type == CadFeatureType::Mate) { + f.mate_kind = enum_index(k, v, kAlignTypes); + return; + } + if (f.type == CadFeatureType::Pattern) { + const int layout = enum_index(k, v, kPatternTypes); + if (layout == 2) + throw std::runtime_error("a pattern's type is linear or circular; a curve pattern is made with pattern {type: \"curve\"}"); + f.pattern_circular = layout == 1; + return; + } + } + if (k == "operation") { + // The member mode, in the words the feature's card offers: a Boolean combines two bodies, so it makes no new + // one; a Mirror adds its mirrored body or joins it back. + const BooleanMode m = BooleanMode(enum_index(k, v, kOperations)); + if (f.type == CadFeatureType::Boolean && m == BooleanMode::New) + throw std::runtime_error("a Boolean's operation is join, cut or intersect"); + if (f.type == CadFeatureType::Mirror && m != BooleanMode::New && m != BooleanMode::Add) + throw std::runtime_error("a Mirror's operation is new_body or join"); + f.mode = m; + return; + } + if (k == "extrude_end") { + // The face or vertex an end goes up to is picked on the canvas; feature_edit keeps the + // feature's own pick and cannot make one. + const ExtrudeEnd e = ExtrudeEnd(enum_index(k, v, kExtrudeEnds)); + if (e == ExtrudeEnd::UpToFace && f.up_to_face < 0) + throw std::runtime_error("extrude_end up_to_face needs a target face, which only the Extrude card picks"); + if (e == ExtrudeEnd::UpToVertex && f.extrude_end != ExtrudeEnd::UpToVertex) + throw std::runtime_error("extrude_end up_to_vertex needs a target vertex, which only the Extrude card picks"); + f.extrude_end = e; + return; + } + throw std::runtime_error(k + " cannot be set"); +} + +// The `feature` param (or `index`, as agents often call it): an index into describe_design's features. +int feature_arg(const json& params, const CadDocument& doc) +{ + const json v = !params.is_object() ? json() : params.contains("feature") ? params["feature"] : params.value("index", json()); + if (!v.is_number_integer()) throw std::runtime_error("feature must be a feature index (describe_design's features[].index)"); + check_feature_index(v.get(), doc); + return v.get(); +} + +json action_feature_describe(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + return cad_feature_json(doc, feature_arg(params, doc)); +} + +// A card's Confirm in edit mode (DesignPanel::confirm_tool): `fields`, then `refs`, written to a copy of the feature, +// a Text feature outlined again when its words, height or font change, then one undo step and replace_feature(), +// which rebuilds and puts the old features back if the rebuild fails. Every argument is checked before anything +// changes. +json action_feature_edit(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + // The card's values go in fields; params and values are what agents often call them. + const char* key = params.contains("fields") ? "fields" : params.contains("params") ? "params" : params.contains("values") ? "values" : nullptr; + json fields = key != nullptr ? params[key] : json::object(); + const json refs = params.value("refs", json::object()); + if (!fields.is_object()) throw std::runtime_error("fields must be an object, as {\"distance\": 15}"); + if (!refs.is_object()) throw std::runtime_error("refs must be an object, as {\"sweep_path_ref\": 2}"); + if (fields.empty() && refs.empty()) + throw std::runtime_error("feature_edit needs fields or refs, as {\"fields\": {\"distance\": 15}} or {\"refs\": {\"sweep_path_ref\": 2}}"); + const CadFeature was = doc.features[fi]; + CadFeature edited = was; + // A Text feature's Bold and Italic go with a face name in text_font, as the Text dialog's boxes go with its Font + // list: they are no field of the feature, whose stored font holds them. + bool bold = false, italic = false, styled = false; + if (was.is_text()) + for (const auto& [k, flag] : {std::pair{"text_bold", &bold}, {"text_italic", &italic}}) { + if (!fields.contains(k)) continue; + if (!fields[k].is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); + *flag = fields[k].get(); + styled = true; + fields.erase(k); + } + if (!fields.empty()) cad_apply_feature_fields(edited, fields); + if (was.is_text() && (styled || fields.contains("text_string") || fields.contains("text_height") || fields.contains("text_font"))) { + // A text_font that is the stored value keeps the feature's font; any other names a face. + const std::string face = fields.contains("text_font") && edited.text_font != was.text_font ? edited.text_font : std::string(); + if (styled && face.empty()) throw std::runtime_error("text_bold and text_italic go with text_font given as a face name"); + edited.text_font = was.text_font; + std::string why; + if (!panel->mcp_outline_text(edited, edited.text_string, face, bold, italic, edited.text_height, why)) + throw std::runtime_error(why); + } + if (!refs.empty()) cad_apply_feature_refs(edited, refs, cad_document_before(doc, fi), doc, fi); + const json described = cad_feature_json(doc, fi); + doc.checkpoint(); + if (!doc.replace_feature(fi, edited)) { + // The features are back already; rollback() also takes back the undo step and restores + // the redo branch, so the refused call leaves the history as it found it. + const std::string why = doc.error.empty() ? "the model could not be rebuilt" : doc.error; + doc.rollback(); + doc.error = why; + panel->mcp_after_change(false); + throw ToolFailure(why, {{"code", "rebuild_failed"}}); + } + panel->mcp_after_change(); + return json{{"ok", true}, + {"feature", fi}, + {"changed", cad_feature_changes(described, cad_feature_json(doc, fi))}, + {"bodies", int(doc.bodies.size())}, + {"generation", doc.topo_generation}, + {"error", doc.error}}; +} + +json action_feature_set_expression(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + if (!params.contains("field")) throw std::runtime_error("feature_set_expression needs 'field' name"); + if (!params.contains("expr")) throw std::runtime_error("feature_set_expression needs 'expr' string"); + const std::string field = params["field"].get(); + const std::string expr = params["expr"].get(); + // A name the evaluator does not know would fail every later rebuild; the binding row refuses it too. + if (!CadDocument::is_bindable_field(field)) + throw std::runtime_error("\"" + field + "\" is not a value an expression can drive"); + // An empty expression removes the binding, as the binding row's Clear does; the field keeps + // the value the binding last gave it. + const bool clear = expr.empty(); + if (clear && doc.features[fi].expr.count(field) == 0) + throw std::runtime_error(field + " has no binding on feature " + std::to_string(fi)); + doc.checkpoint(); + if (clear) + doc.features[fi].expr.erase(field); + else + doc.features[fi].expr[field] = expr; + const bool ok = doc.recompute(); + // rollback() rebuilds, which succeeds and clears doc.error; carry the reason across so the + // reply says why the edit was rejected. + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature", fi}, {"field", field}, {"error", doc.error}}; +} + +} // namespace + +// ---- Shared with the other Design files (DesignCommon.hpp) ---------------------------------- + +[[noreturn]] void tree_edit_refused(const CadDocument& doc) +{ + throw ToolFailure(doc.error.empty() ? "the Design tab refused the edit" : doc.error, {{"code", "rebuild_failed"}}); +} + +json tree_edit_reply(const CadDocument& doc, json reply) +{ + reply["ok"] = true; + reply["features"] = doc.features.size(); + reply["bodies"] = doc.bodies.size(); + reply["generation"] = doc.topo_generation; + return reply; +} + +std::string name_arg(const json& params) +{ + const json v = param(params, "name"); + if (!v.is_string()) throw std::runtime_error("name must be a string"); + std::string name = v.get(); + name.erase(name.find_last_not_of(" \t\r\n") + 1); + name.erase(0, name.find_first_not_of(" \t\r\n")); + if (name.empty()) throw std::runtime_error("name must not be empty"); + return name; +} + +namespace { + +// ---- The Feature tree's edits ------------------------------------------------------------------- + +json action_feature_delete(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + const size_t before = doc.features.size(); + if (!panel->delete_feature(fi)) tree_edit_refused(doc); + return tree_edit_reply(doc, {{"removed", before - doc.features.size()}}); +} + +json action_feature_move(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + const json delta = param(params, "delta"); + if (!delta.is_number_integer() || std::abs(delta.get()) != 1) + throw std::runtime_error("delta must be -1 (up) or 1 (down)"); + const int to = fi + delta.get(); + if (to < 0 || to >= int(doc.features.size())) + throw CadPrecondition("feature " + std::to_string(fi) + " is already " + (to < 0 ? "first" : "last")); + if (!panel->move_feature(fi, delta.get())) tree_edit_refused(doc); + return tree_edit_reply(doc, {{"feature", to}, {"from", fi}}); +} + +// The row's eye: it shows a feature that is not suppressed and hides one that is. +json action_feature_suppress(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + const json suppressed = param(params, "suppressed"); + if (!suppressed.is_boolean()) throw std::runtime_error("suppressed must be true or false"); + const bool shown = !suppressed.get(); + const bool changed = doc.features[fi].enabled != shown; + if (!panel->show_feature(fi, shown)) tree_edit_refused(doc); + return tree_edit_reply(doc, {{"feature", fi}, {"suppressed", suppressed}, {"changed", changed}}); +} + +json action_feature_rename(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + const std::string name = name_arg(params); + const bool changed = doc.features[fi].name != name; + panel->rename_feature(fi, name); + return json{{"ok", true}, {"feature", fi}, {"name", name}, {"changed", changed}, {"undo_depth", doc.undo_depth()}}; +} + +} // namespace + +json cad_feature_json(const CadDocument& doc, int index) +{ + check_feature_index(index, doc); + const CadFeature& f = doc.features[index]; + json j = feature_card(f); + j["index"] = index; + j["type"] = feature_type_name(f.type); + j["name"] = f.name; + j["suppressed"] = !f.enabled; + + // The plane the recipe builds on: a datum's resolved frame, or the plane the feature holds. + using T = CadFeatureType; + const bool own_profile = f.type != T::Sketch && f.sketch_ref < 0 && (!f.entities.empty() || !f.profile.points.empty()); + if (f.type == T::Plane) { + const auto datums = doc.resolve_datum_planes(); + const int ordinal = datum_ordinal(doc, index); + if (f.enabled && ordinal < int(datums.size())) j["plane"] = plane_json(datums[ordinal].second, doc.modeling_origin); + } else if (f.type == T::Sketch || f.type == T::Hole || f.type == T::Thread || f.type == T::Helix || f.type == T::Pattern || + f.type == T::Mirror || f.type == T::Project || (f.type == T::Cut && f.cut_face < 0) || own_profile) { + j["plane"] = plane_json(f.plane, doc.modeling_origin); + } + + // A sketch's geometry, or the loop an extrude or revolve carries itself; points are in the + // plane's frame. + if (!f.entities.empty()) { + json entities = json::array(), constraints = json::array(); + for (size_t i = 0; i < f.entities.size(); ++i) entities.push_back(sketch_entity_to(f.entities[i], int(i))); + for (size_t i = 0; i < f.entity_constraints.size(); ++i) + constraints.push_back(entity_constraint_json(f.entity_constraints[i], int(i))); + j["entities"] = std::move(entities); + j["constraints"] = std::move(constraints); + } else if (!f.profile.points.empty()) { + json points = json::array(), constraints = json::array(); + for (const Vec2d& p : f.profile.points) points.push_back(json::array({p.x(), p.y()})); + for (size_t i = 0; i < f.constraints.size(); ++i) constraints.push_back(profile_constraint_json(f.constraints[i], int(i))); + j["profile"] = json{{"points", std::move(points)}, {"closed", f.profile.closed}}; + j["constraints"] = std::move(constraints); + } + + // What consumes this feature: the references remove_feature() remaps, and for a datum plane + // the features built on it. + const int datum = f.type == T::Plane && f.enabled ? 3 + datum_ordinal(doc, index) : -1; + json used_by = json::array(); + for (int i = 0; i < int(doc.features.size()); ++i) { + bool uses = false; + CadDocument::for_each_feature_ref(doc.features[i], [&](int r) { uses = uses || r == index; }); + if (datum >= 0) CadDocument::for_each_datum_ref(doc.features[i], [&](int r) { uses = uses || r == datum; }); + if (uses) used_by.push_back(i); + } + json made = json::array(); + for (size_t b = 0; b < doc.bodies.size(); ++b) + if (doc.bodies[b].source_feature == index) made.push_back(int(b)); + j["used_by"] = std::move(used_by); + j["bodies_made"] = std::move(made); + for (const auto& [mate, reason] : doc.mate_conflicts) + if (mate == index) j["conflict"] = reason; + + // The model its body indices and face and edge ids are read in: the one just before it, which feature_edit's + // refs take, but for a datum, which the engine resolves against the finished model (for_each_body_ref()). + j["ids_of"] = f.type == T::Plane || f.type == T::Axis || f.type == T::CoordSys ? "finished" : "before"; + // As the last rebuild recorded them, named as the bodies they became are; null where that rebuild did not reach. + json before = nullptr; + if (size_t(index) < doc.bodies_before.size() && doc.bodies_before[size_t(index)]) { + before = json::array(); + const std::vector& was = *doc.bodies_before[size_t(index)]; + for (size_t b = 0; b < was.size(); ++b) { + const int now = doc.body_index(was[b].id); + const CadBody* body = now >= 0 ? &doc.bodies[size_t(now)] : nullptr; + before.push_back(json{{"index", int(b)}, {"name", body != nullptr && body->has_user_name ? body->user_name : was[b].name}}); + } + } + j["bodies_before"] = std::move(before); + return j; +} + +json cad_feature_changes(const json& was, const json& now) +{ + json changed = json::object(); + for (const char* part : {"params", "refs"}) { + const json before = was.value(part, json::object()), after = now.value(part, json::object()); + for (const auto& [k, v] : after.items()) { + const json old = before.value(k, json()); + if (old != v) changed[k] = json::array({old, v}); + } + } + // The plane a Mirror, a Helix or a Cut builds on is reported beside them, and a re-point of it is a change too. + const json old_plane = was.value("plane", json()), new_plane = now.value("plane", json()); + if (old_plane != new_plane) changed["plane"] = json::array({old_plane, new_plane}); + return changed; +} + +void cad_apply_feature_fields(CadFeature& f, const json& fields) +{ + if (!fields.is_object() || fields.empty()) + throw std::runtime_error("fields must name the fields to change, as {\"distance\": 15}"); + const json card = feature_card(f); + const json& editable = card["editable"]; + const json& ranges = card["ranges"]; + const std::string type = feature_type_name(f.type); + if (editable.empty()) + throw std::runtime_error(type + ": no field feature_edit can change; its inputs are geometry or picks"); + if (fields.contains("thread_diameter") && fields.contains("thread_radius")) + throw std::runtime_error("give thread_diameter or thread_radius, not both"); + // The two are one value, so a binding on either drives both. + auto same_value = [](const std::string& a, const std::string& b) { + auto thread_size = [](const std::string& k) { return k == "thread_diameter" || k == "thread_radius"; }; + return a == b || (thread_size(a) && thread_size(b)); + }; + + CadFeature edited = f; + for (const auto& [key, v] : fields.items()) { + if (std::find(editable.begin(), editable.end(), json(key)) == editable.end()) { + std::string list; + for (const json& e : editable) list += (list.empty() ? "" : ", ") + e.get(); + throw std::runtime_error(type + ": '" + key + "' is not an editable field; editable: " + list); + } + // Every rebuild writes a bound field from its expression, so a literal would not last. + for (const auto& [bound, e] : f.expr) + if (same_value(bound, key)) + throw std::runtime_error(key + " is driven by the expression '" + e + "'; change it with set_variable, or " + "remove the binding with feature_set_expression {field: '" + bound + "', expr: ''}"); + const auto range = ranges.find(key); + if (range == ranges.end()) { + set_card_choice(edited, key, v); + continue; + } + if (!v.is_number()) throw std::runtime_error(key + " must be a number"); + const double x = v.get(), lo = (*range)[0].get(), hi = (*range)[1].get(); + if (!(x >= lo && x <= hi)) throw std::runtime_error(Slic3r::format("%1% must be between %2% and %3%", key, lo, hi)); + if (key == "pattern_count" && x != std::floor(x)) throw std::runtime_error("pattern_count must be a whole number"); + CadDocument::set_numeric_field(edited, key, x); + } + f = std::move(edited); +} + +CadDocument cad_document_before(const CadDocument& doc, int feature) +{ + check_feature_index(feature, doc); + CadDocument before = doc.history_before(feature); + if (!before.recompute()) + throw ToolFailure("the model before feature " + std::to_string(feature) + " (" + doc.features[size_t(feature)].name + + ") does not rebuild: " + (before.error.empty() ? std::string("no reason given") : before.error), + {{"code", "rebuild_failed"}}); + return before; +} + +namespace { + +// "feature 5 (Sweep 6)": the feature whose refs feature_edit writes, as its refusals name it. +std::string feature_label(const CadDocument& doc, int index) +{ + return "feature " + std::to_string(index) + " (" + doc.features[size_t(index)].name + ")"; +} + +// The names feature_edit's refs takes for a feature of type `t`: those of feature_describe's refs that its card can +// pick again when it edits. Empty for a type whose card picks nothing again, and for an Extrude, whose profile and +// target are fixed. +std::vector ref_names(CadFeatureType t) +{ + using T = CadFeatureType; + switch (t) { + case T::Revolve: return {"revolve_axis_entity", "target_body"}; + case T::SurfaceRevolve: return {"revolve_axis_entity"}; + case T::Sweep: return {"sweep_path_ref", "target_body"}; + case T::Loft: return {"loft_profile_refs", "target_body"}; + case T::SurfaceLoft: return {"loft_profile_refs"}; + case T::Boolean: return {"target_body", "bool_tool_body"}; + case T::Mirror: + case T::Cut: + case T::Hole: + case T::Thread: return {"plane", "target_body"}; + case T::Helix: return {"plane"}; + case T::Rib: return {"rib_sketch_ref", "rib_entity", "target_body"}; + case T::Mate: return {"mate_cs_a", "mate_cs_b"}; + case T::Fillet: + case T::Chamfer: return {"edges", "face_group", "target_body"}; + case T::Shell: return {"shell_face", "target_body"}; + case T::Draft: return {"draft_face", "target_body"}; + case T::Thicken: return {"thicken_face", "target_body"}; + case T::DeleteFace: return {"delete_faces", "target_body"}; + case T::Plane: + return {"plane_type", "plane_base", "plane_axis", "plane_face_body", "plane_face", "plane_face2_body", "plane_face2", + "plane_edge_body", "plane_edge", "plane_edge2_body", "plane_edge2"}; + case T::Axis: + return {"axis_type", "axis_p1", "axis_p2", "axis_body", "axis_face", "axis_edge", "axis_plane_a", "axis_plane_b"}; + case T::CoordSys: + return {"coordsys_type", "coordsys_point", "coordsys_body", "coordsys_face", "coordsys_edge", "coordsys_x_hint"}; + case T::Pattern: + case T::Transform: + case T::ThickenSurface: + case T::SurfaceOffset: return {"target_body"}; + default: return {}; + } +} + +// Reads the values of feature_edit's refs for features[index] of `doc`, whose body indices and face and edge ids +// name those of `ids`: the model before the feature, or for a datum the finished model, `doc` itself. +struct RefReader +{ + const CadDocument& ids; + const CadDocument& doc; + int index; + bool finished; // `ids` is the finished model, a datum's + std::string at; // feature_label() of the feature + + // Where `ids` stands, as a refusal says it. + std::string where() const { return finished ? "in the finished model" : "before " + at; } + + int integer(const std::string& name, const json& v, const char* what) const + { + if (!v.is_number_integer()) throw std::runtime_error(name + " must be " + what); + return v.get(); + } + + // A feature before the one edited, of one of `types`, which `kinds` names. + int earlier(const std::string& name, const json& v, std::initializer_list types, const char* kinds) const + { + const int fi = integer(name, v, "a feature index (describe_design's features[].index)"); + if (fi < 0 || fi >= index) + throw std::runtime_error(name + " " + std::to_string(fi) + " is not an earlier feature: it must come before " + at); + const CadFeatureType t = doc.features[size_t(fi)].type; + if (std::find(types.begin(), types.end(), t) == types.end()) + throw std::runtime_error(name + " " + std::to_string(fi) + " (" + feature_type_name(t) + ") is not " + kinds); + return fi; + } + + // A body of `ids`, or -1 where `unset` names what -1 stands for. + int body(const std::string& name, const json& v, const char* unset) const + { + const int b = integer(name, v, unset != nullptr ? "a body index, or -1" : "a body index"); + if (unset != nullptr && b == -1) return b; + const int n = int(ids.bodies.size()); + if (b < 0 || b >= n) + throw std::runtime_error(name + " " + std::to_string(b) + " is not a body " + where() + ": there " + + (finished ? (n == 1 ? "is 1 body" : "are " + std::to_string(n) + " bodies") + : (n == 1 ? "was 1 body" : "were " + std::to_string(n) + " bodies"))); + return b; + } + + // The body a feature's target_body names in `ids`: -1 is the last one. + int target(int b) const + { + if (b >= 0) return b; + if (ids.bodies.empty()) throw CadPrecondition("there is no body " + where()); + return int(ids.bodies.size()) - 1; + } + + // Face (`edges` false) or edge ids, each of body `b` of `ids`. + void on_body(const std::vector& list, int b, bool edges) const + { + const TopoDS_Shape& shape = ids.bodies[size_t(b)].shape; + const int n = edges ? GeometryEngine::edge_count(shape) : GeometryEngine::face_count(shape); + const char* kind = edges ? "edge" : "face"; + for (const int id : list) + if (id < 0 || id >= n) + throw std::runtime_error(std::string(kind) + " " + std::to_string(id) + " of body " + std::to_string(b) + " does not exist " + + where() + ": the body " + (finished ? "has " : "had ") + std::to_string(n) + " " + kind + "s" + + (finished ? "" : " there")); + } + + // One id, or for `many` a list of distinct ids. + std::vector id_list(const std::string& name, const json& v, bool many) const + { + std::vector out; + if (many && v.is_array()) { + for (const json& e : v) { + if (!e.is_number_integer()) throw std::runtime_error(name + " must be ids from body_describe"); + if (std::find(out.begin(), out.end(), e.get()) != out.end()) + throw std::runtime_error(name + ": " + std::to_string(e.get()) + " is listed twice"); + out.push_back(e.get()); + } + if (out.empty()) throw std::runtime_error(name + " is an empty list"); + return out; + } + out.push_back(integer(name, v, many ? "an id or a list of ids from body_describe" : "an id from body_describe")); + return out; + } + + // A datum-plane reference: 0, 1 or 2 for XY, XZ or YZ, or 3 + N for the Nth shown Plane feature, which must come + // before the feature edited; -1 where `unset` allows it. + int datum(const std::string& name, const json& v, bool unset) const + { + const int d = integer(name, v, "0, 1 or 2 (XY, XZ or YZ), or 3 + N for the Nth shown datum plane"); + if ((unset && d == -1) || (d >= 0 && d < 3)) return d; + int seen = 0; + for (int i = 0; d >= 3 && i < index; ++i) + if (doc.features[size_t(i)].type == CadFeatureType::Plane && doc.features[size_t(i)].enabled && seen++ == d - 3) + return d; + throw std::runtime_error(name + " " + std::to_string(d) + " names no datum plane before " + at); + } +}; + +// A point or direction [x, y, z] of a datum's refs. +Vec3d vec3_ref(const std::string& name, const json& v, bool direction) +{ + if (!v.is_array() || v.size() != 3 || !v[0].is_number() || !v[1].is_number() || !v[2].is_number()) + throw std::runtime_error(name + " must be [x, y, z]"); + const Vec3d p(v[0].get(), v[1].get(), v[2].get()); + if (direction && !(p.norm() > 1e-9)) throw std::runtime_error(name + " must not be zero"); + return p; +} + +// The refs of a Plane, an Axis and a CoordSys: their types, points and datum references, and bodies, faces and edges +// of the finished model. +void apply_datum_refs(CadFeature& g, const json& refs, const RefReader& r) +{ + using T = CadFeatureType; + const auto given = [&](const char* k) { return refs.contains(k); }; + const auto body = [&](const char* k, int& field) { if (given(k)) field = r.body(k, refs[k], "unset"); }; + const auto id = [&](const char* k, int& field) { if (given(k)) field = r.integer(k, refs[k], "an id from body_describe, or -1"); }; + // A face or an edge set on a body: one of that body's, in the finished model. + const auto check = [&](int b, int ref, bool edges, const char* k) { + if (ref < 0) return; + if (b < 0) throw std::runtime_error(std::string(k) + " " + std::to_string(ref) + " is on no body: give its body too"); + r.on_body({ref}, b, edges); + }; + if (g.type == T::Plane) { + if (given("plane_type")) g.plane_type = PlaneType(enum_index("plane_type", refs["plane_type"], kPlaneTypes)); + if (given("plane_base")) g.plane_base = r.datum("plane_base", refs["plane_base"], false); + if (given("plane_axis")) { + g.plane_axis = r.integer("plane_axis", refs["plane_axis"], "0 (the base's X) or 1 (its Y)"); + if (g.plane_axis != 0 && g.plane_axis != 1) throw std::runtime_error("plane_axis must be 0 (the base's X) or 1 (its Y)"); + } + body("plane_face_body", g.plane_face_body); + id("plane_face", g.plane_face); + body("plane_face2_body", g.plane_face2_body); + id("plane_face2", g.plane_face2); + body("plane_edge_body", g.plane_edge_body); + id("plane_edge", g.plane_edge); + body("plane_edge2_body", g.plane_edge2_body); + id("plane_edge2", g.plane_edge2); + check(g.plane_face_body, g.plane_face, false, "plane_face"); + check(g.plane_face2_body, g.plane_face2, false, "plane_face2"); + check(g.plane_edge_body, g.plane_edge, true, "plane_edge"); + check(g.plane_edge2_body, g.plane_edge2, true, "plane_edge2"); + // What the Plane card's Confirm refuses, which the rebuild would not: an unresolved plane falls back silently. + if (const std::string why = r.doc.datum_plane_refusal(g); !why.empty()) throw std::runtime_error(why); + } else if (g.type == T::Axis) { + if (given("axis_type")) g.axis_type = AxisType(enum_index("axis_type", refs["axis_type"], kAxisTypes)); + if (given("axis_p1")) g.axis_p1 = vec3_ref("axis_p1", refs["axis_p1"], false); + if (given("axis_p2")) g.axis_p2 = vec3_ref("axis_p2", refs["axis_p2"], false); + body("axis_body", g.axis_body); + id("axis_face", g.axis_face); + id("axis_edge", g.axis_edge); + if (given("axis_plane_a")) g.axis_plane_a = r.datum("axis_plane_a", refs["axis_plane_a"], true); + if (given("axis_plane_b")) g.axis_plane_b = r.datum("axis_plane_b", refs["axis_plane_b"], true); + check(g.axis_body, g.axis_face, false, "axis_face"); + check(g.axis_body, g.axis_edge, true, "axis_edge"); + } else { + if (given("coordsys_type")) g.coordsys_type = CoordSysType(enum_index("coordsys_type", refs["coordsys_type"], kCoordSysTypes)); + if (given("coordsys_point")) g.coordsys_point = vec3_ref("coordsys_point", refs["coordsys_point"], false); + if (given("coordsys_x_hint")) g.coordsys_x_hint = vec3_ref("coordsys_x_hint", refs["coordsys_x_hint"], true); + body("coordsys_body", g.coordsys_body); + id("coordsys_face", g.coordsys_face); + id("coordsys_edge", g.coordsys_edge); + check(g.coordsys_body, g.coordsys_face, false, "coordsys_face"); + check(g.coordsys_body, g.coordsys_edge, true, "coordsys_edge"); + } +} + +// The refs of every other type, read in the model before the feature (`r.ids`). +void apply_model_refs(CadFeature& g, const json& refs, const RefReader& r) +{ + using T = CadFeatureType; + const auto given = [&](const char* k) { return refs.contains(k); }; + const CadDocument& doc = r.doc; + if (given("target_body")) g.target_body = r.body("target_body", refs["target_body"], g.type == T::Boolean ? nullptr : "the last body"); + + if (given("revolve_axis_entity")) { + // A line of the sketch the revolve turns, or of the profile it carries itself. + const int e = r.integer("revolve_axis_entity", refs["revolve_axis_entity"], "a line of the feature's sketch (entity index), or -1 for the plane axis"); + const bool own = g.sketch_ref < 0 || g.sketch_ref >= int(doc.features.size()); + if (e != -1 && !revolve_line(own ? g.entities : doc.features[size_t(g.sketch_ref)].entities, e)) + throw std::runtime_error("revolve_axis_entity " + std::to_string(e) + " is not a line of " + + (own ? std::string("its profile") : "sketch " + std::to_string(g.sketch_ref))); + g.revolve_axis_entity = e; + } + if (given("sweep_path_ref")) { + g.sweep_path_ref = r.earlier("sweep_path_ref", refs["sweep_path_ref"], {T::Sketch, T::Helix}, "a Sketch or a Helix"); + if (g.sweep_path_ref == g.sketch_ref) throw std::runtime_error("sweep_path_ref cannot be the profile sketch itself"); + } + if (given("loft_profile_refs")) { + const json& v = refs["loft_profile_refs"]; + if (!v.is_array() || v.size() < 2) throw std::runtime_error("loft_profile_refs must be two or more sketch feature indices, in loft order"); + std::vector profiles; + for (const json& p : v) { + const int s = r.earlier("loft_profile_refs", p, {T::Sketch, T::Project}, "a Sketch"); + if (std::find(profiles.begin(), profiles.end(), s) != profiles.end()) + throw std::runtime_error("loft_profile_refs: sketch " + std::to_string(s) + " is listed twice"); + profiles.push_back(s); + } + g.loft_profile_refs = std::move(profiles); + } + if (given("bool_tool_body")) g.bool_tool_body = r.body("bool_tool_body", refs["bool_tool_body"], nullptr); + // A Boolean's two operands; for every other type bool_tool_body is unused, and target_body -1 is the last body. + if (g.type == T::Boolean && (given("target_body") || given("bool_tool_body")) && g.target_body == g.bool_tool_body) + throw std::runtime_error("target_body and bool_tool_body must be two different bodies"); + + if (given("plane")) { + // A face is one of the model before the feature; a datum's frame is the finished model's, as a card's plane + // list resolves it. A hole or a thread drills the face's own body, as on its card. + const json& v = refs["plane"]; + const bool drill = g.type == T::Hole || g.type == T::Thread; + int face_body = -1; + if (v.is_object() && v.contains("datum")) { + if (const json d = v["datum"]; d.is_number_integer() && (d.get() < 0 || d.get() >= r.index)) + throw std::runtime_error("plane's datum " + std::to_string(d.get()) + " is not an earlier feature: it must come before " + r.at); + g.plane = cad_resolve_plane(v, doc, drill); + } else { + g.plane = cad_resolve_plane(v, r.ids, drill, &face_body); + } + if (g.type == T::Cut) g.cut_face = g.cut_face_body = -1; // a split along the plane, not along a face + if (drill && face_body >= 0) { + if (given("target_body") && g.target_body != face_body) + throw std::runtime_error("the plane is a face of body " + std::to_string(face_body) + ", so that body is drilled, not body " + + std::to_string(g.target_body)); + g.target_body = face_body; + } + } + if (given("rib_sketch_ref")) g.rib_sketch_ref = r.earlier("rib_sketch_ref", refs["rib_sketch_ref"], {T::Sketch}, "a Sketch"); + if (given("rib_entity")) g.rib_entity = r.integer("rib_entity", refs["rib_entity"], "a line of the rib's sketch (entity index)"); + if ((given("rib_sketch_ref") || given("rib_entity")) && + !(g.rib_sketch_ref >= 0 && g.rib_sketch_ref < int(doc.features.size()) && + revolve_line(doc.features[size_t(g.rib_sketch_ref)].entities, g.rib_entity))) + throw std::runtime_error("rib_entity " + std::to_string(g.rib_entity) + " is not a line of sketch " + std::to_string(g.rib_sketch_ref)); + if (given("mate_cs_a")) g.mate_cs_a = r.earlier("mate_cs_a", refs["mate_cs_a"], {T::CoordSys}, "a CoordSys"); + if (given("mate_cs_b")) g.mate_cs_b = r.earlier("mate_cs_b", refs["mate_cs_b"], {T::CoordSys}, "a CoordSys"); + if ((given("mate_cs_a") || given("mate_cs_b")) && g.mate_cs_a == g.mate_cs_b) + throw std::runtime_error("mate_cs_a and mate_cs_b must be two different coordinate systems"); + + if (given("edges") && given("face_group")) throw std::runtime_error("give edges or face_group, not both"); + if (given("edges")) { + const std::vector edges = r.id_list("edges", refs["edges"], true); + g.dressup_edge = edges.front(); + g.dressup_edges = edges.size() > 1 ? edges : std::vector(); + } + if (given("face_group")) { + const std::optional group = face_group_named(refs["face_group"]); + if (!group) throw std::runtime_error("face_group must be " + kFaceGroupWords); + g.face_group = *group; + g.dressup_edge = -1; + g.dressup_edges.clear(); + } + if (given("shell_face")) { + g.shell_face = r.integer("shell_face", refs["shell_face"], "a face id from body_describe, or -1 for a closed hollow"); + if (g.shell_face < -1) throw std::runtime_error("shell_face must be a face id from body_describe, or -1 for a closed hollow"); + } + if (given("draft_face")) g.draft_face = r.id_list("draft_face", refs["draft_face"], false).front(); + if (given("thicken_face")) g.thicken_face = r.id_list("thicken_face", refs["thicken_face"], false).front(); + if (given("delete_faces")) { + if (!refs["delete_faces"].is_array()) throw std::runtime_error("delete_faces must be a list of face ids from body_describe"); + g.delete_faces = r.id_list("delete_faces", refs["delete_faces"], true); + } + + // The faces and edges the feature works on, of its target body as it stood before the feature, whichever of the + // two changed. + const bool retarget = given("target_body"); + const int shown = g.target_body; + if ((g.type == T::Fillet || g.type == T::Chamfer) && (retarget || given("edges")) && !g.dressup_edge_ids().empty()) + r.on_body(g.dressup_edge_ids(), r.target(shown), true); + if (g.type == T::Shell && (retarget || given("shell_face")) && g.shell_face >= 0) r.on_body({g.shell_face}, r.target(shown), false); + if (g.type == T::Draft && (retarget || given("draft_face"))) r.on_body({g.draft_face}, r.target(shown), false); + if (g.type == T::Thicken && (retarget || given("thicken_face"))) r.on_body({g.thicken_face}, r.target(shown), false); + if (g.type == T::DeleteFace && (retarget || given("delete_faces"))) r.on_body(g.delete_faces, r.target(shown), false); +} + +} // namespace + +void cad_apply_feature_refs(CadFeature& f, const json& refs, const CadDocument& before, const CadDocument& doc, int index) +{ + using T = CadFeatureType; + const std::string type = feature_type_name(f.type); + if (f.type == T::Extrude) throw std::runtime_error("Extrude: its profile and its target are fixed"); + if (!refs.is_object() || refs.empty()) throw std::runtime_error("refs must name the references to change, as {\"sweep_path_ref\": 2}"); + const std::vector names = ref_names(f.type); + std::string list; + for (const std::string& n : names) list += (list.empty() ? "" : ", ") + n; + for (const auto& [name, v] : refs.items()) + if (std::find(names.begin(), names.end(), name) == names.end()) + throw std::runtime_error(names.empty() ? type + ": its card picks nothing again, so refs takes no name; '" + name + "' is not one" + : type + " takes " + list + " in refs, not '" + name + "'"); + const bool datum = f.type == T::Plane || f.type == T::Axis || f.type == T::CoordSys; + const RefReader r{datum ? doc : before, doc, index, datum, feature_label(doc, index)}; + CadFeature g = f; + if (datum) apply_datum_refs(g, refs, r); + else apply_model_refs(g, refs, r); + f = std::move(g); +} + +void history_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"feature_describe", action_feature_describe}, + {"feature_set_expression", action_feature_set_expression}, + {"feature_edit", action_feature_edit}, + {"feature_delete", action_feature_delete}, + {"feature_move", action_feature_move}, + {"feature_suppress", action_feature_suppress}, + {"feature_rename", action_feature_rename}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp new file mode 100644 index 0000000000..f562f73472 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp @@ -0,0 +1,599 @@ +// The place Design, its Inspect heading: body_describe, a body's faces and edges with their ids; measure; +// body_mass_properties; body_section; body_compare, a body against a reference; and interference. +// inspect_silent_forms() binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs them behind the +// Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// The kinds body_describe gives faces, in GeomAbs_SurfaceType order (the edges' are kEdgeKinds). +const char* const kFaceKinds[] = {"planar", "cylindrical", "conical", "spherical", "toroidal", "bezier", + "bspline", "revolution", "extrusion", "offset", "other"}; +static_assert(std::size(kFaceKinds) == size_t(GeomAbs_OtherSurface) + 1, "every surface type needs a kind"); + +// The kinds body_describe gives edges, by edge_kind(). +const char* const kEdgeKinds[] = {"line", "circle", "ellipse", "bspline", "bezier", "other"}; + +// The kind of an edge's curve, its index in kEdgeKinds. +int edge_kind(GeomAbs_CurveType t) +{ + switch (t) { + case GeomAbs_Line: return 0; + case GeomAbs_Circle: return 1; + case GeomAbs_Ellipse: return 2; + case GeomAbs_BSplineCurve: return 3; + case GeomAbs_BezierCurve: return 4; + default: return 5; + } +} + +} // namespace + +// ---- Shared with the other Design files (DesignCommon.hpp) ---------------------------------- + +const char* edge_kind_name(const TopoDS_Edge& e) { return kEdgeKinds[edge_kind(BRepAdaptor_Curve(e).GetType())]; } + +const char* face_kind_name(const TopoDS_Face& f) { return kFaceKinds[BRepAdaptor_Surface(f).GetType()]; } + +namespace { + +// Resolve body index -> shape, throwing a clear error if out of range / null. +const TopoDS_Shape& body_shape(const CadDocument& doc, const json& params) +{ + int idx = params.value("body", 0); + if (idx < 0 || idx >= int(doc.bodies.size())) + throw std::runtime_error("body index out of range (have " + std::to_string(doc.bodies.size()) + ")"); + if (doc.bodies[idx].shape.IsNull()) + throw CadPrecondition("body has no shape"); + return doc.bodies[idx].shape; +} + +json body_describe(DesignPanel* panel, const json& params) { return cad_body_describe(panel->mcp_doc(), params); } + +json measure(DesignPanel* panel, const json& params) { return cad_measure(panel->mcp_doc(), params); } + +json body_mass_properties(DesignPanel* panel, const json& params) +{ + const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); + auto mp = GeometryEngine::mass_properties(shape); + if (!mp.valid) throw CadKernelFailure("mass properties could not be computed"); + // A sheet body has no volume and no inertia. Report the area and say so, rather than + // returning numbers a caller would reasonably treat as a material check. + if (!mp.is_solid) + return json{ + {"surface_area", mp.surface_area}, + {"volume", 0.0}, + {"is_solid", false}, + {"valid", mp.valid}, + {"note", "sheet body (open shell): it encloses no material, so volume and inertia " + "are not defined; surface_area is exact"}, + }; + return json{ + {"volume", mp.volume}, + {"surface_area", mp.surface_area}, + {"center_of_mass", json::array({mp.center_of_mass.x(), mp.center_of_mass.y(), mp.center_of_mass.z()})}, + {"inertia", mp.inertia}, + {"is_solid", true}, + {"valid", mp.valid}, + }; +} + +// Chain raw section segments (each a sampled-edge polyline) into ordered contours by joining +// endpoints within tol. Grows the tail; when the tail is stuck, reverses the contour and grows +// the other end. A contour is closed when its two ends meet. OCCT section vertices are exact, +// so a small absolute tol suffices. +std::vector, bool>> +chain_segments(std::vector> segs, double tol) +{ + std::vector, bool>> contours; + std::vector used(segs.size(), 0); + auto meets = [&](const Vec3d& a, const Vec3d& b) { return (a - b).norm() <= tol; }; + for (size_t i = 0; i < segs.size(); ++i) { + if (used[i] || segs[i].size() < 2) continue; + used[i] = 1; + std::vector c = segs[i]; + for (int side = 0; side < 2; ) { // grow tail; reverse once when stuck + bool grew = false; + for (size_t j = 0; j < segs.size(); ++j) { + if (used[j] || segs[j].size() < 2) continue; + if (meets(c.back(), segs[j].front())) { + c.insert(c.end(), segs[j].begin() + 1, segs[j].end()); used[j] = 1; grew = true; + } else if (meets(c.back(), segs[j].back())) { + for (auto it = segs[j].rbegin() + 1; it != segs[j].rend(); ++it) c.push_back(*it); + used[j] = 1; grew = true; + } + } + if (grew) { side = 0; continue; } + std::reverse(c.begin(), c.end()); ++side; // try the other end + } + bool closed = c.size() > 2 && meets(c.front(), c.back()); + contours.emplace_back(std::move(c), closed); + } + return contours; +} + +// sections-as-evidence: cross-section of a body by a named base plane at an offset. +json body_section(DesignPanel* panel, const json& params) +{ + const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); + const std::string plane_name = params.value("plane", std::string("XY")); + const double offset = params.value("offset", 0.0); + // Base plane normal; offset shifts the plane along it. + gp_Dir n = plane_name == "XZ" ? gp_Dir(0, 1, 0) + : plane_name == "YZ" ? gp_Dir(1, 0, 0) + : gp_Dir(0, 0, 1); + gp_Pnt o(n.X() * offset, n.Y() * offset, n.Z() * offset); + BRepAlgoAPI_Section sect(shape, gp_Pln(o, n), false); + sect.ComputePCurveOn1(false); + sect.Approximation(true); + sect.Build(); + if (!sect.IsDone()) throw CadKernelFailure("section failed"); + std::vector> segs; + for (TopExp_Explorer ex(sect.Shape(), TopAbs_EDGE); ex.More(); ex.Next()) { + std::vector pts = GeometryEngine::sample_edge_world(TopoDS::Edge(ex.Current())); + if (pts.size() >= 2) segs.push_back(std::move(pts)); + } + const int raw = int(segs.size()); + auto contours = chain_segments(std::move(segs), 1e-3); + json jcont = json::array(); + int closed_n = 0; + for (auto& pc : contours) { + if (pc.second) ++closed_n; + json pts = json::array(); + for (const Vec3d& p : pc.first) pts.push_back(vec3(p)); + jcont.push_back(json{{"closed", pc.second}, {"points", std::move(pts)}}); + } + return json{{"body", params.value("body", 0)}, {"plane", plane_name}, {"offset", offset}, + {"segment_count", raw}, {"contour_count", int(contours.size())}, + {"closed_count", closed_n}, {"contours", std::move(jcont)}}; +} + +// ---- Validate: volume + bbox deviation of a body vs a reference (the "scarto %") ---------------- +// ponytail: volume delta + bbox/centroid offset (the RE skill's actual acceptance metric). +// Surface-deviation heat-map is the upgrade path (per-vertex BRepExtrema), add when needed. +struct ShapeMetrics { double volume; Vec3d centroid, bmin, bmax; }; +ShapeMetrics shape_metrics(const TopoDS_Shape& s) +{ + GProp_GProps vp; BRepGProp::VolumeProperties(s, vp); + gp_Pnt c = vp.CentreOfMass(); + Bnd_Box bb; BRepBndLib::Add(s, bb); + double x0, y0, z0, x1, y1, z1; bb.Get(x0, y0, z0, x1, y1, z1); + return {vp.Mass(), Vec3d(c.X(), c.Y(), c.Z()), Vec3d(x0, y0, z0), Vec3d(x1, y1, z1)}; +} + +json body_compare(DesignPanel* panel, const json& params) +{ + const TopoDS_Shape& cand = body_shape(panel->mcp_doc(), params); // candidate = the reconstruction + if (!params.contains("reference")) throw std::runtime_error("body_compare needs 'reference' {step|body}"); + const json& r = params["reference"]; + + TopoDS_Shape ref; + if (r.contains("step")) { + std::string err; + std::vector solids = GeometryEngine::read_step_solids(input_path(r["step"], "reference.step"), err); + if (solids.empty()) throw std::runtime_error(err.empty() ? "reference STEP has no solids" : err); + BRep_Builder b; TopoDS_Compound comp; b.MakeCompound(comp); + for (const TopoDS_Shape& s : solids) if (!s.IsNull()) b.Add(comp, s); + ref = comp; + } else if (r.contains("body")) { + CadDocument& doc = panel->mcp_doc(); + int idx = r["body"].get(); + if (idx < 0 || idx >= int(doc.bodies.size()) || doc.bodies[idx].shape.IsNull()) + throw std::runtime_error("reference body index out of range / null"); + ref = doc.bodies[idx].shape; + } else { + throw std::runtime_error("reference must be {\"step\": path} or {\"body\": id}"); + } + + ShapeMetrics a = shape_metrics(cand), b = shape_metrics(ref); + double dv = b.volume > 0 ? (a.volume - b.volume) / b.volume * 100.0 : 0.0; + Vec3d coff = a.centroid - b.centroid; + Vec3d dmin = a.bmin - b.bmin, dmax = a.bmax - b.bmax; + // Surface-level deviation (one-sided Hausdorff, candidate vertices -> reference solid): + // catches local shape error that matching volume + bbox can hide. + GeometryEngine::Deviation dev = GeometryEngine::surface_deviation(cand, ref); + return json{ + {"volume", a.volume}, {"volume_reference", b.volume}, {"volume_delta_pct", dv}, + {"centroid_offset", vec3(coff)}, {"centroid_offset_mm", coff.norm()}, + {"bbox", json{{"min", vec3(a.bmin)}, {"max", vec3(a.bmax)}}}, + {"bbox_reference", json{{"min", vec3(b.bmin)}, {"max", vec3(b.bmax)}}}, + {"bbox_delta", json{{"min", vec3(dmin)}, {"max", vec3(dmax)}}}, + {"surface_deviation", json{{"max_mm", dev.max_mm}, {"mean_mm", dev.mean_mm}, + {"rms_mm", dev.rms_mm}, {"samples", dev.sample_count}}}, + }; +} + +json action_check_interference(DesignPanel* panel, const json& params) +{ + const double min_volume = params.value("min_volume", 1e-6); + CadDocument& doc = panel->mcp_doc(); + // Read-only: no checkpoint(), no recompute(), no mcp_after_change(). + const auto hits = doc.check_interference(min_volume); + json arr = json::array(); + for (const auto& h : hits) { + arr.push_back(json{{"body_a", h.body_a}, {"body_b", h.body_b}, {"volume", h.volume}}); + } + return json{{"ok", true}, {"count", int(hits.size())}, {"interferences", arr}}; +} + +} // namespace + +std::vector cad_body_vertices(const CadDocument& doc, int body) +{ + TopTools_IndexedMapOfShape map; + TopExp::MapShapes(body_shape(doc, json{{"body", body}}), TopAbs_VERTEX, map); + std::vector out; + out.reserve(size_t(map.Extent())); + for (int i = 1; i <= map.Extent(); ++i) { + const gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(map(i))); + out.emplace_back(p.X(), p.Y(), p.Z()); + } + return out; +} + +json cad_body_describe(const CadDocument& doc, const json& params) +{ + if (const json before = params.value("before", json()); !before.is_null()) { + if (!before.is_number_integer()) throw std::runtime_error("before must be a feature index (describe_design's features[].index)"); + json as_of = params; + as_of.erase("before"); + json out = cad_body_describe(cad_document_before(doc, before.get()), as_of); + out["before"] = before; + // The ids are the model's before that feature, read at the live document's generation, which a call passing + // them is checked against. + out["generation"] = doc.topo_generation; + return out; + } + const json vertices = params.value("vertices", json(false)); + if (!vertices.is_boolean()) throw std::runtime_error("vertices must be true or false"); + const TopoDS_Shape& shape = body_shape(doc, params); + + // Filters. Each narrows the list it applies to; direction applies to both. + auto kind_list = [&](const char* key, const auto& names) { + std::vector out; + const json v = params.value(key, json()); + if (v.is_null()) return out; + if (!v.is_array()) throw std::runtime_error(std::string(key) + " must be a list of kinds"); + // A face kind by its surface's noun, as agents often name it: plane for planar. + static const std::map nouns{ + {"plane", "planar"}, {"cylinder", "cylindrical"}, {"cone", "conical"}, {"sphere", "spherical"}, {"torus", "toroidal"}}; + for (const json& k : v) { + const auto noun = k.is_string() && std::string(key) == "kinds" ? nouns.find(k.get()) : nouns.end(); + out.push_back(enum_index(key, noun == nouns.end() ? k : json(noun->second), names)); + } + return out; + }; + const std::vector kinds = kind_list("kinds", kFaceKinds); + const std::vector edge_kinds = kind_list("edge_kinds", kEdgeKinds); + std::optional direction; + if (const json d = params.value("direction", json()); !d.is_null()) { + if (!d.is_array() || d.size() != 3 || !d[0].is_number() || !d[1].is_number() || !d[2].is_number()) + throw std::runtime_error("direction must be [x, y, z]"); + const Vec3d v(d[0].get(), d[1].get(), d[2].get()); + if (!(v.norm() > 1e-9)) throw std::runtime_error("direction must not be zero"); + direction = v.normalized(); + } + const json convex = params.value("convex", json()); + if (!convex.is_null() && !convex.is_boolean()) throw std::runtime_error("convex must be true or false"); + int extreme = -1; // index into kExtremes: axis = extreme / 2, the + side when it is even + static const char* const kExtremes[] = {"+x", "-x", "+y", "-y", "+z", "-z"}; + if (const json e = params.value("at_extreme", json()); !e.is_null()) extreme = enum_index("at_extreme", e, kExtremes); + const json adj = params.value("adjacency", json(false)); + if (!adj.is_boolean()) throw std::runtime_error("adjacency must be true or false"); + const bool adjacency = adj.get() || !convex.is_null(); + const json lim = params.value("limit", json()), off = params.value("offset", json()); + if (!lim.is_null() && !(lim.is_number_integer() && lim.get() >= 1)) throw std::runtime_error("limit must be an integer >= 1"); + if (!off.is_null() && !(off.is_number_integer() && off.get() >= 0)) throw std::runtime_error("offset must be an integer >= 0"); + const double kParallel = std::cos(M_PI / 180.0); // within 1 degree + + // Enumerate once. The _by_index accessors rescan the shape on every call (edge_by_index + // rebuilds the whole indexed map), so indexing a body face-by-face is quadratic: ~15 s on a + // 4.7k-face imported solid, on the UI thread. faces_of/edges_of keep the very same ids. + const std::vector faces = GeometryEngine::faces_of(shape); + const std::vector edges = GeometryEngine::edges_of(shape); + const int nf = int(faces.size()), ne = int(edges.size()); + std::vector> edge_faces, face_edges; + std::vector> convexity(ne); // only for an edge between two faces + if (adjacency) { + edge_faces = GeometryEngine::edge_faces(shape); + face_edges.resize(nf); + for (int e = 0; e < ne; ++e) { + for (int f : edge_faces[e]) face_edges[f].push_back(e); + if (edge_faces[e].size() == 2) + convexity[e] = GeometryEngine::edge_convexity(edges[e], faces[edge_faces[e][0]], faces[edge_faces[e][1]]); + } + } + std::vector> surfaces(nf); + auto surface = [&](int f) -> const GeometryEngine::SurfaceInfo& { + if (!surfaces[f]) surfaces[f] = GeometryEngine::surface_info(faces[f]); + return *surfaces[f]; + }; + double ext_at = 0, ext_tol = 0; + if (extreme >= 0) { + Bnd_Box box; + BRepBndLib::AddOptimal(shape, box, false, false); + double lo[3], hi[3]; + box.Get(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]); + ext_at = extreme % 2 == 0 ? hi[extreme / 2] : lo[extreme / 2]; + ext_tol = std::max(1e-3, 1e-6 * Vec3d(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]).norm()); + } + + auto face_matches = [&](int f) { + const GeometryEngine::SurfaceInfo& s = surface(f); + if (!kinds.empty() && std::find(kinds.begin(), kinds.end(), int(s.type)) == kinds.end()) return false; + // A normal is the face's own only on a plane; elsewhere it is one point's. + if (direction && (s.type != GeomAbs_Plane || GeometryEngine::face_normal_world(faces[f]).dot(*direction) < kParallel)) + return false; + return extreme < 0 || std::abs(s.centroid[extreme / 2] - ext_at) <= ext_tol; + }; + auto edge_matches = [&](int e) { + const BRepAdaptor_Curve c(edges[e]); + if (!edge_kinds.empty() && std::find(edge_kinds.begin(), edge_kinds.end(), edge_kind(c.GetType())) == edge_kinds.end()) + return false; + if (direction) { + if (c.GetType() != GeomAbs_Line) return false; + const gp_Dir t = c.Line().Direction(); + if (std::abs(Vec3d(t.X(), t.Y(), t.Z()).dot(*direction)) < kParallel) return false; + } + return convex.is_null() || (convexity[e] && *convexity[e] == (convex.get() ? 1 : -1)); + }; + + const bool face_filter = !kinds.empty() || direction || extreme >= 0; + const bool edge_filter = !edge_kinds.empty() || direction || !convex.is_null(); + std::vector face_ids, edge_ids; + for (int f = 0; f < nf; ++f) + if ((!face_filter && !edge_filter) || (face_filter && face_matches(f))) face_ids.push_back(f); + // A degenerate edge (a cone's apex) has no length and is not listed. + for (int e = 0; e < ne; ++e) + if (!BRep_Tool::Degenerated(edges[e]) && ((!face_filter && !edge_filter) || (edge_filter && edge_matches(e)))) + edge_ids.push_back(e); + // With adjacency, a list none of whose filters was given holds the neighbours of the other's matches. + auto neighbours = [](const std::vector& of, const std::vector>& links, size_t n) { + std::vector hit(n, false); + for (int i : of) + for (int j : links[i]) hit[j] = true; + std::vector out; + for (size_t j = 0; j < n; ++j) + if (hit[j]) out.push_back(int(j)); + return out; + }; + if (adjacency && edge_filter && !face_filter) face_ids = neighbours(edge_ids, edge_faces, nf); + if (adjacency && face_filter && !edge_filter) edge_ids = neighbours(face_ids, face_edges, ne); + + const size_t first = off.is_null() ? 0 : off.get(); + const size_t count = lim.is_null() ? std::max(face_ids.size(), edge_ids.size()) : lim.get(); + json jfaces = json::array(); + for (size_t k = first; k < face_ids.size() && k - first < count; ++k) { + const int f = face_ids[k]; + const GeometryEngine::SurfaceInfo& s = surface(f); + json jf{{"id", f}, {"kind", kFaceKinds[s.type]}, {"area", s.area}, {"centroid", vec3(s.centroid)}, + {"normal", vec3(GeometryEngine::face_normal_world(faces[f]))}}; + switch (s.type) { + case GeomAbs_Cylinder: + jf["radius"] = s.radius; jf["axis"] = vec3(s.axis); jf["internal"] = s.internal; + break; + case GeomAbs_Cone: + jf["apex"] = vec3(s.location); jf["axis"] = vec3(s.axis); jf["half_angle_deg"] = s.half_angle * 180.0 / M_PI; + jf["radius_min"] = s.radius; jf["radius_max"] = s.radius2; jf["internal"] = s.internal; + break; + case GeomAbs_Sphere: + jf["center"] = vec3(s.location); jf["radius"] = s.radius; jf["internal"] = s.internal; + break; + case GeomAbs_Torus: + jf["center"] = vec3(s.location); jf["axis"] = vec3(s.axis); + jf["major_radius"] = s.radius; jf["minor_radius"] = s.radius2; + break; + default: break; + } + if (adjacency) jf["edges"] = face_edges[f]; + jfaces.push_back(std::move(jf)); + } + json jedges = json::array(); + for (size_t k = first; k < edge_ids.size() && k - first < count; ++k) { + const int e = edge_ids[k]; + const std::vector pts = GeometryEngine::sample_edge_world(edges[e]); + if (pts.size() < 2) continue; + double len = 0; + for (size_t i = 1; i < pts.size(); ++i) len += (pts[i] - pts[i - 1]).norm(); + const BRepAdaptor_Curve c(edges[e]); + json je{{"id", e}, {"kind", kEdgeKinds[edge_kind(c.GetType())]}, {"length", len}, {"p0", vec3(pts.front())}, {"p1", vec3(pts.back())}}; + if (c.GetType() == GeomAbs_Circle) { + const GeometryEngine::CylinderFace circ = GeometryEngine::circle_of_edge(edges[e]); + je["radius"] = circ.radius; + je["center"] = vec3(circ.base); + } else if (c.GetType() == GeomAbs_Ellipse) { + const gp_Elips el = c.Ellipse(); + je["center"] = json::array({el.Location().X(), el.Location().Y(), el.Location().Z()}); + je["major_radius"] = el.MajorRadius(); + je["minor_radius"] = el.MinorRadius(); + } + if (adjacency) { + je["faces"] = edge_faces[e]; + if (convexity[e] && *convexity[e] != 0) je["convex"] = *convexity[e] > 0; + else if (convexity[e]) je["tangent"] = true; + } + jedges.push_back(std::move(je)); + } + json out{{"body", params.value("body", 0)}, {"face_count", nf}, {"edge_count", ne}, + {"faces_total", face_ids.size()}, {"edges_total", edge_ids.size()}, + {"faces", std::move(jfaces)}, {"edges", std::move(jedges)}, + // The ids above are indices into this exact topology and expire with it. Echo + // this back as "generation" on the calls that consume them. + {"generation", doc.topo_generation}}; + if (first + count < std::max(face_ids.size(), edge_ids.size())) out["next_offset"] = first + count; + if (vertices.get()) { + json jvertices = json::array(); + const std::vector points = cad_body_vertices(doc, params.value("body", 0)); + for (size_t v = 0; v < points.size(); ++v) jvertices.push_back(json{{"id", int(v)}, {"p", vec3(points[v])}}); + out["vertices"] = std::move(jvertices); + } + return out; +} + +namespace { + +// One measure ref: its shape, the point that stands for it (a face's centroid, an edge's middle +// sample, an axis's middle, the point itself) and, but for a point, a direction (a face's normal, +// an edge's chord, an axis). `planar` is set for a planar face. +TopoDS_Shape measure_ref(const CadDocument& doc, const json& params, const char* name, Vec3d& point, + std::optional& dir, bool& planar) +{ + const json& ref = params.at(name); + const std::string what = std::string("could not resolve ref \"") + name + "\": "; + planar = false; + dir.reset(); + if (!ref.is_object() || int(ref.contains("face")) + int(ref.contains("edge")) + int(ref.contains("point")) != 1) + throw std::runtime_error(what + "a ref is {\"face\": f}, {\"edge\": e} or {\"point\": [x, y, z]}, with an optional \"body\""); + if (ref.contains("point")) { + const json& p = ref.at("point"); + if (!p.is_array() || p.size() != 3 || !p[0].is_number() || !p[1].is_number() || !p[2].is_number()) + throw std::runtime_error(what + "point must be [x, y, z]"); + point = Vec3d(p[0].get(), p[1].get(), p[2].get()); + return BRepBuilderAPI_MakeVertex(gp_Pnt(point.x(), point.y(), point.z())).Vertex(); + } + const json bv = ref.contains("body") ? ref.at("body") : params.value("body", json(0)); + if (!bv.is_number_integer()) throw std::runtime_error(what + "body must be a body index"); + const int b = bv.get(); + if (b < 0 || b >= int(doc.bodies.size()) || doc.bodies[b].shape.IsNull()) + throw std::runtime_error(what + "body " + std::to_string(b) + " is out of range (have " + std::to_string(doc.bodies.size()) + ")"); + const TopoDS_Shape& shape = doc.bodies[b].shape; + const json axis = ref.value("axis", json(false)); + if (!axis.is_boolean()) throw std::runtime_error(what + "axis must be true or false"); + const std::string on_body = " of body " + std::to_string(b); + if (ref.contains("face")) { + if (!ref.at("face").is_number_integer()) throw std::runtime_error(what + "face must be a face id"); + const int fi = ref.at("face").get(); + const TopoDS_Face f = GeometryEngine::face_by_index(shape, fi); + if (f.IsNull()) + throw std::runtime_error(what + "face " + std::to_string(fi) + on_body + " does not exist (it has " + + std::to_string(GeometryEngine::face_count(shape)) + " faces)"); + if (axis.get()) { + // A cylinder's axis over the face's length: a hole's centre line, for distances to it. + const GeometryEngine::CylinderFace c = GeometryEngine::cylinder_of_face(f); + if (!c.ok) + throw std::runtime_error(what + "face " + std::to_string(fi) + on_body + " is " + face_kind_name(f) + + "; axis takes a cylindrical face"); + const Vec3d top = c.base + c.axis * c.height; + point = 0.5 * (c.base + top); + dir = c.axis; + return BRepBuilderAPI_MakeEdge(gp_Pnt(c.base.x(), c.base.y(), c.base.z()), gp_Pnt(top.x(), top.y(), top.z())).Edge(); + } + point = GeometryEngine::face_centroid_world(f); + dir = GeometryEngine::face_normal_world(f); + planar = BRepAdaptor_Surface(f).GetType() == GeomAbs_Plane; + return f; + } + if (axis.get()) throw std::runtime_error(what + "axis takes a cylindrical face"); + if (!ref.at("edge").is_number_integer()) throw std::runtime_error(what + "edge must be an edge id"); + const int ei = ref.at("edge").get(); + const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, ei); + if (e.IsNull()) + throw std::runtime_error(what + "edge " + std::to_string(ei) + on_body + " does not exist (it has " + + std::to_string(GeometryEngine::edge_count(shape)) + " edges)"); + const std::vector pts = GeometryEngine::sample_edge_world(e); + if (pts.size() < 2) throw std::runtime_error(what + "edge " + std::to_string(ei) + on_body + " has no length"); + point = pts[pts.size() / 2]; // the middle sample + dir = (pts.back() - pts.front()).normalized(); + return e; +} + +} // namespace + +json cad_measure(const CadDocument& doc, const json& params) +{ + if (!params.is_object() || !params.contains("a") || !params.contains("b")) + throw std::runtime_error("measure needs refs 'a' and 'b' ({face|edge|point})"); + Vec3d pa, pb; + std::optional da, db; + bool planar_a = false, planar_b = false; + const TopoDS_Shape sa = measure_ref(doc, params, "a", pa, da, planar_a); + const TopoDS_Shape sb = measure_ref(doc, params, "b", pb, db, planar_b); + json r{{"distance", (pa - pb).norm()}, {"point_a", vec3(pa)}, {"point_b", vec3(pb)}}; + if (da && db) { + const double c = std::max(-1.0, std::min(1.0, da->normalized().dot(db->normalized()))); + r["angle_deg"] = std::acos(c) * 180.0 / M_PI; + } + Vec3d ca, cb; + const double d = GeometryEngine::min_distance(sa, sb, ca, cb); + if (d < 0) throw CadKernelFailure("the minimum distance between the refs could not be computed"); + r["min_distance"] = d; + r["closest_a"] = vec3(ca); + r["closest_b"] = vec3(cb); + // The clearance between two parallel planar faces, as a lid fit wants it: across the gap, not + // along it. + if (planar_a && planar_b && da->cross(*db).norm() < 1e-6) r["parallel_gap"] = std::abs((pb - pa).dot(*da)); + return r; +} + +void inspect_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"body_describe", body_describe}, + {"measure", measure}, + {"body_mass_properties", body_mass_properties}, + {"body_section", body_section}, + {"body_compare", body_compare}, + {"interference", action_check_interference}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp new file mode 100644 index 0000000000..321066b14d --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp @@ -0,0 +1,1708 @@ +// The place Design, its Sketch heading: sketch_create, sketch_edit, sketch_finish and sketch_cancel, which open and +// close a sketch; sketch_describe, sketch_validate, sketch_repair and sketch_list_constraints, which read and mend +// one; sketch_project, sketch_text, sketch_insert_svg and sketch_blend_curve, which add curves made from edges, text, +// an SVG file or two other curves; and the verbs that draw, edit and constrain the open sketch's entities +// (sketch_draw, sketch_constrain, sketch_dimension and the rest), each on the DesignSketchTool the mouse drives. +// sketch_silent_forms() binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs them behind the +// Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignSketchTool.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/SketchSolver.hpp" +#include "libslic3r/CAD/SketchImport.hpp" // svg_to_regions, transform_regions +#include + +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// ---- 2D sketch verbs ---------------------------------------------------------------------------- +// +// The model is FreeCAD's Sketcher, adapted to this tab's right-click world. Three ideas are +// taken over deliberately: +// +// * GEOMETRY IS SEPARATE FROM CONSTRAINTS. You add curves, then you constrain them; the +// solver reports degrees of freedom and whether it is consistent. `sketch_describe` returns +// both halves plus the DoF, which is the whole state a caller needs to reason about. +// * A SKETCH IS JUDGED BY ITS LOOPS, not by its coordinates. FreeCAD asks whether the profile +// is closed before it will build from it; `sketch_describe` answers that directly, listing +// each closed loop, the loops it encloses as VOIDS, and — the actionable part — the exact +// plane coordinates where a chain is still open. +// * VALIDATE, THEN FIX. FreeCAD's ValidateSketch finds vertices that overlap within a +// tolerance but carry no coincidence, and adds the missing ones. `sketch_validate` reports +// them, `sketch_repair` welds and constrains them. That is what turns a loop that is closed by +// floating-point luck into one that is closed by construction and stays closed through +// every later solve. +// +// What is NOT taken over: FreeCAD's Sketcher is a modal dialog with its own toolbars. Here the +// vocabulary is the right-click offer, so these verbs are named after what the menu offers on a +// selection, and every one of them drives the SAME DesignSketchTool the mouse drives. + +DesignSketchTool& mcp_sketch(DesignPanel* panel) +{ + DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + if (!vp->is_sketching()) + throw CadPrecondition("no sketch is open — call sketch_create first"); + return vp->mcp_sketch_tool(); +} + +// An [x, y] point in the sketch plane, named `what` in the error. +Vec2d point_of(const json& v, const std::string& what) +{ + if (!v.is_array() || v.size() != 2 || !v[0].is_number() || !v[1].is_number()) + throw std::runtime_error(what + " must be [x, y]"); + return Vec2d(v[0].get(), v[1].get()); +} + +Vec2d point_arg(const json& j, const char* key) { return point_of(j.value(key, json()), key); } + +// A required finite number. +double number_arg(const json& j, const char* key) +{ + const json v = j.value(key, json()); + if (!v.is_number() || !std::isfinite(v.get())) throw std::runtime_error(std::string(key) + " must be a number"); + return v.get(); +} + +// An angle in radians as `key`, or in degrees as `key`_deg; `def` (radians) when neither is given. +double angle_arg(const json& j, const std::string& key, double def) +{ + const std::string deg = key + "_deg"; + if (j.contains(key) && j.contains(deg)) throw std::runtime_error("give " + key + " or " + deg + ", not both"); + if (j.contains(deg)) return number_arg(j, deg.c_str()) * M_PI / 180.0; + return j.contains(key) ? number_arg(j, key.c_str()) : def; +} + +SketchEntity sketch_entity_from(const json& j) +{ + const std::string t = j.value("type", std::string("")); + SketchEntity e; + auto p = [&](const char* k, double dx, double dy) { + if (!j.contains(k)) return Vec2d(dx, dy); + const json& a = j.at(k); + if (!a.is_array() || a.size() < 2) throw std::runtime_error(std::string(k) + " must be [x, y]"); + return Vec2d(a[0].get(), a[1].get()); + }; + e.construction = j.value("construction", false); + // A circle and an arc are defined BY their centre, so a request that does not carry one is + // incomplete, not a request for a circle at the origin. Defaulting it silently put geometry + // somewhere the caller never asked for and then reported perfectly consistent loops, areas + // and hole attribution ABOUT THAT WRONG GEOMETRY — which is far more expensive to disbelieve + // than an error would have been. A point is its position, for the same reason. + auto centre_of = [&](const char* what) { + if (j.contains("center")) return p("center", 0, 0); + throw std::runtime_error(std::string(what) + " needs a 'center'"); + }; + if (t == "line") { + // Its two ends are the line, so one left out is a mistake (often the key spelled another + // way, start/end), not the origin: a line ending there closes no loop the caller drew. + if (!j.contains("p0") || !j.contains("p1")) + throw std::runtime_error("line needs 'p0' and 'p1' as [x, y]"); + e.type = SketchEntity::Type::Line; + e.p0 = p("p0", 0, 0); e.p1 = p("p1", 0, 0); + } else if (t == "circle_center") { + e.type = SketchEntity::Type::Circle; + e.center = centre_of("circle_center"); + e.radius = j.value("radius", 0.0); + e.p0 = e.center; + if (e.radius <= 0.0) throw std::runtime_error("circle_center needs a positive 'radius'"); + } else if (t == "arc_center") { + e.type = SketchEntity::Type::Arc; + e.center = centre_of("arc_center"); + e.radius = j.value("radius", 0.0); + e.start_angle = angle_arg(j, "start_angle", 0.0); + e.end_angle = angle_arg(j, "end_angle", 0.0); + if (e.radius <= 0.0) throw std::runtime_error("arc_center needs a positive 'radius'"); + e.p0 = e.center + e.radius * Vec2d(std::cos(e.start_angle), std::sin(e.start_angle)); + e.p1 = e.center + e.radius * Vec2d(std::cos(e.end_angle), std::sin(e.end_angle)); + } else if (t == "point") { + e.type = SketchEntity::Type::Point; + e.p0 = point_arg(j, "p"); + } else { + throw std::logic_error("sketch_entity_from takes a line, circle_center, arc_center or point, not " + t); + } + return e; +} + +const char* const kPointRoles[] = {"p0", "p1", "center"}; // SketchPointRole + +json constraint_ref(int entity, SketchPointRole role, bool point) +{ + if (entity == kSketchRefOrigin) return json{{"entity", "origin"}}; + if (entity == kSketchRefAxisX) return json{{"entity", "x_axis"}}; + if (entity == kSketchRefAxisY) return json{{"entity", "y_axis"}}; + json r{{"entity", entity}}; + if (point) r["role"] = enum_name(kPointRoles, int(role)); + return r; +} + +} // namespace + +// ---- Shared with the other Design files (DesignCommon.hpp) -------------------------------------- + +json sketch_entity_to(const SketchEntity& e, int index) +{ + json j{{"index", index}, {"construction", e.construction}}; + switch (e.type) { + case SketchEntity::Type::Line: + j["type"] = "line"; + j["p0"] = json::array({e.p0.x(), e.p0.y()}); + j["p1"] = json::array({e.p1.x(), e.p1.y()}); + j["length"] = (e.p1 - e.p0).norm(); + break; + case SketchEntity::Type::Circle: + j["type"] = "circle"; + j["center"] = json::array({e.center.x(), e.center.y()}); + j["radius"] = e.radius; + break; + case SketchEntity::Type::Arc: + j["type"] = "arc"; + j["center"] = json::array({e.center.x(), e.center.y()}); + j["radius"] = e.radius; + j["start_angle"] = e.start_angle; + j["end_angle"] = e.end_angle; + j["p0"] = json::array({e.p0.x(), e.p0.y()}); + j["p1"] = json::array({e.p1.x(), e.p1.y()}); + break; + case SketchEntity::Type::Point: + j["type"] = "point"; + j["p"] = json::array({e.p0.x(), e.p0.y()}); + break; + // Ellipses and splines serialise every parameter they have, not just a type name: this is + // the only read-back the project has, and from a bare type name a caller could only count + // them and grade the faceted area of the loop they close (2e-2, the faceting error), never + // check a single axis, angle or pole. A precise definition of every aspect cannot be + // asserted about an entity whose aspects the read-back does not show. + case SketchEntity::Type::Ellipse: + j["type"] = "ellipse"; + j["center"] = json::array({e.center.x(), e.center.y()}); + j["radius"] = e.radius; // semi-major (a) + j["rminor"] = e.rminor; // semi-minor (b) + j["rotation"] = e.rotation; // major-axis angle, radians + break; + case SketchEntity::Type::EllipseArc: + j["type"] = "ellipse_arc"; + j["center"] = json::array({e.center.x(), e.center.y()}); + j["radius"] = e.radius; + j["rminor"] = e.rminor; + j["rotation"] = e.rotation; + j["start_angle"] = e.start_angle; + j["end_angle"] = e.end_angle; + j["p0"] = json::array({e.p0.x(), e.p0.y()}); + j["p1"] = json::array({e.p1.x(), e.p1.y()}); + break; + case SketchEntity::Type::BSpline: { + j["type"] = "spline"; + json poles = json::array(); + for (const Vec2d& c : e.ctrl) poles.push_back(json::array({c.x(), c.y()})); + j["ctrl"] = poles; + j["p0"] = json::array({e.p0.x(), e.p0.y()}); + j["p1"] = json::array({e.p1.x(), e.p1.y()}); + break; + } + } + return j; +} + +json constraint_value(SketchConstraintType t, double v) +{ + using T = SketchConstraintType; + switch (t) { + case T::Angle: return v * 180.0 / M_PI; + case T::Distance: case T::DistanceX: case T::DistanceY: case T::LockX: case T::LockY: + case T::Radius: case T::Diameter: case T::PointOnLine: return v; + default: return json(); + } +} + +json entity_constraint_json(const SketchEntityConstraintDef& c, int index) +{ + using T = SketchConstraintType; + json refs = json::array(); + auto pt = [&](int e, SketchPointRole r) { refs.push_back(constraint_ref(e, r, true)); }; + auto ent = [&](int e) { refs.push_back(constraint_ref(e, SketchPointRole::P0, false)); }; + switch (c.type) { + case T::Fix: case T::LockX: case T::LockY: + pt(c.ea, c.ra); break; + case T::Coincident: case T::Horizontal: case T::Vertical: case T::Distance: case T::DistanceX: + case T::DistanceY: case T::SymmetricAboutY: case T::SymmetricAboutX: + pt(c.ea, c.ra); pt(c.eb, c.rb); break; + case T::Radius: case T::Diameter: + ent(c.ea); break; + case T::Concentric: case T::EqualLength: case T::Parallel: case T::Perpendicular: case T::Angle: + case T::Tangent: case T::EqualRadius: case T::Collinear: + ent(c.ea); ent(c.eb); break; + case T::Midpoint: case T::PointOnLine: case T::PointOnObject: + pt(c.ea, c.ra); ent(c.eb); break; + case T::Symmetric: + pt(c.ea, c.ra); pt(c.eb, c.rb); ent(c.ec); break; + } + json j{{"index", index}, {"type", enum_name(kConstraintTypes, int(c.type))}, {"refs", std::move(refs)}}; + if (json v = constraint_value(c.type, c.value); !v.is_null()) j["value"] = std::move(v); + return j; +} + +int sketch_arg(const json& v, const CadDocument& doc) +{ + if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_design's features[].index)"); + const int si = v.get(); + check_feature_index(si, doc); + const CadFeature& f = doc.features[si]; + if (f.type != CadFeatureType::Sketch && f.type != CadFeatureType::Project) + throw std::runtime_error("feature " + std::to_string(si) + " (" + feature_type_name(f.type) + ") is not a sketch"); + return si; +} + +namespace { + +// Which entities a verb acts on in the open sketch (sketch_target_indices()). +std::vector sketch_targets(const json& params, DesignSketchTool& t, bool all_if_empty) +{ + return sketch_target_indices(params, t.selection(), int(t.entities().size()), all_if_empty); +} + +// The open sketch's degrees of freedom, as a reply's dof. The sketch tool keeps -1 while it has no +// constraints, since it runs no solve then and its own readout stays hidden; the count is still +// known, and it is the one a solve would give once a constraint arrives. +int sketch_dof(const DesignSketchTool& t) +{ + return t.constraints().empty() ? sketch_unconstrained_dof(t.entities()) : t.dof(); +} + +// A sketch's loops. Their indices are the ones extrude's `loop` takes: a region lists the loops +// inside it under `holes`, and each of those is a loop of its own. +json sketch_report(const DesignSketchTool::LoopReport& rep) +{ + json loops = json::array(); + for (size_t i = 0; i < rep.loops.size(); ++i) { + const auto& l = rep.loops[i]; + json holes = json::array(); + for (int h : l.holes) holes.push_back(h); + loops.push_back(json{{"index", int(i)}, {"entities", l.ents}, {"holes", holes}, + {"closed", l.closed}, {"area", l.area}}); + } + json open_ends = json::array(); + for (const Vec2d& p : rep.open_ends) open_ends.push_back(json::array({p.x(), p.y()})); + // A profile is buildable when at least one loop closed, nothing is left dangling and no loop + // crosses or folds back on itself. + json defects = json::array(); + for (const auto& l : rep.loops) + if (l.defect) defects.push_back(json::array({l.defect_at.x(), l.defect_at.y()})); + const bool buildable = !rep.loops.empty() && rep.open_ends.empty() && defects.empty(); + return json{{"closed_loops", loops}, {"open_ends", open_ends}, {"defects", defects}, {"buildable", buildable}}; +} + +// The session starts as a plane or face pick starts it, so the panel enters Sketch mode with the +// tool: key dispatch reads the panel's mode while the menu reads the viewport's, and a session the +// panel did not know of would leave every sketch key dead. +json action_sketch_create(DesignPanel* panel, const json& params) +{ + DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + if (vp->is_sketching()) throw CadPrecondition("a sketch is already open"); + const CadDocument& doc = panel->mcp_doc(); + const json pl = params.value("plane", json("XY")); + const SketchPlane plane = cad_resolve_plane(pl, doc, false); + // Named for the status line as the GUI names the plane: XY, a datum's name, or the face. + wxString on; + if (pl.is_string()) on = wxString::FromUTF8(pl.get()); + else if (pl.contains("datum")) on = wxString::FromUTF8(doc.features[pl["datum"].get()].name); + else on = wxString::Format(_L("Face %d"), pl["face"].get()); + panel->mcp_begin_sketch(plane, on); + return json{{"ok", true}, {"plane", pl}, {"frame", frame_json(plane)}}; +} + +// The sketch's Confirm. A failed call is left out of an exported replay, so a call that fails must +// leave the session as it was: a new empty sketch is refused before anything changes (where the +// GUI's commit drops it with a status line), and the session stays open for the replay's next +// sketch call. A re-opened sketch is committed as its Confirm commits it, which replaces it in +// place; a replace the rebuild refuses, or a re-opened sketch left empty, ends the edit with the +// design as it was. That changes the session, so it is a reply, ok false with the reason, which +// the replay keeps and runs to end the edit where the live run ended it. +json action_sketch_finish(DesignPanel* panel, const json& params) +{ + (void)params; + DesignSketchTool& t = mcp_sketch(panel); + const int edited = panel->mcp_edited_sketch(); + if (edited < 0 && t.entities().empty()) throw CadPrecondition("the sketch is empty; add entities or call sketch_cancel"); + const DesignPanel::SketchFinish done = panel->mcp_finish_sketch(); + if (!done.committed && edited >= 0) + return json{{"ok", false}, {"replaced", false}, {"sketch_index", edited}, + {"error", "the sketch was not replaced: " + done.error}}; + if (!done.committed) throw CadPrecondition("the sketch was not committed"); + panel->mcp_after_change(); + // Read back from the committed feature: solving its dimensions can move geometry, and extrude + // takes `loop` against these entities. + const CadDocument& doc = panel->mcp_doc(); + const CadFeature& f = doc.features[done.index]; + json out{{"ok", true}, {"sketch_index", done.index}, {"name", f.name}, {"features", int(doc.features.size())}}; + if (done.replaced) out["replaced"] = true; + out.update(sketch_report(t.loop_report(f.entities))); + return out; +} + +json action_sketch_cancel(DesignPanel* panel, const json& params) +{ + (void)params; + DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + if (!vp->is_sketching()) throw CadPrecondition("no sketch is open"); + panel->mcp_cancel_sketch(); + return json{{"ok", true}}; +} + +// Edit on a committed sketch's Feature tree row, for a sketch drawn from entities: the sketch +// commands then act on it, and sketch_finish puts it back in its place. +json action_sketch_edit(DesignPanel* panel, const json& params) +{ + const json v = params.is_object() ? params.value("sketch", json()) : json(); + if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_design's features[].index)"); + const int si = v.get(); + // The panel's own refusals of the view and an open sketch are the session's state; the others are the feature's. + const DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + if (vp->is_sketching()) throw CadPrecondition("a sketch is already open; finish or cancel it first"); + std::string why; + if (!panel->mcp_edit_sketch(si, why)) throw std::runtime_error(why); + const DesignSketchTool& t = mcp_sketch(panel); + const CadDocument& doc = panel->mcp_doc(); + return json{{"ok", true}, + {"sketch", si}, + {"entities", int(t.entities().size())}, + {"constraints", int(t.constraints().size())}, + {"plane", plane_json(doc.features[si].plane, doc.modeling_origin)}}; +} + +json action_sketch_select(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + std::vector idx; + if (params.contains("entities")) + for (const auto& v : params.at("entities")) idx.push_back(v.get()); + const bool any = t.select_indices(idx); + panel->mcp_viewport()->request_repaint(); + return json{{"ok", true}, {"selected", int(t.selection().size())}, {"any", any}}; +} + +json action_sketch_delete(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + const std::vector tgt = sketch_targets(params, t, false); + if (tgt.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); + const int before = int(t.entities().size()); + t.select_indices(tgt); + t.delete_selected(); + panel->mcp_viewport()->request_repaint(); + return json{{"ok", true}, {"removed", before - int(t.entities().size())}, + {"entities", int(t.entities().size())}}; +} + +json action_sketch_toggle_construction(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + const std::vector tgt = sketch_targets(params, t, false); + if (tgt.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); + t.select_indices(tgt); + const int n = t.toggle_selection_construction(); + panel->mcp_viewport()->request_repaint(); + return json{{"ok", n > 0}, {"changed", n}}; +} + +json action_sketch_describe(DesignPanel* panel, const json& params) +{ + // A committed sketch is read from the document, so no session is needed, nor disturbed. + const json sketch = params.is_object() ? params.value("sketch", json()) : json(); + if (!sketch.is_null()) { + const DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + const CadDocument& doc = panel->mcp_doc(); + return cad_sketch_describe(doc, vp->mcp_sketch_tool(), sketch_arg(sketch, doc)); + } + DesignSketchTool& t = mcp_sketch(panel); + json ents = json::array(); + for (int i = 0; i < int(t.entities().size()); ++i) + ents.push_back(sketch_entity_to(t.entities()[i], i)); + // The armed TOOL and its pending anchors. Without these the only way to tell which tool a + // menu item actually armed is to draw with it and infer from what came out — which is how a + // menu walk that lands one item off gets diagnosed as "the tool is broken". + static const char* const kModeNames[] = { + "select", "dimension", "polyline", "line", "rect_corner", "rect_center", "rect_oblique", + "rect_rounded", "circle_center", "circle_2pt", "point", + "circle_3pt", "arc_3pt", "arc_tangent", "arc_center", "slot", "slot_arc", "polygon", + "ellipse", "ellipse_arc", "spline", + "fillet", "chamfer", "offset", "mirror", + "trim", "extend", + "move", "rotate", "scale", "array", "array_polar", + "transform_art", + "constrain" }; + const int mi = int(t.mode()); + json out{{"ok", true}, + {"entities", ents}, + {"constraints", int(t.constraints().size())}, + {"dof", sketch_dof(t)}, + {"solve_ok", t.solve_ok()}, + {"tool", (mi >= 0 && mi < int(sizeof(kModeNames) / sizeof(kModeNames[0]))) + ? kModeNames[mi] : "unknown"}, + {"pending", t.pending_points()}, + {"editing", t.value_field_open()}, + {"selection", t.selection()}, + {"selected_constraint", t.selected_constraint() >= 0 ? json(t.selected_constraint()) : json(nullptr)}}; + out.update(sketch_report(t.loop_report())); + return out; +} + +json action_sketch_validate(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + const double tol = params.value("tolerance", 1e-3); + json out{{"ok", true}, {"tolerance", tol}, {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; + out.update(sketch_report(t.loop_report())); + return out; +} + +json action_sketch_repair(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + const double tol = params.value("tolerance", 1e-3); + const bool ic = params.value("ignore_construction", true); + const int welded = t.heal_coincidences(tol, ic); + panel->mcp_viewport()->request_repaint(); + json out{{"ok", true}, {"welded", welded}, {"tolerance", tol}, + {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; + out.update(sketch_report(t.loop_report())); + return out; +} + +// sketch_set_value commits a typed dimension by calling apply_dimension, the function the in-canvas +// value field calls, so what a typed value does to the geometry, constrained geometry included, can +// be asserted without a window manager giving that field keyboard focus. apply_dimension clears the +// selection. +json action_sketch_set_value(DesignPanel* panel, const json& params) +{ + DesignSketchTool& t = mcp_sketch(panel); + if (!params.contains("value")) throw std::runtime_error("sketch_set_value needs 'value'"); + const double value = params["value"].get(); + const DesignSketchTool::DimType kind = t.dimension_kind(); + if (kind == DesignSketchTool::DimType::None) + throw CadPrecondition("the selection has no value to set — pick a line, an arc, a circle, or two entities"); + + const char* kind_name = "none"; + switch (kind) { + case DesignSketchTool::DimType::Length: kind_name = "length"; break; + case DesignSketchTool::DimType::Radius: kind_name = "radius"; break; + case DesignSketchTool::DimType::Diameter: kind_name = "diameter"; break; + case DesignSketchTool::DimType::Angle: kind_name = "angle"; break; + case DesignSketchTool::DimType::Distance: kind_name = "distance"; break; + case DesignSketchTool::DimType::DistanceToLine: kind_name = "distance_to_line"; break; + default: break; + } + + // Validate BEFORE apply_dimension. The sketch tool refuses a value outside its thresholds + // itself, but only on its status line and without telling its caller, so this call would + // report the value as set. Fail loudly instead, with the reason. + if (!std::isfinite(value)) + throw std::runtime_error("dimension must be finite — NaN or infinity is not a dimension"); + switch (kind) { + case DesignSketchTool::DimType::Length: + case DesignSketchTool::DimType::Radius: + case DesignSketchTool::DimType::Diameter: + if (value <= 0.0) + throw std::runtime_error(std::string(kind_name) + " must be positive (got " + std::to_string(value) + ")"); + break; + case DesignSketchTool::DimType::Distance: + case DesignSketchTool::DimType::DistanceToLine: + if (value < 0.0) + throw std::runtime_error(std::string(kind_name) + " must be >= 0 (zero means coincident / on the line)"); + break; + case DesignSketchTool::DimType::Angle: + default: + break; // any finite angle is valid + } + + const double before = t.dimension_current(); + t.apply_dimension(value); + panel->mcp_viewport()->request_repaint(); + + json out{{"ok", true}, {"kind", kind_name}, {"before", before}, {"value", value}, + {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; + out.update(sketch_report(t.loop_report())); + return out; +} + +// With a sketch open, new or re-opened, the edges go into it (cad_sketch_project()). Otherwise the Project card's +// Confirm: a new sketch on `plane`, XY when it is left out or null, whose entities follow the body. +json action_sketch_project(DesignPanel* panel, const json& params) +{ + if (DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr && vp->is_sketching()) { + json r = cad_sketch_project(panel->mcp_doc(), vp->mcp_sketch_tool(), params); + vp->request_repaint(); + return r; + } + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); + int source_body = params.value("source_body", -1); + int face = params.value("face", -1); + std::vector edges; + if (params.contains("edges") && params["edges"].is_array()) + for (const auto& v : params["edges"]) edges.push_back(v.get()); + const json plane = params.value("plane", json()); + const SketchPlane pl = cad_resolve_plane(plane.is_null() ? json("XY") : plane, doc, false); + doc.checkpoint(); + int idx = doc.add_project_edges(source_body, edges, face, pl, panel->mcp_feature_name(_L_CONTEXT("Project", "Design"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"scope", "feature"}, {"project_index", idx}, {"bodies", int(doc.bodies.size())}, + {"error", doc.error}, {"frame", frame_json(pl)}}; +} + +json action_sketch_blend_curve(DesignPanel* panel, const json& params) +{ + if (!params.contains("sketch")) throw std::runtime_error("sketch_blend_curve needs 'sketch' (feature index)"); + if (!params.contains("ent_a")) throw std::runtime_error("sketch_blend_curve needs 'ent_a' (entity index)"); + if (!params.contains("ent_b")) throw std::runtime_error("sketch_blend_curve needs 'ent_b' (entity index)"); + int sketch = params["sketch"].get(); + int ent_a = params["ent_a"].get(); + int ent_b = params["ent_b"].get(); + int end_a = params.value("end_a", 1); + int end_b = params.value("end_b", 0); + CadDocument& doc = panel->mcp_doc(); + doc.checkpoint(); + int ei = doc.add_bridge(sketch, ent_a, end_a, ent_b, end_b, "Bridge"); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"sketch_index", sketch}, {"entity_index", ei}, + {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// ---- The open sketch: shapes, edit ops and constraints (cad_sketch_call) ------------------------ +// +// Each runs the sketch tool's own step for its button or gesture (DesignSketchTool's *_scripted +// entry points), checks every argument first and throws, leaving the sketch as it was. sketch_draw, +// whose tools can still refuse an item while drawing it, puts the sketch back as it was before the call when one does. + +// SketchEntity::Type's names, as sketch_describe writes them. +const char* const kEntityTypes[] = {"line", "arc", "circle", "point", "ellipse", "ellipse_arc", "spline"}; +static_assert(std::size(kEntityTypes) == size_t(SketchEntity::Type::BSpline) + 1, "every entity type needs a name"); + +std::string entity_label(const std::vector& ents, int i) +{ + if (i == kSketchRefOrigin) return "origin"; + if (i == kSketchRefAxisX) return "x_axis"; + if (i == kSketchRefAxisY) return "y_axis"; + return std::string(kEntityTypes[int(ents[i].type)]) + " " + std::to_string(i); +} + +// `v`, a list of entity indices of the open sketch. +std::vector entity_indices(const json& v, const std::vector& ents) +{ + if (!v.is_array()) throw std::runtime_error("entities must be a list of entity indices"); + std::vector out; + for (const json& i : v) { + if (!i.is_number_integer()) throw std::runtime_error("entities must be a list of entity indices"); + const int e = i.get(); + if (e < 0 || e >= int(ents.size())) + throw std::runtime_error("entity " + std::to_string(e) + " does not exist; the sketch has " + + std::to_string(ents.size()) + " entities"); + out.push_back(e); + } + return out; +} + +// `entities`, else the selection: what a tool's picks would be. +std::vector entity_picks(const json& params, const DesignSketchTool& t) +{ + const json v = param(params, "entities"); + return v.is_null() || (v.is_array() && v.empty()) ? t.selection() : entity_indices(v, t.entities()); +} + +// The tools' own apply steps take over a gesture in progress or an open value field, as a click +// would; the person finishes or drops those first. +void check_sketch_idle(const DesignSketchTool& t) +{ + if (t.value_field_open()) throw CadPrecondition("a value field is open in the sketch; commit or cancel it (Enter or Esc) first"); + if (t.gesture_pending()) throw CadPrecondition("the armed sketch tool has a gesture in progress; finish it or press Esc first"); +} + +// How many of `cons` reference entity `e`. +int constraints_on(const std::vector& cons, int e) +{ + return int(std::count_if(cons.begin(), cons.end(), [e](const SketchEntityConstraintDef& c) { + return c.ea == e || c.eb == e || c.ec == e; + })); +} + +json solve_state(const DesignSketchTool& t) +{ + return json{{"entities", int(t.entities().size())}, {"constraints", int(t.constraints().size())}, + {"dof", sketch_dof(t)}, {"solve_ok", t.solve_ok()}}; +} + +// One item of sketch_draw: entities added as given (`tool` Select), or a shape a drawing tool builds +// from its clicks. +struct SketchDrawItem +{ + std::vector ents; + DesignSketchTool::Mode tool{DesignSketchTool::Mode::Select}; + std::vector clicks; // the tool's; a tangent arc's end only, its start being the end of what it leaves + int sides{0}; + bool circumscribed{false}; + bool construction{false}; + int from{-1}; // the entity a tangent arc leaves; -1 the one added last +}; + +// sketch_draw's types, in the order its schema lists them, each with the fields it takes beside `type` and +// `construction`. +struct ShapeType +{ + const char* name; + std::vector fields; +}; +const ShapeType kShapeTypes[] = { + {"line", {"p0", "p1"}}, + {"polyline", {"points"}}, + {"rectangle_2_point", {"p0", "p1"}}, + {"rectangle_center", {"center", "corner"}}, + {"rectangle_3_point", {"p0", "p1", "width"}}, + {"rectangle_rounded", {"p0", "p1", "radius"}}, + {"circle_center", {"center", "radius"}}, + {"circle_2_point", {"p0", "p1"}}, + {"circle_3_point", {"p0", "p1", "p2"}}, + {"arc_3_point", {"p0", "p1", "on_arc"}}, + {"arc_center", {"center", "radius", "start_angle", "start_angle_deg", "end_angle", "end_angle_deg"}}, + {"arc_tangent", {"end", "entity"}}, + {"slot", {"c0", "c1", "width"}}, + {"slot_arc", {"center", "start", "end", "width"}}, + {"ellipse", {"center", "radius", "rminor", "rotation", "rotation_deg"}}, + {"ellipse_arc", + {"center", "radius", "rminor", "rotation", "rotation_deg", "start_angle", "start_angle_deg", "end_angle", "end_angle_deg"}}, + {"spline", {"ctrl"}}, + {"polygon", {"center", "sides", "radius", "across_flats", "angle", "angle_deg"}}, + {"point", {"p"}}, +}; + +// Whether a, b and c lie on one line, so that no circle runs through them. +bool on_one_line(const Vec2d& a, const Vec2d& b, const Vec2d& c) +{ + const Vec2d u = b - a, v = c - a; + return std::abs(u.x() * v.y() - u.y() * v.x()) < 1e-9; +} + +// A sketch_draw item: a shape's fields turned into the clicks its tool takes, or plain entities. A field given as +// null is left out, as the schema's null defaults say, and a field its type does not take is refused. Every check +// is made here, or for a tangent arc's entity in sketch_draw() before anything is drawn. Whether an arc fits a +// tangent arc is known once the items before it are drawn, since its start is the end of what it leaves; when none +// does, sketch_draw() puts the sketch back as it was before the call. +SketchDrawItem sketch_draw_item(const json& given) +{ + using Mode = DesignSketchTool::Mode; + using ET = SketchEntity::Type; + if (!given.is_object()) throw std::runtime_error("each shape is an object with a type and its fields"); + json j = json::object(); + for (const auto& [key, value] : given.items()) + if (!value.is_null()) j[key] = value; + SketchDrawItem it; + const std::string t = j.value("type", std::string()); + const auto type = std::find_if(std::begin(kShapeTypes), std::end(kShapeTypes), [&t](const ShapeType& s) { return t == s.name; }); + if (type == std::end(kShapeTypes)) { + std::string types; + for (const ShapeType& s : kShapeTypes) types += (types.empty() ? "" : ", ") + std::string(s.name); + throw std::runtime_error("unknown type '" + t + "': sketch_draw draws " + types); + } + for (const auto& [key, value] : j.items()) + if (key != "type" && key != "construction" && std::find(type->fields.begin(), type->fields.end(), key) == type->fields.end()) + throw std::runtime_error(t + " takes no " + key); + it.construction = j.value("construction", false); + // Smaller than the weld tolerance is no shape: its points would merge. + auto size_arg = [&](const char* key) { + const double v = number_arg(j, key); + if (!(v >= kSketchJoinTol)) throw std::runtime_error(t + " " + key + " must be at least 0.001 mm"); + return v; + }; + // Two corners of a box, which must differ in x and in y. + auto box_corners = [&](const char* a_key, const char* b_key) { + const Vec2d a = point_arg(j, a_key), b = point_arg(j, b_key); + if (std::abs(b.x() - a.x()) < kSketchJoinTol || std::abs(b.y() - a.y()) < kSketchJoinTol) + throw std::runtime_error(t + " " + a_key + " and " + b_key + " must differ in x and in y"); + return std::make_pair(a, b); + }; + if (t == "polyline") { + const json points = j.value("points", json()); + if (!points.is_array() || points.size() < 2) throw std::runtime_error("polyline needs points, 2 or more [[x, y], ...]"); + for (size_t i = 0; i < points.size(); ++i) { + const Vec2d p = point_of(points[i], "points[" + std::to_string(i) + "]"); + if (i > 0 && (p - it.clicks.back()).norm() < kSketchJoinTol) + throw std::runtime_error("polyline points " + std::to_string(i - 1) + " and " + std::to_string(i) + " coincide"); + it.clicks.push_back(p); + } + // The last point on the first closes the loop, as a click on the chain's start does. + if (it.clicks.size() >= 3 && (it.clicks.back() - it.clicks.front()).norm() < kSketchJoinTol) { + if (it.clicks.size() < 4) throw std::runtime_error("a closed polyline needs three points before the one that closes it"); + it.clicks.back() = it.clicks.front(); + } + it.tool = Mode::Polyline; + } else if (t == "rectangle_2_point") { + // The Corner rectangle tool's two clicks, on opposite corners. + const auto [a, b] = box_corners("p0", "p1"); + it.tool = Mode::CornerRect; + it.clicks = {a, b}; + } else if (t == "rectangle_center") { + const auto [c, corner] = box_corners("center", "corner"); + it.tool = Mode::CenterRect; + it.clicks = {c, corner}; + } else if (t == "rectangle_3_point") { + // One side, then the Oblique rectangle tool's third click, the width off it to the left of p0 to p1. + const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"); + const double w = number_arg(j, "width"); + if ((b - a).norm() < kSketchJoinTol) throw std::runtime_error("rectangle_3_point p0 and p1 must be apart"); + if (std::abs(w) < kSketchJoinTol) throw std::runtime_error("rectangle_3_point width must be at least 0.001 mm either way"); + const Vec2d u = (b - a).normalized(); + it.tool = Mode::ObliqueRect; + it.clicks = {a, b, a + w * Vec2d(-u.y(), u.x())}; + } else if (t == "rectangle_rounded") { + const auto [a, b] = box_corners("p0", "p1"); + const double r = size_arg("radius"); + const double half = 0.5 * std::min(std::abs(b.x() - a.x()), std::abs(b.y() - a.y())); + if (!(r < half)) + throw std::runtime_error("rectangle_rounded radius must be less than half its shorter side, " + json(half).dump() + " mm"); + // The Rounded rectangle tool's third click sets the corner radius by its distance to the nearest corner. + it.tool = Mode::RoundedRect; + it.clicks = {a, b, Vec2d(std::min(a.x(), b.x()) + r, std::min(a.y(), b.y()))}; + } else if (t == "circle_2_point") { + const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"); + if ((b - a).norm() < 2.0 * kSketchJoinTol) + throw std::runtime_error("circle_2_point p0 and p1, the ends of a diameter, must be at least 0.002 mm apart"); + it.tool = Mode::TwoPointCircle; + it.clicks = {a, b}; + } else if (t == "circle_3_point") { + const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"), c = point_arg(j, "p2"); + if (on_one_line(a, b, c)) throw std::runtime_error("circle_3_point p0, p1 and p2 must not lie on one line"); + it.tool = Mode::ThreePointCircle; + it.clicks = {a, b, c}; + } else if (t == "arc_3_point") { + const Vec2d a = point_arg(j, "p0"), b = point_arg(j, "p1"), m = point_arg(j, "on_arc"); + if (on_one_line(a, b, m)) throw std::runtime_error("arc_3_point p0, p1 and on_arc must not lie on one line"); + it.tool = Mode::ThreePointArc; + it.clicks = {a, b, m}; + } else if (t == "arc_tangent") { + if (j.contains("entity")) { + const json e = j.at("entity"); + if (!e.is_number_integer() || e.get() < 0) + throw std::runtime_error("arc_tangent entity must be the index of the line or arc it leaves"); + it.from = e.get(); + } + it.tool = Mode::TangentArc; + it.clicks = {point_arg(j, "end")}; + } else if (t == "slot_arc") { + const Vec2d c = point_arg(j, "center"), s = point_arg(j, "start"), e = point_arg(j, "end"); + const double w = size_arg("width"); + const double rc = (s - c).norm(); + if (rc < kSketchJoinTol) throw std::runtime_error("slot_arc start must be apart from center"); + if ((e - c).norm() < kSketchJoinTol) throw std::runtime_error("slot_arc end must be apart from center"); + const Vec2d ds = (s - c) / rc, de = (e - c).normalized(); + if (std::abs(ds.x() * de.y() - ds.y() * de.x()) < 1e-9 && ds.dot(de) > 0.0) + throw std::runtime_error("slot_arc end must lie in another direction from center than start"); + if (!(0.5 * w < rc)) throw std::runtime_error("slot_arc width must be less than twice the distance from center to start"); + // The Arc slot tool's clicks: the centre, the centreline's start, its end's direction, and the width's half off + // the centreline circle. + it.tool = Mode::ArcSlot; + it.clicks = {c, s, e, c + (rc + 0.5 * w) * ds}; + } else if (t == "polygon") { + const Vec2d c = point_arg(j, "center"); + const json sides = j.value("sides", json()); + if (!sides.is_number_integer() || sides.get() < 3 || sides.get() > 1000) + throw std::runtime_error("polygon needs sides, 3 to 1000"); + if (j.contains("across_flats") == j.contains("radius")) + throw std::runtime_error("polygon needs radius (centre to a vertex) or across_flats, one of them"); + // The tool's second click: on a vertex (inscribed), or on an edge's midpoint, half the + // across-flats size out (circumscribed). + it.circumscribed = j.contains("across_flats"); + const double d = it.circumscribed ? size_arg("across_flats") / 2.0 : size_arg("radius"); + const double a = angle_arg(j, "angle", 0.0); + it.tool = Mode::Polygon; + it.sides = sides.get(); + it.clicks = {c, c + d * Vec2d(std::cos(a), std::sin(a))}; + } else if (t == "slot") { + const Vec2d c0 = point_arg(j, "c0"), c1 = point_arg(j, "c1"); + const double w = size_arg("width"); + if ((c1 - c0).norm() < kSketchJoinTol) throw std::runtime_error("slot centres c0 and c1 must be apart"); + const Vec2d u = (c1 - c0).normalized(); + it.tool = Mode::Slot; + it.clicks = {c0, c1, c0 + 0.5 * w * Vec2d(-u.y(), u.x())}; + } else if (t == "ellipse" || t == "ellipse_arc") { + const Vec2d c = point_arg(j, "center"); + const double a = size_arg("radius"), b = size_arg("rminor"); + if (b > a) throw std::runtime_error(t + " rminor must not exceed radius, the semi-major axis"); + const double phi = angle_arg(j, "rotation", 0.0); + const Vec2d u(std::cos(phi), std::sin(phi)), v(-std::sin(phi), std::cos(phi)); + it.tool = Mode::Ellipse; + it.clicks = {c, c + a * u, c + b * v}; + if (t == "ellipse_arc") { + for (const char* k : {"start_angle", "end_angle"}) + if (!j.contains(k) && !j.contains(std::string(k) + "_deg")) + throw std::runtime_error(std::string("ellipse_arc needs ") + k + " (or " + k + "_deg)"); + const double t0 = angle_arg(j, "start_angle", 0.0), t1 = angle_arg(j, "end_angle", 0.0); + if (std::abs(std::remainder(t1 - t0, 2.0 * M_PI)) < 1e-9) + throw std::runtime_error("ellipse_arc end_angle must differ from start_angle; a whole turn is an ellipse"); + // Points on the ellipse at those parametric angles, which the tool reads back off them. + auto on = [&](double s) { return Vec2d(c + a * std::cos(s) * u + b * std::sin(s) * v); }; + it.tool = Mode::EllipseArc; + it.clicks.push_back(on(t0)); + it.clicks.push_back(on(t1)); + } + } else if (t == "spline") { + const json ctrl = j.value("ctrl", json()); + if (!ctrl.is_array() || ctrl.size() < 2) throw std::runtime_error("spline needs ctrl, 2 or more poles [[x, y], ...]"); + for (size_t i = 0; i < ctrl.size(); ++i) { + const Vec2d p = point_of(ctrl[i], "ctrl[" + std::to_string(i) + "]"); + if (i > 0 && (p - it.clicks.back()).norm() < kSketchJoinTol) + throw std::runtime_error("spline poles " + std::to_string(i - 1) + " and " + std::to_string(i) + " coincide"); + it.clicks.push_back(p); + } + it.tool = Mode::BSpline; + } else { + it.ents.push_back(sketch_entity_from(j)); // line, circle_center, arc_center, point + } + return it; +} + +json sketch_draw(DesignSketchTool& t, const json& params) +{ + using Mode = DesignSketchTool::Mode; + std::vector items; + const json list = param(params, "entities"), type = param(params, "type"); + if (!list.is_null()) { + // An entities given is the list form, an empty one included. Each item holds its shape's fields, so one beside + // the list would draw nothing, and is refused. construction is no shape's field: beside the list it is each + // item's that gives none of its own. + for (const auto& [key, value] : params.items()) + if (key != "entities" && key != "construction" && key != "generation" && !value.is_null()) + throw std::runtime_error(key + " belongs in an item of entities, not beside the list"); + if (!list.is_array()) throw std::runtime_error("entities must be a list of shapes, each an object with a type and its fields"); + if (list.empty()) throw std::runtime_error("entities is empty: give it the shapes to draw, or a single type and its fields"); + const json construction = param(params, "construction"); + for (json j : list) { + if (j.is_object() && !construction.is_null() && j.value("construction", json()).is_null()) j["construction"] = construction; + items.push_back(sketch_draw_item(j)); + } + } else if (type.is_string() && !type.get().empty()) { + // One item, its fields beside `type`. + json one = params; + one.erase("entities"); + one.erase("generation"); + items.push_back(sketch_draw_item(one)); + } else { + throw std::runtime_error("sketch_draw needs 'entities' or a single 'type'"); + } + if (std::any_of(items.begin(), items.end(), [](const SketchDrawItem& it) { return it.tool != Mode::Select; })) + check_sketch_idle(t); + + const int before = int(t.entities().size()); + json shapes = json::array(); + // An item refused while drawing puts the sketch back as it was before the call, the items before it taken off. + const DesignSketchTool::DrawnState kept = t.drawn_state(); + try { + for (size_t i = 0; i < items.size();) { + if (items[i].tool == DesignSketchTool::Mode::Select) { + // Entities next to each other are added in one batch, so their constraints are inferred + // together, as a list of entities always was. + std::vector run; + size_t end = i; + for (; end < items.size() && items[end].tool == DesignSketchTool::Mode::Select; ++end) + run.insert(run.end(), items[end].ents.begin(), items[end].ents.end()); + int at = t.add_entities_scripted(run); + for (; i < end; ++i) { + shapes.push_back(json{{"first", at}, {"count", int(items[i].ents.size())}}); + at += int(items[i].ents.size()); + } + } else { + const SketchDrawItem& it = items[i++]; + std::vector clicks = it.clicks; + if (it.tool == Mode::TangentArc) { + // It leaves a line or an arc: the entity it names, one the sketch has or one an item before it + // added, else the entity added last. Its start is that entity's end, as the tool's first click + // snaps onto it. + const auto& ents = t.entities(); + if (it.from >= int(ents.size())) + throw std::runtime_error("arc_tangent entity " + std::to_string(it.from) + " does not exist; the sketch has " + + std::to_string(ents.size()) + " entities with the items before it"); + if (ents.empty()) throw CadPrecondition("arc_tangent needs a line or an arc to leave, and the sketch has none"); + const int from = it.from >= 0 ? it.from : int(ents.size()) - 1; + if (ents[from].type != SketchEntity::Type::Line && ents[from].type != SketchEntity::Type::Arc) + throw std::runtime_error("arc_tangent leaves a line or an arc, and " + entity_label(ents, from) + " is neither"); + clicks.insert(clicks.begin(), ents[from].p1); + } + const int at = t.add_shape_scripted(it.tool, clicks, it.sides, it.circumscribed, it.construction, it.from); + if (at < 0 && it.tool == Mode::TangentArc) + throw std::runtime_error("arc_tangent from item " + std::to_string(i - 1) + + " makes no arc: its end must be apart from its start, " + + json::array({clicks[0].x(), clicks[0].y()}).dump() + ", and off the line it leaves along"); + if (at < 0) throw std::runtime_error("the sketch tool built nothing from item " + std::to_string(i - 1)); + shapes.push_back(json{{"first", at}, {"count", int(t.entities().size()) - at}}); + } + } + } catch (...) { + t.restore_drawn_state(kept); + throw; + } + return json{{"ok", true}, {"first_index", before}, {"added", int(t.entities().size()) - before}, + {"shapes", std::move(shapes)}, {"entities", int(t.entities().size())}, {"dof", sketch_dof(t)}}; +} + +// sketch_fillet and sketch_chamfer: the Fillet and Chamfer tools on two picked lines. +json sketch_corner(DesignSketchTool& t, const json& params, bool chamfer) +{ + const std::string what = chamfer ? "chamfer" : "fillet"; + const char* key = chamfer ? "distance" : "radius"; + const auto& ents = t.entities(); + const std::vector lines = entity_picks(params, t); + if (lines.size() != 2 || lines[0] == lines[1]) + throw std::runtime_error(what + " needs two lines, as entities or the selection"); + for (int i : lines) + if (ents[i].type != SketchEntity::Type::Line) + throw std::runtime_error(what + " needs two lines that meet at a corner; " + entity_label(ents, i) + " is not a line"); + const double value = number_arg(params, key); + if (!(value > 0.0)) throw std::runtime_error(std::string(key) + " must be > 0"); + const int a = lines[0], b = lines[1]; + const Vec2d da = ents[a].p1 - ents[a].p0, db = ents[b].p1 - ents[b].p0; + if (std::abs(da.x() * db.y() - da.y() * db.x()) < 1e-12) // the tool's own corner test (op_corner) + throw std::runtime_error(what + " needs two lines that meet at a corner; lines " + std::to_string(a) + " and " + + std::to_string(b) + " are parallel"); + check_sketch_idle(t); + const int cons_before = int(t.constraints().size()); + if (!t.fillet_scripted(a, b, value, chamfer)) + throw std::runtime_error("the " + std::string(key) + " " + json(value).dump() + " overruns a leg of line " + + std::to_string(a) + " or " + std::to_string(b)); + // The new arc or segment is last; every constraint the op added binds it, the rest it released. + const int added = int(ents.size()) - 1, bound = constraints_on(t.constraints(), added); + json r{{"ok", true}, {"entity", added}, {"lines", json::array({a, b})}, + {"released_constraints", cons_before + bound - int(t.constraints().size())}}; + r.update(solve_state(t)); + return r; +} + +// What sketch_offset and sketch_mirror copy: `entities`, else the selection, else every entity. A listed index the +// sketch does not have is refused, and so is one listed twice. +std::vector copy_sources(const json& params, const DesignSketchTool& t, bool& listed) +{ + const json given = param(params, "entities"); + listed = !given.is_null() && !(given.is_array() && given.empty()); + const std::vector out = listed ? entity_indices(given, t.entities()) + : sketch_target_indices(params, t.selection(), int(t.entities().size()), true); + for (size_t i = 0; i < out.size(); ++i) + if (std::find(out.begin(), out.begin() + i, out[i]) != out.begin() + i) + throw std::runtime_error("entity " + std::to_string(out[i]) + " is listed twice"); + return out; +} + +// The constraints `indices` of the open sketch, as sketch_list_constraints writes them. +json constraints_at(const DesignSketchTool& t, const std::vector& indices) +{ + json out = json::array(); + for (int c : indices) out.push_back(entity_constraint_json(t.constraints()[c], c)); + return out; +} + +// sketch_offset: offset copies. The copy of one entity alone is the Offset tool's Confirm, which adds it with no +// constraint inferred and binds it to its source, Parallel for a line and Concentric for an arc or a circle: inferred +// first, the copy of a horizontal or vertical line would be held so, and the solver refuses the redundant Parallel. +// Several entities' copies are added as drawn entities are, bound to nothing. +json sketch_offset(DesignSketchTool& t, const json& params) +{ + if (!params.contains("distance")) throw std::runtime_error("sketch_offset needs 'distance'"); + const double d = number_arg(params, "distance"); + bool listed = false; + const std::vector sources = copy_sources(params, t, listed); + std::vector src; + for (int i : sources) src.push_back(t.entities()[i]); + if (src.empty()) throw CadPrecondition("nothing to offset"); + const auto out = SketchEngine::offset_entities(src, d); + if (out.empty()) throw std::runtime_error("offset produced nothing (ellipses and splines are not offset)"); + const int base = int(t.entities().size()); + std::vector bound; + if (sources.size() == 1) { + check_sketch_idle(t); + if (!t.offset_scripted(sources.front(), d, bound)) throw std::runtime_error("the Offset tool refused the offset"); + } else { + t.add_entities_scripted(out); + } + return json{{"ok", true}, {"first_index", base}, {"added", int(t.entities().size()) - base}, + {"constraints_added", constraints_at(t, bound)}, {"dof", sketch_dof(t)}}; +} + +// sketch_mirror: about `axis`, a line of the sketch or one of its axes, the Mirror tool's Confirm, which binds each +// copy Symmetric to its source; or across the line through axis_a and axis_b, two free points, copies bound to nothing. +json sketch_mirror(DesignSketchTool& t, const json& params) +{ + const auto& ents = t.entities(); + const json axis_v = param(params, "axis"); + bool listed = false; + std::vector targets = copy_sources(params, t, listed); + if (axis_v.is_null()) { + const Vec2d a = params.contains("axis_a") ? point_arg(params, "axis_a") : Vec2d(0, 0); + const Vec2d b = params.contains("axis_b") ? point_arg(params, "axis_b") : Vec2d(0, 1); + if (targets.empty()) throw CadPrecondition("nothing to mirror"); + std::vector src; + for (int i : targets) src.push_back(ents[i]); + const auto out = SketchEngine::mirror_entities(src, a, b); + const int base = t.add_entities_scripted(out); + return json{{"ok", true}, {"first_index", base}, {"added", int(out.size())}, + {"constraints_added", json::array()}, {"dof", sketch_dof(t)}}; + } + if (params.contains("axis_a") || params.contains("axis_b")) + throw std::runtime_error("give axis, or axis_a and axis_b, not both"); + int axis = -1; + if (axis_v == "x_axis") + axis = kSketchRefAxisX; + else if (axis_v == "y_axis") + axis = kSketchRefAxisY; + else if (axis_v.is_number_integer()) + axis = entity_indices(json::array({axis_v}), ents).front(); + else + throw std::runtime_error("axis must be a line's entity index, \"x_axis\" or \"y_axis\""); + if (axis >= 0 && ents[axis].type != SketchEntity::Type::Line) + throw std::runtime_error("axis must be a line of the sketch, \"x_axis\" or \"y_axis\"; " + entity_label(ents, axis) + + " is not a line"); + // The tool takes no pick of its axis as something to mirror. + if (const auto it = std::find(targets.begin(), targets.end(), axis); it != targets.end()) { + if (listed) throw std::runtime_error("entity " + std::to_string(axis) + " is the axis; it is not mirrored about itself"); + targets.erase(it); + } + if (targets.empty()) throw CadPrecondition("nothing to mirror"); + check_sketch_idle(t); + const int base = int(ents.size()); + std::vector kept; + if (!t.mirror_scripted(targets, axis, kept)) throw std::runtime_error("the Mirror tool refused the mirror"); + return json{{"ok", true}, {"first_index", base}, {"added", int(ents.size()) - base}, + {"constraints_added", constraints_at(t, kept)}, {"dof", sketch_dof(t)}}; +} + +// sketch_trim: a Trim click at `at`; sketch_extend (extend): an Extend click there. +json sketch_trim_or_extend(DesignSketchTool& t, const json& params, bool extend) +{ + const Vec2d at = point_arg(params, "at"); + const double tol = params.contains("tolerance") ? number_arg(params, "tolerance") : 0.05; + if (!(tol > 0.0)) throw std::runtime_error("tolerance must be > 0"); + check_sketch_idle(t); + const int cons_before = int(t.constraints().size()); + const auto where = json::array({at.x(), at.y()}).dump(); + int picked = -1; + if (!t.trim_scripted(at, tol, extend, picked)) { + const auto& ents = t.entities(); + if (picked < 0) + throw std::runtime_error("no sketch entity within " + json(tol).dump() + " mm of " + where + "; tolerance widens the search"); + using ET = SketchEntity::Type; + const ET ty = ents[picked].type; + if (extend && ty != ET::Line && ty != ET::Arc) + throw std::runtime_error("extend works on lines and arcs; " + entity_label(ents, picked) + " is neither"); + if (!extend && ty != ET::Line && ty != ET::Arc && ty != ET::Circle) + throw std::runtime_error("trim works on lines, arcs and circles; " + entity_label(ents, picked) + " is none of them"); + throw std::runtime_error(extend ? "extend: " + entity_label(ents, picked) + " reaches no other entity from its end nearest " + where + : "trim: nothing to cut on " + entity_label(ents, picked) + " at " + where + + ": no other entity crosses it beyond that point (a circle needs two crossings)"); + } + json r{{"ok", true}, {"entity", picked}, {"geometry", sketch_entity_to(t.entities()[picked], picked)}, + {"released_constraints", cons_before - int(t.constraints().size())}}; + r.update(solve_state(t)); + return r; +} + +// sketch_transform: the Move, Rotate and Scale tools' Confirm, by params.type. sketch_pattern +// (pattern): the Linear and Polar array tools' Confirm, type linear or circular. +json sketch_transform(DesignSketchTool& t, const json& params, bool pattern) +{ + using Mode = DesignSketchTool::Mode; + using Types = std::vector>; + static const Types kTransforms = {{"move", Mode::Move}, {"rotate", Mode::Rotate}, {"scale", Mode::Scale}}; + static const Types kPatterns = {{"linear", Mode::Array}, {"circular", Mode::PolarArray}}; + const json typev = param(params, "type"); + const char* type = nullptr; + Mode mode = Mode::Move; + for (const auto& [name, m] : pattern ? kPatterns : kTransforms) + if (typev.is_string() && typev.get() == name) { type = name; mode = m; } + if (type == nullptr) throw std::runtime_error(pattern ? "type must be linear or circular" : "type must be move, rotate or scale"); + + // What each type reads; anything else would be ignored, so it is refused. + const bool shifts = mode == Mode::Move || mode == Mode::Array, turns = mode == Mode::Rotate || mode == Mode::PolarArray; + const bool counts = mode == Mode::Array || mode == Mode::PolarArray, pivots = mode != Mode::Move && mode != Mode::Array; + const std::pair takes[] = {{"dx", shifts}, {"dy", shifts}, {"angle", turns}, {"angle_deg", turns}, + {"scale", mode == Mode::Scale}, {"count", counts}, {"pivot", pivots}}; + for (const auto& [key, read] : takes) + if (!read && params.contains(key)) throw std::runtime_error(std::string(type) + " takes no " + key); + + const std::vector targets = entity_picks(params, t); + if (targets.empty()) throw std::runtime_error("nothing selected and no 'entities' given"); + for (size_t i = 0; i < targets.size(); ++i) + if (std::find(targets.begin(), targets.begin() + i, targets[i]) != targets.begin() + i) + throw std::runtime_error("entity " + std::to_string(targets[i]) + " is listed twice"); + const Vec2d delta(params.contains("dx") ? number_arg(params, "dx") : 0.0, params.contains("dy") ? number_arg(params, "dy") : 0.0); + const double angle = angle_arg(params, "angle", mode == Mode::PolarArray ? 2.0 * M_PI : 0.0); + const double scale = params.contains("scale") ? number_arg(params, "scale") : 1.0; + int count = 0; + if (counts) { + const json c = param(params, "count"); + if (!c.is_number_integer() || c.get() < 2 || c.get() > 1000) + throw std::runtime_error(std::string(type) + " needs count, 2 to 1000 instances counting the original"); + count = c.get(); + } + std::optional pivot; + if (params.contains("pivot")) pivot = point_arg(params, "pivot"); + // A transform that moves nothing would still drop the constraints it invalidates. + if (shifts && delta.norm() < 1e-9) throw std::runtime_error(std::string(type) + " needs a non-zero dx or dy"); + if (mode == Mode::Rotate && std::abs(angle) < 1e-12) throw std::runtime_error("rotate needs a non-zero angle (or angle_deg)"); + if (mode == Mode::Scale && (!(scale > 0.0) || std::abs(scale - 1.0) < 1e-12)) + throw std::runtime_error("scale needs a positive factor other than 1"); + if (mode == Mode::PolarArray && !pivot) throw std::runtime_error("circular needs pivot, the centre to array about"); + if (mode == Mode::PolarArray && std::abs(angle) < 1e-12) throw std::runtime_error("circular needs a non-zero angle"); + + check_sketch_idle(t); + const int ents_before = int(t.entities().size()), cons_before = int(t.constraints().size()); + const auto used = t.transform_scripted(mode, targets, delta, angle, scale, count, pivot); + if (!used) throw std::runtime_error("the sketch tool refused the transform"); + json r{{"ok", true}, {"type", type}}; + if (counts) { + r["first_index"] = ents_before; + r["added"] = int(t.entities().size()) - ents_before; + r["bound"] = int(t.constraints().size()) - cons_before; // each copy's ties to its source + } else { + r["moved"] = targets; + r["released_constraints"] = cons_before - int(t.constraints().size()); + } + if (pivots) r["pivot"] = json::array({used->x(), used->y()}); + r.update(solve_state(t)); + return r; +} + +// The constraint type `v` names: SketchConstraintType's name in snake_case, or "equal", the +// CONSTRAIN bar's Equal (equal length, or equal radius for two curves). +SketchConstraintType constraint_type_arg(const json& v) +{ + if (!v.is_string()) + throw std::runtime_error("type must be a constraint type, such as \"parallel\" (tool_describe {tool: \"sketch_constrain\"} lists " + "them, and {tool: \"sketch_dimension\"} the dimensions)"); + const std::string s = v.get(); + if (s == "equal") return SketchConstraintType::EqualLength; + for (size_t i = 0; i < std::size(kConstraintTypes); ++i) + if (s == kConstraintTypes[i]) return SketchConstraintType(i); + std::string close; + for (const char* n : kConstraintTypes) + if (edit_distance(boost::algorithm::to_lower_copy(s), n) <= 2 + s.size() / 4) + close += std::string(close.empty() ? "" : ", ") + "\"" + n + "\""; + throw std::runtime_error("unknown constraint type \"" + s + "\"" + (close.empty() ? "" : "; did you mean " + close) + + " (tool_describe {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)"); +} + +// Why the CONSTRAIN bar refuses a pick, in ConstraintReject order: a code an agent can test and the +// English of the status line's message (constraint_reject_text in DesignPanel.cpp). +const std::pair kConstraintRejects[] = { + {"none", ""}, + {"need_one_entity", "needs an entity: pass entities, or select one"}, + {"need_two_entities", "needs two entities: pass entities, or select them"}, + {"need_a_line", "applies to a line"}, + {"need_two_lines", "applies to two lines"}, + {"need_two_rounds", "needs two circles or arcs"}, + {"need_tangent_pair", "needs a line and a circle or arc, or two circles or arcs"}, + {"need_joinable_points", "needs two entities with a point to join"}, + {"need_measurable_points", "needs two entities with a point to measure between"}, + {"need_point_and_line", "needs a point and a line"}, + {"need_two_points_or_lines", "needs two points or two lines"}, + {"need_axis_line", "needs two entities, then an axis line"}, + {"need_round", "needs a circle or an arc"}, + {"unsupported", "has no CONSTRAIN bar button; name its points with refs instead"}, +}; +static_assert(std::size(kConstraintRejects) == size_t(ConstraintReject::Unsupported) + 1, "every refusal needs a text"); + +// A point reference {entity, role}: "origin", or a point of an entity. The role may be left out +// where the entity has only one point: a point's p0, a circle's or an ellipse's centre. +std::pair point_ref(const json& r, const std::vector& ents, const std::string& what) +{ + if (!r.is_object() || !r.contains("entity")) + throw std::runtime_error(what + " must be {\"entity\": i or \"origin\", \"role\": \"p0\", \"p1\" or \"center\"}"); + const json& e = r.at("entity"); + if (e == "origin") { + if (r.contains("role")) throw std::runtime_error(what + ": the origin is a point and takes no role"); + return {kSketchRefOrigin, SketchPointRole::P0}; + } + if (!e.is_number_integer()) + throw std::runtime_error(what + " names a point: an entity index or \"origin\""); + const int i = entity_indices(json::array({e}), ents).front(); + // The points the solver gives each type (SketchSolver's slots). + using ET = SketchEntity::Type; + using R = SketchPointRole; + std::vector roles; + switch (ents[i].type) { + case ET::Line: case ET::BSpline: roles = {R::P0, R::P1}; break; + case ET::Arc: case ET::EllipseArc: roles = {R::P0, R::P1, R::Center}; break; + case ET::Circle: case ET::Ellipse: roles = {R::Center}; break; + case ET::Point: roles = {R::P0}; break; + } + std::string names; + for (R x : roles) names += (names.empty() ? "" : ", ") + std::string(kPointRoles[int(x)]); + if (!r.contains("role")) { + if (roles.size() == 1) return {i, roles.front()}; + throw std::runtime_error(what + " needs a role: " + entity_label(ents, i) + " has " + names); + } + const R role = R(enum_index(what + " role", r.at("role"), kPointRoles)); + if (std::find(roles.begin(), roles.end(), role) == roles.end()) + throw std::runtime_error(what + ": role \"" + kPointRoles[int(role)] + "\" does not exist on " + entity_label(ents, i) + + " (it has " + names + ")"); + return {i, role}; +} + +// A whole-entity reference {entity}: an entity, or "x_axis" / "y_axis", the sketch's axes. +int entity_ref(const json& r, const std::vector& ents, const std::string& what) +{ + if (!r.is_object() || !r.contains("entity")) + throw std::runtime_error(what + " must be {\"entity\": i, \"x_axis\" or \"y_axis\"}"); + if (r.contains("role")) throw std::runtime_error(what + " is a whole entity and takes no role"); + const json& e = r.at("entity"); + if (e == "x_axis") return kSketchRefAxisX; + if (e == "y_axis") return kSketchRefAxisY; + if (!e.is_number_integer()) throw std::runtime_error(what + " names an entity: an index, \"x_axis\" or \"y_axis\""); + return entity_indices(json::array({e}), ents).front(); +} + +// A constraint from `refs`, as entity_constraint_json writes it: each type's references are points +// (P) or whole entities (E) in the order the solver reads them. +SketchEntityConstraintDef refs_constraint(SketchConstraintType type, const std::string& name, const json& refs, + const std::vector& ents) +{ + using T = SketchConstraintType; + using ET = SketchEntity::Type; + const char* shape = "PP"; + const char* says = "two points"; + switch (type) { + case T::Fix: case T::LockX: case T::LockY: + shape = "P"; says = "one point"; break; + case T::Radius: case T::Diameter: + shape = "E"; says = "one entity"; break; + case T::Concentric: case T::EqualLength: case T::Parallel: case T::Perpendicular: case T::Angle: + case T::Tangent: case T::EqualRadius: case T::Collinear: + shape = "EE"; says = "two entities"; break; + case T::Midpoint: case T::PointOnLine: case T::PointOnObject: + shape = "PE"; says = "a point, then an entity"; break; + case T::Symmetric: + shape = "PPE"; says = "two points, then the axis line"; break; + default: break; + } + if (!refs.is_array() || refs.size() != std::strlen(shape)) + throw std::runtime_error(name + " takes refs: " + says); + SketchEntityConstraintDef d; + d.type = type; + int* ent[3] = {&d.ea, &d.eb, &d.ec}; + SketchPointRole* role[3] = {&d.ra, &d.rb, &d.rc}; + for (size_t k = 0; k < refs.size(); ++k) { + const std::string what = name + " refs[" + std::to_string(k) + "]"; + if (shape[k] == 'P') std::tie(*ent[k], *role[k]) = point_ref(refs[k], ents, what); + else *ent[k] = entity_ref(refs[k], ents, what); + } + // The entity each type acts on, as the planner checks a pick (plan_entity_constraint); the + // solver would drop anything else without a word. The axes are lines, though no segment. + auto line = [&](int e) { return e == kSketchRefAxisX || e == kSketchRefAxisY || (e >= 0 && ents[e].type == ET::Line); }; + auto seg = [&](int e) { return e >= 0 && ents[e].type == ET::Line; }; + auto round = [&](int e) { return e >= 0 && (ents[e].type == ET::Circle || ents[e].type == ET::Arc); }; + auto need = [&](bool ok, int e, const char* kind) { + if (!ok) throw std::runtime_error(name + " needs " + kind + "; " + entity_label(ents, e) + " is not one"); + }; + switch (type) { + case T::Radius: case T::Diameter: + need(round(d.ea), d.ea, "a circle or an arc"); + d.ra = SketchPointRole::Center; + break; + case T::Concentric: case T::EqualRadius: + need(round(d.ea), d.ea, "two circles or arcs"); + need(round(d.eb), d.eb, "two circles or arcs"); + if (type == T::Concentric) d.ra = d.rb = SketchPointRole::Center; + break; + case T::EqualLength: + need(seg(d.ea), d.ea, "two lines"); + need(seg(d.eb), d.eb, "two lines"); + break; + case T::Parallel: case T::Perpendicular: case T::Angle: case T::Collinear: + need(line(d.ea), d.ea, "two lines"); + need(line(d.eb), d.eb, "two lines"); + break; + case T::Tangent: + if (!((round(d.ea) && (line(d.eb) || round(d.eb))) || (line(d.ea) && round(d.eb)))) + throw std::runtime_error(name + " needs a line and a circle or arc, or two circles or arcs; got " + + entity_label(ents, d.ea) + " and " + entity_label(ents, d.eb)); + break; + case T::Midpoint: need(seg(d.eb), d.eb, "a line to sit at the middle of"); break; + case T::PointOnLine: need(line(d.eb), d.eb, "a line"); break; + case T::PointOnObject: need(line(d.eb) || round(d.eb), d.eb, "a line, circle or arc"); break; + case T::Symmetric: need(line(d.ec), d.ec, "an axis line"); break; + default: break; + } + return d; +} + +json constraint_items(const std::vector& cons) +{ + json items = json::array(); + for (size_t i = 0; i < cons.size(); ++i) items.push_back(entity_constraint_json(cons[i], int(i))); + return items; +} + +// Whether `type` is a dimension, which holds a measured value; the other types are geometric. +bool is_dimension(SketchConstraintType type) +{ + using T = SketchConstraintType; + return type == T::Distance || type == T::DistanceX || type == T::DistanceY || type == T::Angle || type == T::Radius || + type == T::Diameter; +} + +// sketch_constrain: a geometric constraint; sketch_dimension (dimension): a dimension. Each is a +// CONSTRAIN bar button on the picks, or a constraint on named points, and refuses the other's types. +json sketch_constrain(DesignSketchTool& t, const json& params, bool dimension) +{ + if (is_dimension(constraint_type_arg(param(params, "type"))) != dimension) { + const std::string type = params.at("type").get(); + throw std::runtime_error(dimension ? type + " is a geometric constraint, which sketch_constrain adds" + : type + " is a dimension, which sketch_dimension adds"); + } + const std::vector defs = cad_constraint_defs(params, t.entities(), t.selection()); + const int first = t.constrain_scripted(defs); + if (first < 0) + throw std::runtime_error("over-constrained: " + param(params, "type").get() + + " was rejected and rolled back (dof " + std::to_string(sketch_dof(t)) + ")"); + json added = json::array(), items = json::array(); + for (int i = first; i < int(t.constraints().size()); ++i) { + added.push_back(i); + items.push_back(entity_constraint_json(t.constraints()[i], i)); + } + json r{{"ok", true}, {"added", std::move(added)}, {"items", std::move(items)}}; + r.update(solve_state(t)); + return r; +} + +json sketch_list_constraints(DesignSketchTool& t, const json&) +{ + json r{{"ok", true}, {"scope", "live"}, {"items", constraint_items(t.constraints())}}; + r.update(solve_state(t)); + return r; +} + +// sketch_delete_constraint: a constraint row's delete button in a sketch session. +json sketch_delete_constraint(DesignSketchTool& t, const json& params) +{ + const json v = param(params, "index"); + if (!v.is_number_integer()) throw std::runtime_error("index must be a constraint index (sketch_list_constraints' items[].index)"); + const int i = v.get(); + if (i < 0 || i >= int(t.constraints().size())) + throw std::runtime_error("constraint " + std::to_string(i) + " is out of range; the sketch has " + + std::to_string(t.constraints().size()) + " constraints"); + json removed = entity_constraint_json(t.constraints()[i], i); + if (!t.remove_constraint(i)) throw std::runtime_error("constraint " + std::to_string(i) + " could not be removed"); + json r{{"ok", true}, {"removed", std::move(removed)}}; + r.update(solve_state(t)); + return r; +} + +// A Design command on the open sketch alone, then a repaint. +json on_open_sketch(DesignPanel* panel, const char* name, const json& params) +{ + json r = cad_sketch_call(mcp_sketch(panel), name, params); + panel->mcp_viewport()->request_repaint(); + return r; +} + +json action_sketch_list_constraints(DesignPanel* panel, const json& params) +{ + const json sketch = param(params, "sketch"); + if (sketch.is_null()) return cad_sketch_call(mcp_sketch(panel), "sketch_list_constraints", params); + // A committed sketch's are read from the document, so no session is needed, nor disturbed. + const CadDocument& doc = panel->mcp_doc(); + const int si = sketch_arg(sketch, doc); + const CadFeature& f = doc.features[si]; + if (f.entities.empty()) + throw std::runtime_error("sketch " + std::to_string(si) + " is not drawn from entities; feature_describe reads its constraints"); + return json{{"ok", true}, {"scope", "committed"}, {"sketch", si}, {"items", constraint_items(f.entity_constraints)}, + {"constraints", int(f.entity_constraints.size())}}; +} + +// ---- Text and SVG art --------------------------------------------------------------------------- + +// The `position` param: [x, y] in the plane, where the text's or the art's centre goes; the origin when left out. +Vec2d position_arg(const json& params) +{ + const json v = param(params, "position"); + return v.is_null() ? Vec2d::Zero() : point_of(v, "position"); +} + +// sketch_insert_svg's outlines: the filled shapes of the SVG file params.path, centred on the origin and scaled by +// params.scale, as Insert SVG reads them (svg_to_regions()). Throws std::runtime_error for a file that is not there +// and one that gives no outline. +ImportRegions svg_regions(const json& params) +{ + const std::string path = input_path(param(params, "path"), "path"); + const json s = param(params, "scale"); + const double scale = s.is_null() ? 1.0 : s.is_number() ? s.get() : 0.0; + if (!(scale > 0.0) || !std::isfinite(scale)) throw std::runtime_error("scale must be a number above 0"); + ImportRegions regions = svg_to_regions(path, scale); + if (regions.empty()) throw std::runtime_error("the SVG file gives no outline: it has no filled shape, or it is not SVG"); + return regions; +} + +// sketch_insert_svg with a sketch open: the outlines moved by params.position, added as Insert SVG adds them there, +// as lines (DesignSketchTool::add_imported_regions()). +json sketch_insert_svg(DesignSketchTool& t, const json& params) +{ + if (!param(params, "plane").is_null()) throw std::runtime_error("plane is the open sketch's: leave it out"); + const ImportRegions regions = transform_regions(svg_regions(params), position_arg(params), 1.0, 1.0); + const std::size_t before = t.entities().size(); + if (!t.add_imported_regions(regions)) throw std::runtime_error("the SVG file's outlines give no lines"); + return json{{"ok", true}, {"scope", "sketch"}, {"added", int(t.entities().size() - before)}, + {"entities", int(t.entities().size())}}; +} + +// With a sketch open, the outlines go into it (sketch_insert_svg()). Otherwise Insert SVG's art feature on `plane`, XY +// when it is left out or null, in one undo step, with no file dialog and no placement step. +json action_sketch_insert_svg(DesignPanel* panel, const json& params) +{ + if (const DesignCanvas* vp = panel->mcp_viewport(); vp != nullptr && vp->is_sketching()) + return on_open_sketch(panel, "sketch_insert_svg", params); + const ImportRegions regions = svg_regions(params); + const json plane = param(params, "plane"); + int face_body = -1; + const SketchPlane pl = cad_resolve_plane(plane.is_null() ? json("XY") : plane, panel->mcp_doc(), false, &face_body); + const Vec2d at = position_arg(params); + json r = add_feature(panel, "art_index", [&] { return panel->mcp_push_art(regions, _L("SVG"), pl, face_body, at); }); + r["frame"] = frame_json(pl); + return r; +} + +// The Text dialog's Text feature from arguments (DesignPanel::mcp_push_text()), in one undo step, with no dialog and +// no placement step. Every refusal comes before anything changes: the font and the outline are checked first. +json action_sketch_text(DesignPanel* panel, const json& params) +{ + const json text = param(params, "text"); + if (!text.is_string()) throw std::runtime_error("text must be the words to outline"); + const json height = param(params, "height"); + if (!height.is_null() && !(height.is_number() && height.get() >= 0.5 && height.get() <= 500.0)) + throw std::runtime_error("height must be 0.5 to 500 mm"); + const std::string words = text.get(); + const std::string font = params.value("font", std::string()); + const bool bold = params.value("bold", false); + const bool italic = params.value("italic", false); + const double mm = height.is_null() ? 0.0 : height.get(); + int face_body = -1; + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), panel->mcp_doc(), false, &face_body); + const Vec2d at = position_arg(params); + std::string why; + if (CadFeature outlined; !panel->mcp_outline_text(outlined, words, font, bold, italic, mm, why)) + throw std::runtime_error(why); + json r = add_feature(panel, "text_index", [&] { + const int index = panel->mcp_push_text(words, font, bold, italic, mm, pl, face_body, at, why); + if (index < 0) throw std::runtime_error(why); + return index; + }); + r["frame"] = frame_json(pl); + return r; +} + +} // namespace + +std::vector sketch_target_indices(const json& params, const std::vector& selection, int entity_count, bool all_if_empty) +{ + std::vector out; + // An empty list names nothing, so it reads as left out, as the schema's default [] says and as + // entity_picks() reads it. Anything else that is given names what it holds. + if (const auto given = params.find("entities"); given != params.end() && !(given->is_array() && given->empty())) { + for (const auto& v : *given) out.push_back(v.get()); + return out; + } + out = selection; + if (out.empty() && all_if_empty) + for (int i = 0; i < entity_count; ++i) out.push_back(i); + return out; +} + +json cad_sketch_describe(const CadDocument& doc, const DesignSketchTool& tool, int sketch) +{ + sketch_arg(sketch, doc); + const CadFeature& f = doc.features[sketch]; + if (f.entities.empty()) + throw std::runtime_error("sketch " + std::to_string(sketch) + + " is not drawn from entities (a rectangle, circle, profile or imported art); feature_describe reads it"); + json ents = json::array(); + for (size_t i = 0; i < f.entities.size(); ++i) ents.push_back(sketch_entity_to(f.entities[i], int(i))); + json out{{"ok", true}, + {"sketch", sketch}, + {"name", f.name}, + {"plane", plane_json(f.plane, doc.modeling_origin)}, + {"entities", std::move(ents)}, + {"constraints", int(f.entity_constraints.size())}}; + out.update(sketch_report(tool.loop_report(f.entities))); + return out; +} + +json cad_sketch_call(DesignSketchTool& tool, const std::string& name, const json& params) +{ + const json p = params.is_object() ? params : json::object(); + if (name == "sketch_draw") return sketch_draw(tool, p); + if (name == "sketch_fillet") return sketch_corner(tool, p, false); + if (name == "sketch_chamfer") return sketch_corner(tool, p, true); + if (name == "sketch_trim") return sketch_trim_or_extend(tool, p, false); + if (name == "sketch_extend") return sketch_trim_or_extend(tool, p, true); + if (name == "sketch_offset") return sketch_offset(tool, p); + if (name == "sketch_mirror") return sketch_mirror(tool, p); + if (name == "sketch_transform") return sketch_transform(tool, p, false); + if (name == "sketch_pattern") return sketch_transform(tool, p, true); + if (name == "sketch_constrain") return sketch_constrain(tool, p, false); + if (name == "sketch_dimension") return sketch_constrain(tool, p, true); + if (name == "sketch_list_constraints") return sketch_list_constraints(tool, p); + if (name == "sketch_delete_constraint") return sketch_delete_constraint(tool, p); + if (name == "sketch_insert_svg") return sketch_insert_svg(tool, p); + throw std::runtime_error(name + " is not a Design command of the open sketch"); +} + +json cad_sketch_project(const CadDocument& doc, DesignSketchTool& tool, const json& params) +{ + if (!param(params, "plane").is_null()) throw std::runtime_error("plane is the open sketch's: leave it out"); + if (doc.bodies.empty()) throw CadPrecondition("no source body to project from"); + const json body = param(params, "source_body"); + if (!body.is_null() && !body.is_number_integer()) throw std::runtime_error("source_body must be a body index, or -1 for the last body"); + const int source = body.is_null() || body.get() == -1 ? int(doc.bodies.size()) - 1 : body.get(); + std::vector edges; + for (const json& v : param(params, "edges")) { + if (!v.is_number_integer()) throw std::runtime_error("edges must be edge ids (body_describe)"); + edges.push_back(v.get()); + } + const json face = param(params, "face"); + if (!face.is_null() && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe), or -1"); + // A body with no shape is the design's state; project_edges_on()'s other reasons are the call's edges, face and + // body index. + if (source >= 0 && source < int(doc.bodies.size()) && doc.bodies[size_t(source)].shape.IsNull()) + throw CadPrecondition("body " + std::to_string(source) + " has no shape"); + std::string error; + const std::vector ents = doc.project_edges_on(tool.plane(), source, edges, face.is_null() ? -1 : face.get(), error); + if (ents.empty()) throw std::runtime_error(error); + const int first = tool.add_entities_scripted(ents); + return json{{"ok", true}, {"scope", "sketch"}, {"first_index", first}, {"added", int(ents.size())}, + {"entities", int(tool.entities().size())}}; +} + +std::vector cad_constraint_defs(const json& params, const std::vector& ents, + const std::vector& selection) +{ + using T = SketchConstraintType; + const T type = constraint_type_arg(param(params, "type")); + const std::string name = params.at("type").get(); + const json refs = param(params, "refs"), picks = param(params, "entities"); + const bool by_refs = !refs.is_null() && !(refs.is_array() && refs.empty()); + const bool by_picks = !picks.is_null() && !(picks.is_array() && picks.empty()); + if (by_refs && by_picks) throw std::runtime_error("give entities or refs, not both"); + + // The value: mm, or degrees for an angle. A type that carries none refuses one. + const json value = param(params, "value"); + const bool valued = type == T::Distance || type == T::DistanceX || type == T::DistanceY || type == T::LockX || + type == T::LockY || type == T::Angle || type == T::Radius || type == T::Diameter || type == T::PointOnLine; + if (!value.is_null()) { + if (!value.is_number() || !std::isfinite(value.get())) throw std::runtime_error(name + " value must be a number"); + if (!valued) throw std::runtime_error(name + " takes no value"); + if ((type == T::Radius || type == T::Diameter) && !(value.get() > 0.0)) + throw std::runtime_error(name + " value must be > 0"); + if (type == T::Distance && value.get() < 0.0) throw std::runtime_error("distance value must be >= 0"); + } + + std::vector defs; + if (by_refs) { + defs.push_back(refs_constraint(type, name, refs, ents)); + if (value.is_null() && valued && type != T::PointOnLine) + throw std::runtime_error(name + " needs value (mm, or degrees for an angle)"); + write_plan_value(defs, value.is_null() ? 0.0 : value.get()); + return defs; + } + + // The CONSTRAIN bar's path: the planner takes the picks and chooses the points, as for a selection. + const std::vector picked = by_picks ? entity_indices(picks, ents) : selection; + const size_t takes = type == T::Fix || type == T::Horizontal || type == T::Vertical || type == T::Radius || type == T::Diameter + ? 1 : type == T::Symmetric ? 3 : 2; + if (by_picks && picked.size() > takes) + throw std::runtime_error(name + " takes " + std::to_string(takes) + (takes == 1 ? " entity" : " entities") + "; " + + std::to_string(picked.size()) + " were given"); + auto pick = [&](size_t k) { return k < picked.size() ? picked[k] : -1; }; + ConstraintPlan plan = plan_entity_constraint(ents, pick(0), pick(1), pick(2), type); + if (plan.kind == ConstraintPlan::Kind::Reject) { + std::string got; + for (int e : picked) got += (got.empty() ? "" : ", ") + entity_label(ents, e); + const auto& [code, text] = kConstraintRejects[int(plan.reason)]; + throw std::runtime_error(name + " " + text + (got.empty() ? "" : "; got " + got) + " (" + code + ")"); + } + // A value the button would ask for: the one given, else the current one, which the field shows. + if (plan.kind == ConstraintPlan::Kind::AskValue) write_plan_value(plan.defs, value.is_null() ? plan.prefill : value.get()); + return plan.defs; +} + +void sketch_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"sketch_describe", action_sketch_describe}, + {"sketch_validate", action_sketch_validate}, + {"sketch_list_constraints", action_sketch_list_constraints}, + {"sketch_project", action_sketch_project}, + {"sketch_text", action_sketch_text}, + {"sketch_insert_svg", action_sketch_insert_svg}, + {"sketch_blend_curve", action_sketch_blend_curve}, + {"sketch_create", action_sketch_create}, + {"sketch_finish", action_sketch_finish}, + {"sketch_cancel", action_sketch_cancel}, + {"sketch_edit", action_sketch_edit}, + {"sketch_draw", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_draw", a); }}, + {"sketch_select", action_sketch_select}, + {"sketch_delete", action_sketch_delete}, + {"sketch_toggle_construction", action_sketch_toggle_construction}, + {"sketch_offset", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_offset", a); }}, + {"sketch_mirror", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_mirror", a); }}, + {"sketch_repair", action_sketch_repair}, + {"sketch_set_value", action_sketch_set_value}, + {"sketch_fillet", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_fillet", a); }}, + {"sketch_chamfer", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_chamfer", a); }}, + {"sketch_trim", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_trim", a); }}, + {"sketch_extend", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_extend", a); }}, + {"sketch_transform", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_transform", a); }}, + {"sketch_pattern", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_pattern", a); }}, + {"sketch_constrain", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_constrain", a); }}, + {"sketch_dimension", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_dimension", a); }}, + {"sketch_delete_constraint", [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_delete_constraint", a); }}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp new file mode 100644 index 0000000000..c8c3dc5542 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp @@ -0,0 +1,1167 @@ +// The place Design, its Solid heading: extrude and revolve, which grow a body from a profile; fillet, chamfer, shell, +// draft, rib and hole, which shape one; sweep, loft, thicken and thread; boolean, mirror, pattern, split and +// delete_face; and align with list_align_types, which fasten one body to another. The cad_* builders they share with +// the Design tab's cards are here too (McpToolsDesign.hpp). solid_silent_forms() binds them to their tool blocks, and +// run_design_tool() (DesignTools.cpp) runs them behind the Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "libslic3r/Point.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignSketchTool.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/SketchSolver.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/CAD/ThreadStandards.hpp" +#include + +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// The operations each command takes (operation_arg()): extrude's, auto among them; revolve's, sweep's and loft's; +// boolean's, which combines two bodies there and makes none; mirror's, which keeps its image apart or joins it. +const std::vector kExtrudeOperations = {"auto", "new_body", "join", "cut", "intersect"}; +const std::vector kSolidOperations = {"new_body", "join", "cut", "intersect"}; +const std::vector kBooleanOperations = {"join", "cut", "intersect"}; +const std::vector kMirrorOperations = {"new_body", "join"}; + +// The `operation` argument: one of the words `takes` lists, "auto" coming back empty; `def` when the call leaves it +// out or gives null, and with no `def` the call must give one. +std::optional operation_arg(const json& params, const char* def, const std::vector& takes) +{ + json v = params.value("operation", json()); + if (v.is_null() && def != nullptr) v = def; + const std::string word = v.is_string() ? v.get() : std::string(); + if (std::find(takes.begin(), takes.end(), word) != takes.end()) { + if (word == "auto") return std::nullopt; + for (size_t i = 0; i < std::size(kOperations); ++i) + if (word == kOperations[i]) return BooleanMode(i); + } + std::string list; + for (size_t i = 0; i < takes.size(); ++i) + list += (i == 0 ? "" : i + 1 == takes.size() ? " or " : ", ") + takes[i]; + throw std::runtime_error("operation must be " + list); +} + +// Optional explicit closed profile: params["profile"] = [[x,y],...] in plane mm. +// This is the Measure->Build bridge — feed a measured contour straight back. +// An empty array is the row's default and means no profile. +bool profile_from(const json& params, SketchProfile& out) +{ + if (!params.contains("profile") || params["profile"].empty()) return false; + out.points.clear(); + for (const auto& p : params["profile"]) out.points.emplace_back(p[0].get(), p[1].get()); + out.closed = true; + if (out.points.size() < 3) throw std::runtime_error("profile needs at least 3 points [x, y]"); + return true; +} + +} // namespace + +// ---- Shared with the other Design files (DesignCommon.hpp) ---------------------------------- + +int target_body_arg(const json& params, const CadDocument& doc) +{ + int bi = params.value("body", -1); + if (bi >= int(doc.bodies.size())) + throw std::runtime_error("body index out of range (have " + std::to_string(doc.bodies.size()) + ")"); + return bi; // <0 -> kernel uses the last body +} + +std::optional face_group_named(const json& v) +{ + for (size_t i = 0; i < std::size(kFaceGroups); ++i) + if (v.is_string() && v.get() == kFaceGroups[i]) return FaceGroup(i); + return std::nullopt; +} + +int revolve_axis_arg(const json& params) +{ + const int axis = params.value("axis", 0); + if (axis != 0 && axis != 1) throw std::runtime_error("axis must be 0 (plane X) or 1 (plane Y)"); + return axis; +} + +bool revolve_line(const std::vector& ents, int e) +{ + return e >= 0 && e < int(ents.size()) && ents[size_t(e)].type == SketchEntity::Type::Line; +} + +int revolve_axis_entity_arg(const json& params, const CadDocument& doc, int si) +{ + const json ae = params.value("axis_entity", json()); + if (ae.is_null()) return params.contains("axis") ? -1 : DesignPanel::default_revolve_axis_entity(doc.features[si].entities); + if (!ae.is_number_integer()) throw std::runtime_error("axis_entity must be an entity index of the sketch, or -1 for the plane axis"); + if (ae.get() != -1 && !revolve_line(doc.features[si].entities, ae.get())) + throw std::runtime_error("axis_entity " + std::to_string(ae.get()) + " is not a line of sketch " + std::to_string(si)); + return ae.get(); +} + +namespace { + +// `edges` is one id or an array of ids; an array becomes ONE feature, every id resolved +// against the same body (a chain of single-edge features would see the ids drift). +std::vector edge_ids_arg(const json& params, const char* verb) +{ + if (!params.contains("edges")) + throw std::runtime_error(std::string(verb) + " needs 'edges' (an id or array of ids from body_describe)"); + const json& e = params["edges"]; + std::vector ids; + if (e.is_array()) for (const json& v : e) ids.push_back(v.get()); + else ids.push_back(e.get()); + if (ids.empty()) throw std::runtime_error(std::string(verb) + ": 'edges' is an empty array"); + return ids; +} + +// fillet and chamfer: the Fillet and Chamfer cards' Confirm on picked edges. +json action_dressup(DesignPanel* panel, const json& params, bool chamfer) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_dressup(doc, params, chamfer); + const char* key = chamfer ? "chamfer_index" : "fillet_index"; + json r = add_feature(panel, key, [&] { return add(panel->mcp_feature_name(chamfer ? _L("Chamfer") : _L("Fillet"))); }); + const int target = doc.features[r.at(key).get()].target_body; + r["body"] = target >= 0 ? target : int(doc.bodies.size()) - 1; + return r; +} + +json action_fillet(DesignPanel* panel, const json& params) { return action_dressup(panel, params, false); } +json action_chamfer(DesignPanel* panel, const json& params) { return action_dressup(panel, params, true); } + +// The Hole card's Confirm; the reply says where the hole went (cad_hole_placement) and the frame of its plane. +json action_hole(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + json resolved; + const auto add = cad_hole(doc, params, resolved); + json r = add_feature(panel, "hole_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Hole", "Design"))); }); + r.update(resolved); + return r; +} + +json action_boolean(DesignPanel* panel, const json& params) +{ + const BooleanMode m = *operation_arg(params, nullptr, kBooleanOperations); + const int target = params.value("target", 0); + const int tool = params.value("tool", 1); + const bool keep = params.value("keep_tool", false); + const double tol = params.value("tolerance", 0.0); + CadDocument& doc = panel->mcp_doc(); + int n = int(doc.bodies.size()); + if (target < 0 || target >= n || tool < 0 || tool >= n) + throw std::runtime_error("target/tool body index out of range (have " + std::to_string(n) + ")"); + if (target == tool) throw std::runtime_error("target and tool must differ"); + doc.checkpoint(); + int b = doc.add_boolean(m, target, tool, keep, tol, -1, -1, panel->mcp_feature_name(_L("Boolean"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"boolean_index", b}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// The Pattern card's Confirm: a linear or circular pattern replies with the frame of its plane. +json action_pattern(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_pattern(doc, params); + json r = add_feature(panel, "pattern_index", [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Pattern", "Design"))); }); + const CadFeature& f = doc.features[r.at("pattern_index").get()]; + if (f.pattern_curve_sketch < 0) r["frame"] = frame_json(f.plane); + return r; +} + +json action_shell(DesignPanel* panel, const json& params) +{ + const double thickness = params.value("thickness", 1.0); + if (thickness <= 0) throw std::runtime_error("thickness must be > 0"); + const int face = params.value("face", -1); // face id to leave open (-1 = closed hollow) + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to shell"); + int bi = target_body_arg(params, doc); + doc.checkpoint(); + int s = doc.add_shell(thickness, face, bi, panel->mcp_feature_name(_L_CONTEXT("Shell", "Design"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"shell_index", s}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_rib(DesignPanel* panel, const json& params) +{ + if (!params.contains("sketch")) throw std::runtime_error("rib needs 'sketch' (feature index)"); + if (!params.contains("entity")) throw std::runtime_error("rib needs 'entity' (entity index)"); + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to rib"); + int sketch = params["sketch"].get(); + int entity = params["entity"].get(); + double thickness = params.value("thickness", 2.0); + double depth = params.value("depth", 10.0); + int bi = target_body_arg(params, doc); + doc.checkpoint(); + int idx = doc.add_rib(sketch, entity, thickness, depth, bi, panel->mcp_feature_name(_L_CONTEXT("Rib", "Design"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"rib_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_draft(DesignPanel* panel, const json& params) +{ + if (!params.contains("face")) throw std::runtime_error("draft needs 'face' (id from body_describe)"); + const double angle = params.value("angle", 5.0); + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to draft"); + int bi = target_body_arg(params, doc); + doc.checkpoint(); + int d = doc.add_draft(angle, params["face"].get(), bi, panel->mcp_feature_name(_L("Draft"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"draft_index", d}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// ---- Solids from a profile: extrude and revolve ------------------------------------------------- +// +// With `sketch` they are the Extrude and Revolve cards' Confirm on a committed sketch (or one loop +// of it); without, they draw their own sketch first, a `profile` or a rectangle on `plane`. + +// A join or cut needs something to work on, as the Revolve card says. +void check_has_body(BooleanMode mode, const CadDocument& doc) +{ + if (mode != BooleanMode::New && doc.bodies.empty()) + throw CadPrecondition("operation " + std::string(kOperations[int(mode)]) + " needs a body; add or import one first"); +} + +double distance_arg(const json& params) +{ + const double d = params.value("distance", 10.0); + if (!(d > 0)) throw std::runtime_error("distance must be > 0"); + return d; +} + +ExtrudeEnd extrude_end_arg(const json& params) +{ + const std::string end = params.value("end", std::string("blind")); + // up_to_vertex needs a picked vertex, which no param carries. + for (int i = 0; i < int(ExtrudeEnd::UpToVertex); ++i) + if (end == kExtrudeEnds[i]) return ExtrudeEnd(i); + throw std::runtime_error("end must be blind, symmetric, two_sided, through_all or up_to_face"); +} + +// The end condition and the options that go with it, as the card's Confirm carries them onto the +// new feature (on_add_extrude). apply_feature reads extrude_end, not the kernel's `symmetric` flag; +// up_to_face is a face id of the target body. +void set_extrude_options(CadFeature& fe, const json& params, ExtrudeEnd end, double d) +{ + fe.flip = params.value("flip", false); + fe.taper_deg = params.value("taper", 0.0); + fe.extrude_end = end; + if (end == ExtrudeEnd::TwoSided) fe.distance2 = params.value("distance2", d); + if (end == ExtrudeEnd::UpToFace) fe.up_to_face = params.value("up_to_face", -1); +} + +// The sketch is the profile and fixes its plane, so these would be ignored; refusing them shows the +// caller its mistake. An empty profile is the row's default, which means none. +void refuse_with_sketch(const json& params) +{ + for (const char* k : {"profile", "width", "height", "plane"}) + if (params.contains(k) && !(params.at(k).is_array() && params.at(k).empty())) + throw std::runtime_error(std::string(k) + " cannot be given with sketch: the sketch is the profile and fixes its plane"); +} + +// Loop `loop` of sketch `si`: the region's own entities followed by those of the loops inside it, +// the list a loop picked in the viewport hands the Extrude card (selected_loop_entities()). +std::vector loop_entities(const DesignSketchTool& tool, const CadDocument& doc, int si, const json& loop) +{ + const std::vector& ents = doc.features[si].entities; + if (!loop.is_number_integer()) throw std::runtime_error("loop must be a loop index (closed_loops[].index of the sketch)"); + if (ents.empty()) + throw std::runtime_error("sketch " + std::to_string(si) + " is not drawn from entities, so it has no loops to pick; extrude it whole"); + const std::vector> regions = tool.region_entity_indices_with_holes(ents); + const int li = loop.get(); + if (li < 0 || li >= int(regions.size())) + throw std::runtime_error("loop " + std::to_string(li) + " does not exist; sketch " + std::to_string(si) + " has " + + std::to_string(regions.size()) + (regions.size() == 1 ? " closed loop" : " closed loops")); + std::vector out; + for (int ei : regions[li]) + if (ei >= 0 && ei < int(ents.size())) out.push_back(ents[ei]); + return out; +} + +// How many separate regions a whole-sketch extrude would have to build: loops not inside another. +int separate_regions(const DesignSketchTool& tool, const std::vector& ents) +{ + const DesignSketchTool::LoopReport rep = tool.loop_report(ents); + std::vector inside(rep.loops.size(), false); + for (const auto& l : rep.loops) + for (int h : l.holes) + if (h >= 0 && h < int(inside.size())) inside[h] = true; + return int(std::count(inside.begin(), inside.end(), false)); +} + +// The body an extrude or revolve went into: the one it made, else the one it joined, cut or +// intersected (its target, or by default the last body). +int result_body(const CadDocument& doc, int feature) +{ + for (size_t b = 0; b < doc.bodies.size(); ++b) + if (doc.bodies[b].source_feature == feature) return int(b); + const int t = doc.features[feature].target_body; + return t >= 0 ? t : int(doc.bodies.size()) - 1; +} + +// The operation a solid feature was built with and the body it went into, as the defaults resolved. +json body_reply(json r, const CadDocument& doc, const char* index_key) +{ + const int f = r.at(index_key).get(); + r["operation"] = kOperations[int(doc.features[f].mode)]; + r["body"] = result_body(doc, f); + return r; +} + +// Both forms reply alike, so a caller need not know which it used: the sketch and the feature, and +// what the defaults resolved to. +json solid_reply(json r, const CadDocument& doc, const char* index_key, int sketch) +{ + r = body_reply(std::move(r), doc, index_key); + const int f = r.at(index_key).get(); + r["sketch_index"] = sketch; + r["frame"] = frame_json(sketch >= 0 ? doc.features[sketch].plane : doc.features[f].plane); + return r; +} + +json action_extrude(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const json sketch = params.value("sketch", json()); + const json loop = params.value("loop", json()); + const ExtrudeEnd end = extrude_end_arg(params); + if (!params.value("face", json()).is_null()) { + SketchPlane frame; + const auto add = cad_face_extrude(doc, params, frame); + json r = add_feature(panel, "extrude_index", + [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); }); + r = solid_reply(std::move(r), doc, "extrude_index", -1); + r["frame"] = frame_json(frame); // the face's, which the feature does not carry + r["face"] = params.at("face"); + r["end"] = kExtrudeEnds[int(end)]; + return r; + } + if (!sketch.is_null()) { + const DesignCanvas* vp = panel->mcp_viewport(); + if (vp == nullptr) throw no_design_view(); + const auto add = cad_sketch_extrude(doc, vp->mcp_sketch_tool(), params); + json r; + try { + r = add_feature(panel, "extrude_index", + [&] { return add(panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); }); + } catch (const ToolFailure& e) { + // A whole sketch builds one region, with the loops inside it as holes. When the rebuild + // refused a sketch of several, name the way to take one; any other failure has another cause. + if (!loop.is_null() || e.details.value("code", std::string()) != "rebuild_failed" || + separate_regions(vp->mcp_sketch_tool(), doc.features[sketch.get()].entities) < 2) + throw; + throw ToolFailure(std::string(e.what()) + + "; pass \"loop\" to extrude one of its regions (closed_loops of sketch_describe {sketch})", + e.details); + } + r = solid_reply(std::move(r), doc, "extrude_index", sketch.get()); + r["end"] = kExtrudeEnds[int(end)]; + if (!loop.is_null()) r["loop"] = loop; + return r; + } + if (!loop.is_null()) throw std::runtime_error("loop picks a loop of a committed sketch; give sketch too"); + + const double d = distance_arg(params); + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); + const auto mode = operation_arg(params, "new_body", kExtrudeOperations); + const int body = std::max(-1, target_body_arg(params, doc)); + if (mode) check_has_body(*mode, doc); + SketchProfile prof; + const bool has_prof = profile_from(params, prof); + double w = 0, h = 0; + if (!has_prof) { + w = params.value("width", 20.0); h = params.value("height", 20.0); + if (w <= 0 || h <= 0) throw std::runtime_error("width and height must be > 0"); + } + int s = -1; + json r = add_feature(panel, "extrude_index", [&] { + const std::string sketch_name = panel->mcp_feature_name(_L("Sketch")); + s = has_prof ? doc.add_sketch_profile(prof, pl, sketch_name) + : doc.add_sketch(SketchShape::Rectangle, pl, w, h, 0.0, sketch_name); + // "auto" decides as the card does for a sketch: join the body the profile touches. + const int touching = mode ? -1 : doc.body_touching_sketch(s); + const BooleanMode m = mode.value_or(touching >= 0 ? BooleanMode::Add : BooleanMode::New); + const int e = doc.add_extrude(s, d, /*symmetric*/false, m, panel->mcp_feature_name(_L_CONTEXT("Extrude", "Design"))); + set_extrude_options(doc.features[e], params, end, d); + doc.features[e].target_body = body >= 0 ? body : touching; + return e; + }); + r = solid_reply(std::move(r), doc, "extrude_index", s); + r["end"] = kExtrudeEnds[int(end)]; + return r; +} + +json action_revolve(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const json sketch = params.value("sketch", json()); + if (!sketch.is_null()) { + const auto add = cad_sketch_revolve(doc, params); + json r = add_feature(panel, "revolve_index", [&] { return add(panel->mcp_feature_name(_L("Revolve"))); }); + r = solid_reply(std::move(r), doc, "revolve_index", sketch.get()); + const CadFeature& f = doc.features[r.at("revolve_index").get()]; + r["axis"] = f.revolve_axis; + r["axis_entity"] = f.revolve_axis_entity; + return r; + } + if (!params.value("axis_entity", json()).is_null()) + throw std::runtime_error("axis_entity is a line of a committed sketch; give sketch too"); + + const double angle = params.value("angle", 360.0); + const int axis = revolve_axis_arg(params); + const bool flip = params.value("flip", false); + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); + const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + const SketchProfile prof = cad_revolve_profile(params); + int s = -1; + json r = add_feature(panel, "revolve_index", [&] { + s = doc.add_sketch_profile(prof, pl, panel->mcp_feature_name(_L("Sketch"))); + const int rv = doc.add_revolve(s, angle, axis, flip, mode, panel->mcp_feature_name(_L("Revolve"))); + doc.features[rv].target_body = body; + return rv; + }); + r = solid_reply(std::move(r), doc, "revolve_index", s); + r["axis"] = axis; + return r; +} + +json action_mirror(DesignPanel* panel, const json& params) +{ + const BooleanMode m = *operation_arg(params, "new_body", kMirrorOperations); + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to mirror"); + int bi = target_body_arg(params, doc); + bool keep = params.value("keep_original", true); + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XZ")), doc, false); + doc.checkpoint(); + int idx = doc.add_mirror(pl, bi, m, panel->mcp_feature_name(_L_CONTEXT("Mirror", "Design"))); + doc.features[idx].mirror_keep_original = keep; + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"mirror_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, + {"frame", frame_json(pl)}}; +} + +// Whether a thicken call thickens a whole sheet body (type surface, or no type and no face) rather than a face. +bool thickens_surface(const json& params) +{ + const json type = params.value("type", json()); + return type.is_null() ? params.value("face", json()).is_null() : type == "surface"; +} + +// The Thicken and Thicken Surface cards' Confirm, each feature named as its card names it. +json action_thicken(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_thicken(doc, params); + const wxString name = thickens_surface(params) ? _L("Thicken Surface") : _L("Thicken"); + return add_feature(panel, "thicken_index", [&] { return add(panel->mcp_feature_name(name)); }); +} + +// With a plane, the Cut card's Confirm (on_add_cut); with a face, a split along that face's plane. +json action_split(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + json resolved; + const auto add = cad_split(doc, params, resolved); + const bool face = !params.value("face", json()).is_null(); + json r = add_feature(panel, "split_index", [&] { + return add(panel->mcp_feature_name(face ? _L_CONTEXT("Split", "Design") : _L_CONTEXT("Cut", "Design"))); + }); + r.update(resolved); + return r; +} + +json action_delete_face(DesignPanel* panel, const json& params) +{ + if (!params.contains("faces")) throw std::runtime_error("delete_face needs 'faces' (array of face ids)"); + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no body to delete faces from"); + int bi = target_body_arg(params, doc); + std::vector faces; + if (params["faces"].is_array()) + for (const auto& v : params["faces"]) faces.push_back(v.get()); + doc.checkpoint(); + int idx = doc.add_delete_face(bi, faces, panel->mcp_feature_name(_L("Delete Face"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// Thread, sweep and loft: their cards' Confirm. They rebuild off the UI thread, as the cards do. +json action_thread(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + json resolved; + const auto add = cad_thread(doc, params, resolved); + json r = add_feature(panel, "thread_index", [&] { return add(panel->mcp_feature_name(_L("Thread"))); }, true); + r.update(resolved); + r["body"] = result_body(doc, r.at("thread_index").get()); // a rod threaded from nothing is a new body + return r; +} + +json action_sweep(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_sweep(doc, params); + json r = add_feature(panel, "sweep_index", [&] { return add(panel->mcp_feature_name(_L("Sweep"))); }, true); + return body_reply(std::move(r), doc, "sweep_index"); +} + +json action_loft(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_loft(doc, params); + json r = add_feature(panel, "loft_index", [&] { return add(panel->mcp_feature_name(_L("Loft"))); }, true); + return body_reply(std::move(r), doc, "loft_index"); +} + +// The Mate card's Confirm: the feature keeps the history's name for it, Mate. +json action_align(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_align(doc, params); + return add_feature(panel, "align_index", [&] { return add(panel->mcp_feature_name(_L("Mate"))); }); +} + +json action_list_align_types(DesignPanel* panel, const json& params) { return cad_align_types(panel->mcp_doc(), params); } + +} // namespace + +std::function cad_sketch_extrude(CadDocument& doc, const DesignSketchTool& tool, const json& params) +{ + refuse_with_sketch(params); + const int si = sketch_arg(params.value("sketch", json()), doc); + const double d = distance_arg(params); + const ExtrudeEnd end = extrude_end_arg(params); + const auto mode = operation_arg(params, "auto", kExtrudeOperations); + int body = std::max(-1, target_body_arg(params, doc)); + if (mode) check_has_body(*mode, doc); + const json loop = params.value("loop", json()); + std::vector subset; + if (!loop.is_null()) subset = loop_entities(tool, doc, si, loop); + // The card's defaults (open_tool): it works on the body the profile lies on or touches, and + // "auto" joins that body, or starts a new one when the profile touches none. + const int touching = doc.body_touching_sketch(si); + if (body < 0) body = touching; + const BooleanMode m = mode.value_or(touching >= 0 ? BooleanMode::Add : BooleanMode::New); + return [&doc, params, si, d, end, body, m, by_loop = !loop.is_null(), subset](const std::string& name) { + const SketchPlane plane = doc.features[si].plane; + const int e = by_loop ? doc.add_extrude_entities(subset, plane, d, false, m, name) : doc.add_extrude(si, d, false, m, name); + set_extrude_options(doc.features[e], params, end, d); + doc.features[e].target_body = body; + return e; + }; +} + +std::function cad_sketch_revolve(CadDocument& doc, const json& params) +{ + refuse_with_sketch(params); + const int si = sketch_arg(params.value("sketch", json()), doc); + const double angle = params.value("angle", 360.0); + const int axis = revolve_axis_arg(params); + const bool flip = params.value("flip", false); + const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + const int axis_entity = revolve_axis_entity_arg(params, doc, si); + return [&doc, si, angle, axis, flip, mode, body, axis_entity](const std::string& name) { + const int r = doc.add_revolve(si, angle, axis, flip, mode, name); + doc.features[r].revolve_axis_entity = axis_entity; + doc.features[r].target_body = body; + return r; + }; +} + +json cad_align_types(const CadDocument& doc, const json& params) +{ + for (const char* k : {"cs_a", "cs_b"}) + if (!params.value(k, json()).is_number_integer()) + throw std::runtime_error(std::string("list_align_types needs '") + k + "' (CoordSys feature index)"); + const int cs_a = params.at("cs_a").get(); + const int cs_b = params.at("cs_b").get(); + json types = json::array(); + for (const CadDocument::MateOption& o : doc.mate_options(cs_a, cs_b)) + types.push_back(json{{"type", enum_name(kAlignTypes, o.kind)}, {"fits", o.viable}, {"reason", o.viable ? json() : json(o.reason)}}); + return json{{"ok", true}, {"cs_a", cs_a}, {"cs_b", cs_b}, {"types", std::move(types)}}; +} + +SketchProfile cad_revolve_profile(const json& params) +{ + SketchProfile prof; + if (profile_from(params, prof)) return prof; + const double w = params.value("width", 20.0), h = params.value("height", 10.0); + if (w <= 0 || h <= 0) throw std::runtime_error("width and height must be > 0"); + // On one side of the axis, as make_revolve requires: a rectangle across it would sweep + // through itself. Both corner orders run counter-clockwise, as a drawn profile does. + const double a = w / 2; + prof.points = revolve_axis_arg(params) == 0 ? std::vector{{-a, 0}, {a, 0}, {a, h}, {-a, h}} + : std::vector{{0, -a}, {h, -a}, {h, a}, {0, a}}; + prof.closed = true; + return prof; +} + +std::function cad_face_extrude(CadDocument& doc, const json& params, SketchPlane& frame) +{ + for (const char* k : {"sketch", "loop", "profile", "width", "height", "plane"}) + if (params.contains(k) && !params.at(k).is_null() && !(params.at(k).is_array() && params.at(k).empty())) + throw std::runtime_error(std::string(k) + " cannot be given with face: the face is the profile and fixes its plane"); + const json fv = params.at("face"); + if (!fv.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); + if (doc.bodies.empty()) throw CadPrecondition("a face push/pull needs a body"); + const int asked = target_body_arg(params, doc); + const int b = asked >= 0 ? asked : int(doc.bodies.size()) - 1; + const int fi = fv.get(); + const TopoDS_Face face = GeometryEngine::face_by_index(doc.bodies[b].shape, fi); + if (face.IsNull()) + throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " does not exist (it has " + + std::to_string(GeometryEngine::face_count(doc.bodies[b].shape)) + " faces)"); + if (!doc.plane_of_face(b, fi, frame)) + throw std::runtime_error("face " + std::to_string(fi) + " of body " + std::to_string(b) + " is " + face_kind_name(face) + + "; a push/pull needs a planar face"); + // The kernel grows a face blind or symmetric along its normal (apply_feature); the card's other + // ends and its taper act on sketch profiles only. + const ExtrudeEnd end = extrude_end_arg(params); + if (end != ExtrudeEnd::Blind && end != ExtrudeEnd::Symmetric) throw std::runtime_error("a face push/pull ends blind or symmetric"); + if (params.value("taper", 0.0) != 0.0) throw std::runtime_error("taper does not apply to a face push/pull"); + const double d = distance_arg(params); + const bool flip = params.value("flip", false); + // The card joins a picked face's own body by default. + const BooleanMode mode = operation_arg(params, "auto", kExtrudeOperations).value_or(BooleanMode::Add); + return [&doc, fi, d, mode, end, flip, b](const std::string& name) { + const int e = doc.add_extrude_face(fi, d, false, mode, name); + doc.features[e].extrude_end = end; + doc.features[e].flip = flip; + doc.features[e].target_body = b; // the face id is of this body + return e; + }; +} + +json cad_hole_placement(const CadDocument& doc, const json& params, SketchPlane& plane, int& target_body) +{ + if (doc.bodies.empty()) throw CadPrecondition("no body to drill"); + int face_body = -1; + plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true, &face_body); + const int body = target_body_arg(params, doc); + if (face_body >= 0 && body >= 0 && body != face_body) + throw std::runtime_error("the plane is a face of body " + std::to_string(face_body) + ", so that body is drilled, not body " + + std::to_string(body)); + // A face plane drills its own body, as the Hole card does for a picked face; otherwise the + // body asked for, or the kernel's default, the last body. + target_body = face_body >= 0 ? face_body : body; + json r{{"body", target_body >= 0 ? target_body : int(doc.bodies.size()) - 1}}; + const json at = params.value("at", json()); + if (at.is_null()) { + r["x"] = params.value("x", 0.0); + r["y"] = params.value("y", 0.0); + return r; + } + if (params.contains("x") || params.contains("y")) throw std::runtime_error("give at, or x and y, not both"); + static const std::string kAtForms = "at must be [x, y, z], {\"body\": b, \"face\": f} or {\"body\": b, \"edge\": e}"; + Vec3d p; + if (at.is_array()) { + if (at.size() != 3 || !at[0].is_number() || !at[1].is_number() || !at[2].is_number()) throw std::runtime_error(kAtForms); + p = Vec3d(at[0].get(), at[1].get(), at[2].get()); + } else if (at.is_object() && at.size() == 2 && at.contains("body") && at.at("body").is_number_integer() && + ((at.contains("face") && at.at("face").is_number_integer()) || (at.contains("edge") && at.at("edge").is_number_integer()))) { + // A round reference stands for its axis, so the hole shares it: the STEP-hole fix. + const int b = at.at("body").get(); + if (b < 0 || b >= int(doc.bodies.size())) + throw std::runtime_error("at: body " + std::to_string(b) + " is out of range (have " + std::to_string(doc.bodies.size()) + ")"); + const TopoDS_Shape& shape = doc.bodies[b].shape; + const bool is_face = at.contains("face"); + const int id = at.at(is_face ? "face" : "edge").get(); + const std::string what = std::string(is_face ? "face " : "edge ") + std::to_string(id) + " of body " + std::to_string(b); + GeometryEngine::CylinderFace round; + if (is_face) { + const TopoDS_Face f = GeometryEngine::face_by_index(shape, id); + if (f.IsNull()) throw std::runtime_error("at: " + what + " does not exist"); + round = GeometryEngine::cylinder_of_face(f); + if (!round.ok) throw std::runtime_error(what + " is " + face_kind_name(f) + "; \"at\" takes a cylindrical face or a circular edge"); + } else { + const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id); + if (e.IsNull()) throw std::runtime_error("at: " + what + " does not exist"); + round = GeometryEngine::circle_of_edge(e); + if (!round.ok) throw std::runtime_error(what + " is a " + edge_kind_name(e) + "; \"at\" takes a cylindrical face or a circular edge"); + } + if (std::abs(round.axis.dot(plane.normal)) < std::cos(M_PI / 180.0)) + throw std::runtime_error("the axis of " + what + " is not square to the plane, so a hole drilled from it cannot share that axis"); + p = round.base; + } else { + throw std::runtime_error(kAtForms); + } + // Projected onto the plane along its normal, in the plane's frame. + const Vec3d d = p - plane.origin; + r["x"] = d.dot(plane.x_axis); + r["y"] = d.dot(plane.y_axis); + r["off_plane"] = d.dot(plane.normal); + return r; +} + +std::function cad_thread(CadDocument& doc, const json& params, json& resolved) +{ + auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; + auto flag = [&](const char* k) { + if (!params.at(k).is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); + return params.at(k).get(); + }; + // A size in mm that replaces the standard's; absent keeps it. + auto size = [&](const char* k) -> std::optional { + if (!given(k)) return std::nullopt; + if (!params.at(k).is_number() || !(params.at(k).get() > 0)) + throw std::runtime_error(std::string(k) + " must be a number > 0 (mm)"); + return params.at(k).get(); + }; + const bool on_face = given("face"), on_edge = given("edge"); + if (on_face && on_edge) throw std::runtime_error("give face or edge, not both"); + + SketchPlane plane; + GeometryEngine::CylinderFace cyl; + bool internal = false; + int target = -1; // the kernel's last body + if (on_face || on_edge) { + // A picked bore, boss or rim: the thread runs along its axis from its base, as the card's + // pick sets it, on that body. + const std::string kind = on_face ? "face" : "edge"; + for (const char* k : {"plane", "x", "y", "at"}) + if (given(k)) throw std::runtime_error(std::string(k) + " cannot be given with " + kind + ": the thread runs on its axis"); + if (doc.bodies.empty()) throw CadPrecondition("no body to thread"); + if (!params.at(kind).is_number_integer()) throw std::runtime_error(kind + " must be an id from body_describe"); + target = target_body_arg(params, doc); + if (target < 0) target = int(doc.bodies.size()) - 1; + const int id = params.at(kind).get(); + const TopoDS_Shape& shape = doc.bodies[target].shape; + const std::string what = kind + " " + std::to_string(id) + " of body " + std::to_string(target); + if (!doc.thread_target(target, on_face ? id : -1, on_face ? -1 : id, plane, cyl)) { + if (on_face) { + const TopoDS_Face f = GeometryEngine::face_by_index(shape, id); + if (f.IsNull()) + throw std::runtime_error(what + " does not exist (it has " + std::to_string(GeometryEngine::face_count(shape)) + " faces)"); + throw std::runtime_error(what + " is " + face_kind_name(f) + "; a thread needs a cylindrical face or a circular edge"); + } + const TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id); + if (e.IsNull()) + throw std::runtime_error(what + " does not exist (it has " + std::to_string(GeometryEngine::edge_count(shape)) + " edges)"); + throw std::runtime_error(what + " is a " + edge_kind_name(e) + "; a thread needs a cylindrical face or a circular edge"); + } + // A bore taps, a boss is threaded; a rim cannot tell, so it is external unless told. + internal = given("internal") ? flag("internal") : cyl.internal; + resolved = {{"x", 0.0}, {"y", 0.0}}; + } else { + if (!given("internal")) + throw std::runtime_error("internal is required for a thread on a plane: true taps a hole in a body, false threads a rod"); + internal = flag("internal"); + if (!doc.bodies.empty()) { + resolved = cad_hole_placement(doc, params, plane, target); // placed as a hole is + } else { + // A rod threaded from nothing: there is no body to place against. + if (internal) throw CadPrecondition("an internal thread needs a body to tap; add or import one first"); + if (given("at")) throw std::runtime_error("at places a thread against a body, and there is none; give x and y"); + plane = cad_resolve_plane(params.value("plane", json("XY")), doc, true); + resolved = {{"x", params.value("x", 0.0)}, {"y", params.value("y", 0.0)}}; + } + } + + // The standard named, else the one nearest the picked cylinder, as the card infers it. + const ThreadSpec* spec = nullptr; + if (given("designation")) { + const json& d = params.at("designation"); + if (!d.is_string()) throw std::runtime_error("designation must be a string such as \"M5\" or \"1/4-20 UNC\""); + spec = find_thread_standard(d.get()); + if (spec == nullptr) { + // The same name in another case, else the names that start the other or are one edit away. + const std::string want = boost::algorithm::to_lower_copy(d.get()); + std::string close; + for (const ThreadSpec& t : thread_standards()) + if (boost::algorithm::to_lower_copy(std::string(t.name)) == want) close = t.name; + if (close.empty() && !want.empty()) + for (const ThreadSpec& t : thread_standards()) { + const std::string n = boost::algorithm::to_lower_copy(std::string(t.name)); + if (n.rfind(want, 0) == 0 || want.rfind(n, 0) == 0 || edit_distance(n, want) <= 1) + close += (close.empty() ? "" : ", ") + t.name; + } + throw std::runtime_error("unknown designation \"" + d.get() + "\"" + + (close.empty() ? std::string("; ISO metric (M5, M8x1) and UTS (1/4-20 UNC) sizes are known") : "; close: " + close)); + } + } else if (cyl.ok) { + spec = nearest_thread_standard(2.0 * cyl.radius, internal); + } + const std::optional diameter = size("diameter"), pitch = size("pitch"), depth = size("depth"), length = size("length"); + if (spec == nullptr && (!diameter || !pitch)) + throw std::runtime_error("a thread on a plane needs designation, or diameter and pitch for a custom thread"); + ThreadSpec s = spec != nullptr ? *spec : ThreadSpec{"", *diameter, *pitch, ThreadSpec::Series::MetricCoarse}; + if (diameter) s.major_diameter_mm = *diameter; + if (pitch) s.pitch_mm = *pitch; + // The 60 degree V of the standards: a tapped thread runs from the minor diameter out to the + // major, a rod's in from the crests, as the card sets the depth for the role. + const double d = depth ? *depth : internal ? s.internal_depth_mm() : s.thread_depth_mm(); + double len = 0; + if (length) + len = *length; + else if (on_face && cyl.height > 1e-6) + len = cyl.height; // the card's default: the whole face + else + throw std::runtime_error(on_face ? "length is required: the face has no length" + : on_edge ? "length is required for a thread on an edge" + : "length is required for a thread on a plane"); + + const bool custom = spec == nullptr || s.major_diameter_mm != spec->major_diameter_mm || s.pitch_mm != spec->pitch_mm; + resolved["designation"] = custom ? json() : json(spec->name); + resolved["internal"] = internal; + resolved["diameter"] = s.major_diameter_mm; + resolved["pitch"] = s.pitch_mm; + resolved["depth"] = d; + resolved["length"] = len; + resolved["frame"] = frame_json(plane); + const double x = resolved.at("x").get(), y = resolved.at("y").get(); + return [&doc, s, len, d, internal, x, y, plane, target](const std::string& name) { + const int t = doc.add_thread(0.5 * s.major_diameter_mm, s.pitch_mm, len, d, internal, x, y, plane, name); + doc.features[t].target_body = target; + return t; + }; +} + +std::function cad_sweep(CadDocument& doc, const json& params) +{ + const int si = sketch_arg(params.value("sketch", json()), doc); + const json pv = params.value("path", json()); + if (!pv.is_number_integer()) throw std::runtime_error("path must be the feature index of a sketch or a helix (describe_design)"); + const int pi = pv.get(); + check_feature_index(pi, doc); + const CadFeatureType pt = doc.features[pi].type; + if (pt != CadFeatureType::Sketch && pt != CadFeatureType::Helix) + throw std::runtime_error("path " + std::to_string(pi) + " (" + feature_type_name(pt) + ") is not a sketch or a helix"); + if (pi == si) throw std::runtime_error("the path cannot be the profile sketch itself"); + const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + return [&doc, si, pi, mode, body](const std::string& name) { + const int i = doc.add_sweep(si, pi, mode, name); + doc.features[i].target_body = body; + return i; + }; +} + +std::function cad_loft(CadDocument& doc, const json& params) +{ + const json pv = params.value("profiles", json()); + if (!pv.is_array()) throw std::runtime_error("profiles must be a list of sketch feature indices, in loft order"); + if (pv.size() < 2) throw std::runtime_error("loft needs 2 or more sketches in profiles"); + std::vector refs; + for (const json& v : pv) { + if (!v.is_number_integer()) throw std::runtime_error("profiles must hold sketch feature indices (describe_design)"); + const int si = sketch_arg(v, doc); + if (std::find(refs.begin(), refs.end(), si) != refs.end()) + throw std::runtime_error("sketch " + std::to_string(si) + " is listed twice in profiles"); + refs.push_back(si); + } + const json ruled = params.value("ruled", json(false)); + if (!ruled.is_boolean()) throw std::runtime_error("ruled must be true or false"); + const BooleanMode mode = *operation_arg(params, "new_body", kSolidOperations); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + return [&doc, refs, ruled = ruled.get(), mode, body](const std::string& name) { + const int i = doc.add_loft(refs, ruled, mode, name); + doc.features[i].target_body = body; + return i; + }; +} + +std::function cad_hole(CadDocument& doc, const json& params, json& resolved) +{ + const int style = enum_index("type", params.value("type", json("simple")), kHoleTypes); + // A seat's sizes are its type's: beside another type they would size nothing, so they are refused. A null is the + // argument left out. + static const std::pair kSeatOf[] = {{"cbore_diameter", 1}, {"cbore_depth", 1}, {"csink_diameter", 2}, {"csink_angle", 2}}; + for (const auto& [key, seat] : kSeatOf) + if (seat != style && params.contains(key) && !params.at(key).is_null()) + throw std::runtime_error(std::string(key) + " goes with type " + kHoleTypes[seat] + ", not " + kHoleTypes[style]); + const json named = params.value("designation", json()); + const bool standard = !named.is_null(); + if (standard) { + if (params.contains("diameter")) throw std::runtime_error("give diameter or designation, not both"); + // The standard sizes the seat too (CadDocument::add_hole_standard), so these would be replaced. + for (const char* k : {"cbore_diameter", "cbore_depth", "csink_diameter", "csink_angle", "standard"}) + if (params.contains(k)) + throw std::runtime_error(std::string(k) + " cannot be given with designation: the standard sizes the hole and its seat"); + if (!named.is_string() || named.get().empty()) + throw std::runtime_error("designation must be a standard size such as \"M6\" or \"1/4-20\""); + } + const double diameter = params.value("diameter", 5.0); + if (diameter <= 0) throw std::runtime_error("diameter must be > 0"); + const double depth = params.value("depth", 10.0); + const bool through = params.value("through", false); + const double cbore_diameter = params.value("cbore_diameter", 0.0); + const double cbore_depth = params.value("cbore_depth", 0.0); + const double csink_diameter = params.value("csink_diameter", 0.0); + const double csink_angle = params.value("csink_angle", 90.0); + const std::string provenance = params.value("standard", std::string()); + const std::string designation = standard ? named.get() : std::string(); + SketchPlane plane; + int body = -1; + resolved = cad_hole_placement(doc, params, plane, body); + resolved["frame"] = frame_json(plane); + const double x = resolved.at("x").get(), y = resolved.at("y").get(); + // add_hole_standard throws on a designation it does not know, which the caller's add_feature rolls back. + return [&doc, style, standard, designation, diameter, depth, through, cbore_diameter, cbore_depth, csink_diameter, + csink_angle, provenance, x, y, plane, body](const std::string& name) { + const int h = standard ? doc.add_hole_standard(designation, style, through, depth, x, y, plane, name) + : doc.add_hole_styled(diameter, depth, through, x, y, plane, style, cbore_diameter, cbore_depth, + csink_diameter, csink_angle, provenance, name); + doc.features[h].target_body = body; + return h; + }; +} + +std::function cad_thicken(CadDocument& doc, const json& params) +{ + const json type = params.value("type", json()); + if (!type.is_null() && type != "face" && type != "surface") throw std::runtime_error("type must be face or surface"); + const bool surface = thickens_surface(params); + const json face = params.value("face", json()); + if (surface && !face.is_null()) + throw std::runtime_error("type surface thickens a whole sheet body and takes no face; type face thickens a face"); + if (!surface && face.is_null()) throw std::runtime_error("type face needs face, a face id (body_describe)"); + if (!surface && !face.is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); + if (doc.bodies.empty()) throw CadPrecondition(surface ? "no sheet body to thicken" : "no body to thicken"); + const int body = target_body_arg(params, doc); + const double thickness = params.value("thickness", 2.0); + const bool flip = params.value("flip", false); + if (surface) + return [&doc, body, thickness, flip](const std::string& name) { return doc.add_thicken_surface(body, thickness, flip, name); }; + return [&doc, body, fi = face.get(), thickness, flip](const std::string& name) { + return doc.add_thicken(body, fi, thickness, flip, name); + }; +} + +std::function cad_pattern(CadDocument& doc, const json& params) +{ + const int layout = enum_index("type", params.value("type", json("linear")), kPatternTypes); + const bool curve = layout == 2; + // What each layout reads beside count and body, by layout (linear, circular, curve): beside another it would place + // nothing, so it is refused. A null is the argument left out. + struct Takes + { + const char* key; + const char* types; + bool by[3]; + }; + static const Takes kTakes[] = {{"spacing", "linear", {true, false, false}}, {"dir", "linear", {true, false, false}}, + {"angle", "circular", {false, true, false}}, {"plane", "linear or circular", {true, true, false}}, + {"sketch", "curve", {false, false, true}}, {"entity", "curve", {false, false, true}}}; + for (const Takes& t : kTakes) + if (!t.by[layout] && params.contains(t.key) && !params.at(t.key).is_null()) + throw std::runtime_error(std::string(t.key) + " goes with type " + t.types + ", not " + kPatternTypes[layout]); + // The curve the copies follow, which a curve pattern needs. + if (curve) + for (const char* k : {"sketch", "entity"}) + if (!params.value(k, json()).is_number_integer()) + throw std::runtime_error(std::string("a curve pattern needs ") + k + + (std::string(k) == "sketch" ? ", the feature index of the sketch holding the guide curve" + : ", the guide curve's entity index within that sketch")); + const int count = params.value("count", 3); + if (count < 1) throw std::runtime_error("count must be >= 1"); + if (doc.bodies.empty()) throw CadPrecondition("no body to pattern"); + const int body = target_body_arg(params, doc); + if (curve) + return [&doc, count, sketch = params.at("sketch").get(), entity = params.at("entity").get(), body](const std::string& name) { + return doc.add_pattern_on_curve(count, sketch, entity, body, name); + }; + const double spacing = params.value("spacing", 10.0); // linear step (mm) + const int dir = params.value("dir", 0); // 0 = plane X, 1 = plane Y + const double angle = params.value("angle", 360.0); // circular total sweep (deg) + const SketchPlane plane = cad_resolve_plane(params.value("plane", json("XY")), doc, false); + return [&doc, circular = layout == 1, count, spacing, dir, angle, body, plane](const std::string& name) { + const int p = doc.add_pattern(circular, count, spacing, dir, angle, body, name); + doc.features[p].plane = plane; // the circular pattern's axis, the linear one's step directions + return p; + }; +} + +std::function cad_align(CadDocument& doc, const json& params) +{ + for (const char* k : {"cs_a", "cs_b"}) + if (!params.value(k, json()).is_number_integer()) + throw std::runtime_error(std::string("align needs '") + k + "' (CoordSys feature index)"); + const int kind = enum_index("type", params.value("type", json("fastened")), kAlignTypes); + const int cs_a = params.at("cs_a").get(); + const int cs_b = params.at("cs_b").get(); + const double offset = params.value("offset", 0.0); + const double angle = params.value("angle", 0.0); + const bool flip = params.value("flip", false); + return [&doc, kind, cs_a, cs_b, offset, angle, flip](const std::string& name) { + return doc.add_mate(kind, cs_a, cs_b, offset, angle, flip, name); + }; +} + +std::function cad_dressup(CadDocument& doc, const json& params, bool chamfer) +{ + const char* verb = chamfer ? "chamfer" : "fillet"; + const json given = params.value("edges", json()); + // A word names the card's Edges choice, an edge group; anything else is ids. + const std::optional group = face_group_named(given); + if (given.is_string() && !group) throw std::runtime_error("edges must be an edge id, a list of them, or " + kFaceGroupWords); + const std::vector edges = group ? std::vector() : edge_ids_arg(params, verb); + const char* key = chamfer ? "distance" : "radius"; + const double size = params.value(key, 1.0); + if (size <= 0) throw std::runtime_error(std::string(key) + " must be > 0"); + if (doc.bodies.empty()) throw CadPrecondition(std::string("no body to ") + verb); + const int body = target_body_arg(params, doc); + return [&doc, chamfer, group, edges, size, body](const std::string& name) { + const int i = group ? (chamfer ? doc.add_chamfer(size, *group, name) : doc.add_fillet(size, *group, name)) + : (chamfer ? doc.add_chamfer(size, edges, name) : doc.add_fillet(size, edges, name)); + if (body >= 0) doc.features[i].target_body = body; // the edge ids are resolved against this body's shape + return i; + }; +} + +std::function cad_split(CadDocument& doc, const json& params, json& resolved) +{ + auto given = [&](const char* k) { return params.contains(k) && !params.at(k).is_null(); }; + auto flag = [&](const char* k, bool def) { + if (!given(k)) return def; + if (!params.at(k).is_boolean()) throw std::runtime_error(std::string(k) + " must be true or false"); + return params.at(k).get(); + }; + const bool by_plane = given("plane"), by_face = given("face"); + if (by_plane && by_face) throw std::runtime_error("give plane or face, not both"); + if (!by_plane && !by_face) + throw std::runtime_error("split needs plane (\"XY\", \"XZ\", \"YZ\", {\"datum\": i} or {\"body\": b, \"face\": f}) or face (a face id to split along)"); + if (doc.bodies.empty()) throw CadPrecondition("no body to split"); + const int body = target_body_arg(params, doc); + const int t = body >= 0 ? body : int(doc.bodies.size()) - 1; + const bool keep_upper = flag("keep_upper", true), keep_lower = flag("keep_lower", true); + if (!keep_upper && !keep_lower) throw std::runtime_error("keep_upper and keep_lower are both false, so nothing would be kept"); + // The kernel keeps the upper piece in the body's place and puts the lower one after it. + resolved = {{"body", t}}; + if (keep_upper) resolved["upper_body"] = t; + if (keep_lower) resolved["lower_body"] = keep_upper ? t + 1 : t; + + if (by_face) { + for (const char* k : {"offset", "flip"}) + if (given(k)) + throw std::runtime_error(std::string(k) + " goes with plane; to split along a face at an offset, give plane {\"body\": b, \"face\": f}"); + if (!params.at("face").is_number_integer()) throw std::runtime_error("face must be a face id (body_describe)"); + const int face = params.at("face").get(); + const json fbv = params.value("face_body", json(-1)); + if (!fbv.is_number_integer() || fbv.get() < -1 || fbv.get() >= int(doc.bodies.size())) + throw std::runtime_error("face_body must be a body index, or -1 for the body being split"); + const int face_body = fbv.get(); + const int fb = face_body >= 0 ? face_body : t; + if (GeometryEngine::face_by_index(doc.bodies[fb].shape, face).IsNull()) + throw std::runtime_error("face " + std::to_string(face) + " of body " + std::to_string(fb) + " does not exist (it has " + + std::to_string(GeometryEngine::face_count(doc.bodies[fb].shape)) + " faces)"); + return [&doc, body, face_body, face, keep_upper, keep_lower](const std::string& name) { + return doc.add_split_by_face(body, face_body, face, keep_upper, keep_lower, name); + }; + } + if (given("face_body")) throw std::runtime_error("face_body goes with face"); + const SketchPlane plane = cad_resolve_plane(params.at("plane"), doc, false); + const json ov = params.value("offset", json(0.0)); + if (!ov.is_number()) throw std::runtime_error("offset must be a number (mm along the plane's normal)"); + const double offset = ov.get(); + const bool flip = flag("flip", false); + // The plane the kernel cuts along (apply_cut): moved along its normal, then turned over. + SketchPlane cut = plane; + cut.origin += cut.normal * offset; + if (flip) cut.normal = -cut.normal; + // A plane clear of the body would leave one piece empty; the card does not check this. + Bnd_Box box; + BRepBndLib::AddOptimal(doc.bodies[t].shape, box, false, false); + if (!box.IsVoid()) { + double x0, y0, z0, x1, y1, z1; + box.Get(x0, y0, z0, x1, y1, z1); + double lo = 1e300, hi = -1e300; + for (double x : {x0, x1}) + for (double y : {y0, y1}) + for (double z : {z0, z1}) { + const double side = (Vec3d(x, y, z) - cut.origin).dot(cut.normal); + lo = std::min(lo, side); + hi = std::max(hi, side); + } + if (lo >= -1e-6 || hi <= 1e-6) + throw std::runtime_error("the plane misses body " + std::to_string(t) + ": all of it lies on its " + + (lo >= -1e-6 ? "upper" : "lower") + " side, so there is nothing to split"); + } + resolved["frame"] = frame_json(cut); + return [&doc, plane, offset, flip, keep_upper, keep_lower, body](const std::string& name) { + return doc.add_cut(plane, offset, flip, keep_upper, keep_lower, body, name); + }; +} + +void solid_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"extrude", action_extrude}, + {"revolve", action_revolve}, + {"fillet", action_fillet}, + {"chamfer", action_chamfer}, + {"hole", action_hole}, + {"boolean", action_boolean}, + {"pattern", action_pattern}, + {"shell", action_shell}, + {"rib", action_rib}, + {"draft", action_draft}, + {"mirror", action_mirror}, + {"thicken", action_thicken}, + {"split", action_split}, + {"thread", action_thread}, + {"sweep", action_sweep}, + {"loft", action_loft}, + {"delete_face", action_delete_face}, + {"align", action_align}, + {"list_align_types", action_list_align_types}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp new file mode 100644 index 0000000000..f9a31813fa --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp @@ -0,0 +1,126 @@ +// The place Design, its Surface heading: surface_extrude, surface_revolve, surface_loft, surface_patch and +// surface_offset, which make surface bodies (the Solid heading's thicken makes a solid of one). surface_silent_forms() +// binds them to their tool blocks, and run_design_tool() (DesignTools.cpp) runs them behind the Design commands' gate. + +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" + +#include "libslic3r/CAD/CadDocument.hpp" + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +json action_surface_extrude(DesignPanel* panel, const json& params) +{ + if (!params.contains("sketch")) throw std::runtime_error("surface_extrude needs 'sketch' (feature index)"); + CadDocument& doc = panel->mcp_doc(); + int sketch = params["sketch"].get(); + double distance = params.value("distance", 10.0); + doc.checkpoint(); + int idx = doc.add_surface_extrude(sketch, distance, panel->mcp_feature_name(_L("Surface Extrude"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_surface_revolve(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const auto add = cad_surface_revolve(doc, params); + doc.checkpoint(); + int idx = add(panel->mcp_feature_name(_L("Surface Revolve"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_surface_offset(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("no sheet body to offset"); + int bi = target_body_arg(params, doc); + double offset = params.value("offset", 1.0); + doc.checkpoint(); + int idx = doc.add_surface_offset(bi, offset, panel->mcp_feature_name(_L("Surface Offset"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_surface_loft(DesignPanel* panel, const json& params) +{ + if (!params.contains("profiles") || !params["profiles"].is_array()) + throw std::runtime_error("surface_loft needs 'profiles' (array of int feature indices)"); + CadDocument& doc = panel->mcp_doc(); + std::vector profiles; + for (const json& j : params["profiles"]) profiles.push_back(j.get()); + bool ruled = params.value("ruled", false); + doc.checkpoint(); + int idx = doc.add_surface_loft(profiles, ruled, panel->mcp_feature_name(_L("Surface Loft"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +json action_surface_patch(DesignPanel* panel, const json& params) +{ + if (!params.contains("sketch")) throw std::runtime_error("surface_patch needs 'sketch' (feature index)"); + CadDocument& doc = panel->mcp_doc(); + int sketch = params["sketch"].get(); + doc.checkpoint(); + int idx = doc.add_surface_fill(sketch, panel->mcp_feature_name(_L("Surface Fill"))); + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"feature_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +} // namespace + +std::function cad_surface_revolve(CadDocument& doc, const json& params) +{ + const int si = sketch_arg(params.value("sketch", json()), doc); + const double angle = params.value("angle", 360.0); + const int axis = revolve_axis_arg(params); + const bool flip = params.value("flip", false); + const int axis_entity = revolve_axis_entity_arg(params, doc, si); + return [&doc, si, angle, axis, flip, axis_entity](const std::string& name) { + const int r = doc.add_surface_revolve(si, angle, axis, name); + doc.features[r].flip = flip; + doc.features[r].revolve_axis_entity = axis_entity; + return r; + }; +} + +void surface_silent_forms(std::vector& forms) +{ + forms.insert(forms.end(), { + {"surface_extrude", action_surface_extrude}, + {"surface_revolve", action_surface_revolve}, + {"surface_loft", action_surface_loft}, + {"surface_patch", action_surface_patch}, + {"surface_offset", action_surface_offset}, + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/DesignTools.cpp b/src/slic3r/GUI/Mcp/Tools/DesignTools.cpp new file mode 100644 index 0000000000..5c9845e73e --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/DesignTools.cpp @@ -0,0 +1,1287 @@ +// The place Design, the Design tab's commands, and its Document heading: describe_design, select_geometry, confirm_tool +// and cancel_tool, what the tab shows and has open; import_step and import_mesh; set_variable; and commit_to_plate, +// new_design and export_step. The Design table (kDesignTools, generated from scripts/CAD/tool_atlas.json) declares +// every command, its menu item, handler, access, tool block and the items folded into it; silent_forms() binds each +// block to the function that runs it, which is in the file of its heading (DesignSketchTools.cpp for Sketch, +// DesignSolidTools.cpp for Solid and so on). register_design_tools() makes a command of each entry that is one +// (is_design_command()): a call with the arguments that choose one of its items does what that menu item does +// (opened_item(), open_tool()), and any other has run_design_tool() run its silent form on the UI thread, through the +// GUI's own CadDocument and DesignPanel's mcp_* hooks, behind the Design tab's busy and stale-id checks +// (design_gate()). The helpers the other headings' files share are here too, declared in DesignCommon.hpp. + +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "slic3r/GUI/Mcp/Tools/DesignCommon.hpp" +#include "libslic3r/Point.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include // OCCT base error + +#include "slic3r/GUI/GUI.hpp" // into_u8 +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" // itObject +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" // gizmo_name: the name app_state reports +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignSketchTool.hpp" +#include "slic3r/GUI/CAD/DesignOffer.hpp" // the Design table: every command's menu item, handler and tool block + +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Color.hpp" +#include "libslic3r/Format/OBJ.hpp" +#include "libslic3r_version.h" +#include +#include +#include +#include "libslic3r/BoundingBox.hpp" + +#include + +using json = nlohmann::json; + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +// ---- What the commands' descriptions and schemas add to the Design table ------------------------ + +// The `generation` property of every Design command with a silent form: how face and edge ids expire, and +// how a call keeps from acting on a stale one. +const char* const kGenerationNote = + "The generation (describe_design, body_describe) the face and edge ids this call passes were read at. Ids " + "expire when a feature rebuilds the model, and a stale id still names a real face or edge: with the " + "generation, a call whose ids were read before the model changed is refused."; + +// How a silent form whose entry has ok_false reports a rebuild the kernel rejects. +const char* const kFailureNote = "A rejected rebuild is reported in the reply: ok is false or error is not empty."; + +// The rest of the description of a command whose entry has a handler and no silent form, after its hint and +// before mode_note(). +const char* const kOpensToolNote = + "It takes no arguments and does what the Design tab's right-click menu item does, as a person's pick does: open " + "a tool, start a sketch tool, act at once, or tell the person why it cannot. The reply's status is what the " + "tab's status line shows then."; + +// The `silent` property of a command whose call with no arguments opens a tool, before mode_note() of that tool's +// item. +const char* const kSilentNote = + "true runs the tool with the other arguments and opens nothing. A call with no arguments does what the Design " + "tab's menu item does, as a person's pick does."; + +// The mode an entry with a handler runs in, as the Design tab's right-click menu offers it (offered_in_mode()). +// A sketch being constrained counts as open, and refuses sketch_finish and sketch_cancel: the tab's own Confirm +// and Cancel buttons end it. A call that takes no arguments runs only there; `no_arguments` words it for the call +// with no arguments of a command that also runs from arguments, whose argument form may run in the other mode +// (sketch_text, sketch_project). +std::string mode_note(const DesignTool& t, bool no_arguments = false) +{ + return std::string(no_arguments ? "Called with no arguments, it runs only " : "It runs only ") + + (t.sketch_mode ? "in an open sketch (sketch_create opens one)." + : "outside a sketch (sketch_finish or sketch_cancel ends one; while the tab constrains a sketch, " + "its Confirm or Cancel button ends that)."); +} + +// cad_note()'s text, given while the feature is off and while it is on but was off at startup. The +// catalog holds the Design commands only when the feature was on at startup (the preference, or the command +// line's --cad), and the main window creates the Design page only then too (its panel is built on first use), +// so turning the feature on takes a restart. +const char* const kCadOffNote = "tool_call runs no Design command now: they need the CAD feature on when OrcaSlicer " + "started, in Preferences > Features or with --cad. A person turns it on there if it is " + "off and restarts OrcaSlicer, or starts it with --cad."; + +// Why a catalog built without the Design commands leaves them out, after "Unknown tool: ; " or an action's +// " is a Design tab action, and " (unknown_action()): in the editor the CAD feature was off at startup; the +// G-code viewer has no Design tab whatever the preference says. +const char* const kCadOffAtStartup = "the CAD feature was off when OrcaSlicer started: a person turns it on in " + "Preferences > Features and restarts OrcaSlicer, or starts it with --cad"; +const char* const kNoDesignInViewer = "the G-code viewer has no Design tab: a person opens the project in OrcaSlicer's editor"; +// design_gate()'s refusal while the CAD feature is off in a run that started with it on. +const char* const kCadOffNow = "The CAD feature is off; enable it in Preferences > Features and restart OrcaSlicer"; + +// The details of a ToolFailure a silent form passes on, with invalid_argument as their code where they name no cause, +// as a plain exception a silent form throws reads (run_guarded(), add_feature()). +json with_code(json details) +{ + if (!details.is_object()) + details = json::object(); + if (!details.contains("code")) + details["code"] = "invalid_argument"; + return details; +} + +} // namespace + +// ---- Shared with the other Design files (DesignCommon.hpp) -------------------------------------- + +const char* feature_type_name(CadFeatureType t) +{ + switch (t) { + case CadFeatureType::Sketch: return "Sketch"; + case CadFeatureType::Extrude: return "Extrude"; + case CadFeatureType::Fillet: return "Fillet"; + case CadFeatureType::Chamfer: return "Chamfer"; + case CadFeatureType::Hole: return "Hole"; + case CadFeatureType::Thread: return "Thread"; + case CadFeatureType::Shell: return "Shell"; + case CadFeatureType::Revolve: return "Revolve"; + case CadFeatureType::Sweep: return "Sweep"; + case CadFeatureType::Pattern: return "Pattern"; + case CadFeatureType::Plane: return "Plane"; + case CadFeatureType::Loft: return "Loft"; + case CadFeatureType::Draft: return "Draft"; + case CadFeatureType::Import: return "Import"; + case CadFeatureType::Boolean: return "Boolean"; + case CadFeatureType::Cut: return "Cut"; + case CadFeatureType::Mirror: return "Mirror"; + case CadFeatureType::Axis: return "Axis"; + case CadFeatureType::CoordSys: return "CoordSys"; + case CadFeatureType::Helix: return "Helix"; + case CadFeatureType::Transform: return "Transform"; + case CadFeatureType::Thicken: return "Thicken"; + case CadFeatureType::Project: return "Project"; + case CadFeatureType::DeleteFace: return "DeleteFace"; + case CadFeatureType::Rib: return "Rib"; + case CadFeatureType::SurfaceExtrude: return "SurfaceExtrude"; + case CadFeatureType::SurfaceRevolve: return "SurfaceRevolve"; + case CadFeatureType::ThickenSurface: return "ThickenSurface"; + case CadFeatureType::SurfaceOffset: return "SurfaceOffset"; + case CadFeatureType::SurfaceLoft: return "SurfaceLoft"; + case CadFeatureType::SurfaceFill: return "SurfaceFill"; + case CadFeatureType::Mate: return "Mate"; + } + return "Unknown"; +} + +json placement_json(const DesignPanel& panel, int b) +{ + const Transform3d t = panel.mcp_body_placement(b); + if (t.isApprox(Transform3d::Identity())) return json(); + json rows = json::array(); + for (int r = 0; r < 3; ++r) + rows.push_back(json::array({t(r, 0), t(r, 1), t(r, 2), t(r, 3)})); + return rows; +} + +json frame_json(const SketchPlane& p) +{ + return json{{"origin", vec3(p.origin)}, {"normal", vec3(p.normal)}, + {"x_axis", vec3(p.x_axis)}, {"y_axis", vec3(p.y_axis)}}; +} + +json plane_json(const SketchPlane& p, const Vec3d& modeling_origin) +{ + json j = frame_json(p); + const std::pair bases[] = {{"XY", SketchPlane::XY()}, {"XZ", SketchPlane::XZ()}, {"YZ", SketchPlane::YZ()}}; + for (const auto& [name, b] : bases) + if ((p.normal - b.normal).norm() < 1e-9 && (p.x_axis - b.x_axis).norm() < 1e-9 && + (p.y_axis - b.y_axis).norm() < 1e-9 && std::abs((p.origin - modeling_origin).dot(b.normal)) < 1e-6) + j["base"] = name; + return j; +} + +json add_feature(DesignPanel* panel, const char* index_key, const std::function& add, bool slow) +{ + CadDocument& doc = panel->mcp_doc(); + doc.checkpoint(); + int idx = -1; + std::string why; + json details = {{"code", "rebuild_failed"}}; + try { + idx = add(); + if (!(slow ? panel->recompute_guarded(_L("Rebuilding model…")) : doc.recompute())) + why = doc.error.empty() ? "the model could not be rebuilt" : doc.error; + } catch (const ToolFailure& ex) { // a refusal with its own code, such as no_design_view() + why = ex.what(); + details = with_code(ex.details); + } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it + why = std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"); + details = {{"code", "kernel_failure"}}; + } catch (const CadKernelFailure& ex) { + why = std::string("OCCT: ") + ex.what(); + details = {{"code", "kernel_failure"}}; + } catch (const CadPrecondition& ex) { + why = ex.what(); + details = {{"code", "precondition"}}; + } catch (const std::exception& ex) { + why = *ex.what() ? ex.what() : "the feature could not be added"; + details = {{"code", "invalid_argument"}}; + } + if (!why.empty()) { + doc.rollback(); + doc.error = why; // the rollback's rebuild cleared it; the status line reads it + panel->mcp_after_change(false); + throw ToolFailure(why, std::move(details)); + } + panel->mcp_after_change(); + return json{{"ok", true}, {index_key, idx}, {"bodies", int(doc.bodies.size())}}; +} + +std::string input_path(const json& value, const std::string& what) +{ + if (!value.is_string()) throw std::runtime_error(what + " must be an absolute path"); + std::string err; + const auto path = Mcp::resolve_input_path(value.get(), err); + if (!path) throw std::runtime_error(err); + return Mcp::path_to_utf8(*path); +} + +void check_feature_index(int fi, const CadDocument& doc) +{ + if (fi < 0 || fi >= int(doc.features.size())) + throw std::runtime_error("feature " + std::to_string(fi) + " is out of range; the design has " + + std::to_string(doc.features.size()) + " features"); +} + +json param(const json& params, const char* key) +{ + return params.is_object() ? params.value(key, json()) : json(); +} + +namespace { + +// What describe_design and select_geometry say is selected. The selection: what the right-click menu would be built +// for, its kind (an OfferSel) and its id in the atlas, which the entries' accepts name. +json selection_json(const DesignPanel& panel) +{ + const int kind = panel.mcp_offer_selection_kind(); + return json{{"kind", kind}, {"id", kDesignSelectionIds[kind]}}; +} + +// The reference plane picked in the view, which the next Sketch opens on: "XY", "XZ", "YZ" or null. +json picked_plane_json(const DesignPanel& panel) +{ + static const char* const names[] = {"XY", "XZ", "YZ"}; + const int plane = panel.mcp_picked_plane(); + return plane >= 0 ? json(names[plane]) : json(); +} + +// The selected row of the Feature list, a feature index, which the menu items that act on it take while nothing is picked +// in the view; or null. +json feature_row_json(const DesignPanel& panel) +{ + const int row = panel.mcp_feature_row(); + return row >= 0 ? json(row) : json(); +} + +json describe_design(DesignPanel* panel) +{ + CadDocument& doc = panel->mcp_doc(); + + json features = json::array(); + for (size_t i = 0; i < doc.features.size(); ++i) { + const CadFeature& f = doc.features[i]; + json jf{{"index", int(i)}, {"type", feature_type_name(f.type)}, {"name", f.name}, {"suppressed", !f.enabled}}; + // The fields an expression drives: feature_edit refuses them, feature_describe has the expressions. + if (!f.expr.empty()) { + json bound = json::array(); + for (const auto& kv : f.expr) bound.push_back(kv.first); + jf["bound"] = std::move(bound); + } + features.push_back(std::move(jf)); + } + + // A variable that does not evaluate leaves every value null; the error says why. + std::string var_error; + const std::map values = doc.variable_values(var_error); + json variables = json::array(); + for (const auto& [name, expr] : doc.variables) { + const auto v = values.find(name); + variables.push_back(json{{"name", name}, {"expr", expr}, {"value", v != values.end() ? json(v->second) : json()}}); + } + + const DesignCanvas* vp = panel->mcp_viewport(); + json bodies = json::array(); + for (size_t i = 0; i < doc.bodies.size(); ++i) { + // The user's name when the body has one, the derived maker name otherwise — the same + // rule the Bodies row shows, so a driver and a person read the same thing. + json b{{"index", int(i)}, + {"name", doc.bodies[i].has_user_name ? doc.bodies[i].user_name : doc.bodies[i].name}, + {"user_name", doc.bodies[i].has_user_name}, + {"has_color", doc.bodies[i].has_color}, + {"source_feature", doc.bodies[i].source_feature}, + {"visible", panel->mcp_body_shown(int(i))}, + // Where it stands (body_place, the Move gizmo, Place on Face), which bbox, the recipe's body, does not + // include. + {"moved", panel->mcp_body_moved(int(i))}, + {"placement", placement_json(*panel, int(i))}}; + // The colour the canvas draws: the override when has_color, else the automatic one. + if (vp != nullptr) b["color"] = encode_color(vp->body_color(int(i))); + // Per-body bbox/centre from the already-tessellated display meshes. + if (i < doc.display_body_meshes.size() && !doc.display_body_meshes[i].empty()) { + BoundingBoxf3 bb = doc.display_body_meshes[i].bounding_box(); + b["bbox"] = json{{"min", {bb.min.x(), bb.min.y(), bb.min.z()}}, + {"max", {bb.max.x(), bb.max.y(), bb.max.z()}}}; + Vec3d c = bb.center(); + b["center"] = {c.x(), c.y(), c.z()}; + } + bodies.push_back(std::move(b)); + } + + json out{ + {"modeling_origin", {doc.modeling_origin.x(), doc.modeling_origin.y(), doc.modeling_origin.z()}}, + {"features", std::move(features)}, + {"variables", std::move(variables)}, + {"bodies", std::move(bodies)}, + {"error", doc.error}, + // Pass this back as "generation" on any call that takes a face or edge id and the call + // is refused if the topology has moved on. See the stale-id guard in design_gate(). + {"generation", doc.topo_generation}, + {"undo_depth", doc.undo_depth()}, + {"redo_depth", doc.redo_depth()}, + // Whether sketch endpoints that nearly meet are welded: the document's rule, which changes + // the loops sketch_draw's entities make. + {"auto_close_loops", doc.auto_close_loops}, + }; + out["selection"] = selection_json(*panel); + out["picked_plane"] = picked_plane_json(*panel); + out["feature_row"] = feature_row_json(*panel); + // The Commit button's mode, which commit_to_plate uses when given none. + out["commit_mode"] = panel->commit_mode() == DesignPanel::CommitMode::Bodies ? "bodies" : "assembly"; + if (!var_error.empty()) out["variables_error"] = var_error; + // The aligns (Mate features) that cannot hold with those before them. + if (!doc.mate_conflicts.empty()) { + json conflicts = json::array(); + for (const auto& [feature, reason] : doc.mate_conflicts) + conflicts.push_back(json{{"feature", feature}, {"reason", reason}}); + out["align_conflicts"] = std::move(conflicts); + } + return out; +} + +// ---- Build: bring a reference part in (Import STEP as native B-rep bodies) ---------------------- +json import_step(DesignPanel* panel, const json& params) +{ + if (!params.contains("path")) throw std::runtime_error("import_step needs 'path'"); + const std::string path = input_path(params["path"], "path"); + std::string err; + std::vector solids = GeometryEngine::read_step_solids(path, err); + if (solids.empty()) throw std::runtime_error(err.empty() ? "no solids in STEP" : err); + + CadDocument& doc = panel->mcp_doc(); + doc.checkpoint(); + int first = int(doc.features.size()); + for (const TopoDS_Shape& s : solids) { + CadFeature f; + f.type = CadFeatureType::Import; + f.name = panel->mcp_feature_name("STEP"); + f.imported_solid = s; + f.mode = BooleanMode::New; // each solid = its own coexisting body + doc.features.push_back(f); + } + bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"imported", int(solids.size())}, {"first_feature", first}, + {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; +} + +// ---- Import a triangle mesh as a B-rep body (GeometryEngine::mesh_to_brep) ---------------------- +// Same destination as import_step: a CadFeatureType::Import body every feature tool can edit. +// The full conversion stats come back so a caller can tell an honest solid from an open shell +// instead of discovering it later when a boolean silently fails. +json import_mesh(DesignPanel* panel, const json& params) +{ + if (!params.contains("path")) throw std::runtime_error("import_mesh needs 'path'"); + const std::string path = input_path(params["path"], "path"); + const double tolerance = params.value("tolerance", 0.01); + const double merge_angle_deg = params.value("merge_angle_deg", 5.0); + + TriangleMesh mesh; + const std::string ext = boost::algorithm::to_lower_copy( + boost::filesystem::path(path).extension().string()); + if (ext == ".stl") { + if (!mesh.ReadSTLFile(path.c_str())) throw std::runtime_error("could not read STL: " + path); + } else if (ext == ".obj") { + ObjInfo obj_info; std::string obj_err; + if (!load_obj(path.c_str(), &mesh, obj_info, obj_err)) + throw std::runtime_error("could not read OBJ: " + obj_err); + } else { + throw std::runtime_error("unsupported mesh format (want .stl or .obj): " + ext); + } + + GeometryEngine::MeshBrepStats st; + const TopoDS_Shape shape = GeometryEngine::mesh_to_brep(mesh.its, tolerance, merge_angle_deg, st); + if (shape.IsNull()) throw std::runtime_error("mesh conversion produced no geometry"); + + CadDocument& doc = panel->mcp_doc(); + doc.checkpoint(); + const int first = int(doc.features.size()); + CadFeature f; + f.type = CadFeatureType::Import; + f.name = panel->mcp_feature_name(_L("Mesh")); + f.imported_solid = shape; + f.mode = BooleanMode::New; + doc.features.push_back(f); + + const bool ok = doc.recompute(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"first_feature", first}, {"bodies", int(doc.bodies.size())}, + {"input_triangles", st.input_tris}, {"kept_triangles", st.kept_tris}, + {"degenerate_collapsed", st.degenerate_collapsed}, + {"degenerate_sliver", st.degenerate_sliver}, + {"faces_built", st.faces_built}, {"faces_failed", st.faces_failed}, + {"faces_final", st.faces_final}, {"unique_edges", st.unique_edges}, + {"boundary_edges", st.boundary_edges}, + {"nonmanifold_edges", st.nonmanifold_edges}, + {"watertight", st.watertight}, {"is_solid", st.is_solid}, + {"volume", st.volume}, {"error", doc.error}}; +} + +json action_set_variable(DesignPanel* panel, const json& params) +{ + if (!params.contains("name")) throw std::runtime_error("set_variable needs 'name'"); + if (!params.contains("expr")) throw std::runtime_error("set_variable needs 'expr'"); + CadDocument& doc = panel->mcp_doc(); + const std::string name = params["name"].get(); + const std::string expr = params["expr"].get(); + if (name.empty()) throw std::runtime_error("set_variable needs a non-empty 'name'"); + // An empty expression removes the variable, as Remove in the Variables list does. + const bool remove = expr.empty(); + if (remove && doc.variables.count(name) == 0) + throw std::runtime_error("there is no variable '" + name + "'"); + doc.checkpoint(); + if (remove) + doc.variables.erase(name); + else + doc.variables[name] = expr; + const bool ok = doc.recompute(); + if (!ok) { + // rollback() rebuilds, which succeeds and clears doc.error; the reply and the status line + // need the reason. A removal fails because a binding still names the variable, as the + // GUI's Remove says. + const std::string why = doc.error; + doc.rollback(); + doc.error = remove ? std::string(wxString::Format(_L("Variable '%s' could not be removed (likely still referenced " + "by a feature expression): %s"), + wxString::FromUTF8(name), wxString::FromUTF8(why)).ToUTF8().data()) + : why; + } + panel->mcp_after_change(ok); + json r{{"ok", ok}, {"name", name}, {"error", doc.error}}; + if (remove) r["removed"] = ok; + return r; +} + +// Edit > Undo / Redo with the Design tab shown: the Design history, or inside a sketch session the +// sketch's own, which takes off or puts back the last drawn shape. The project's history is undo's +// with history "project". +json undo_redo(DesignPanel* panel, bool redo) +{ + DesignCanvas* vp = panel->mcp_viewport(); + const bool sketch = vp != nullptr && vp->is_sketching(); + if (!panel->menu_can_undo_redo(redo)) { + if (sketch) throw CadPrecondition(redo ? "Nothing to redo in the open sketch" : "Nothing to undo in the open sketch"); + throw CadPrecondition(redo ? "Nothing to redo in the Design history (history \"project\" redoes the project's)" + : "Nothing to undo in the Design history (history \"project\" undoes the project's)"); + } + panel->menu_undo_redo(redo); + if (sketch) return json{{"scope", "sketch"}, {"entities", vp->mcp_sketch_tool().entities().size()}}; + const CadDocument& doc = panel->mcp_doc(); + return json{{"scope", "design"}, + {"undo_depth", doc.undo_depth()}, + {"redo_depth", doc.redo_depth()}, + {"features", doc.features.size()}, + {"bodies", doc.bodies.size()}, + {"generation", doc.topo_generation}}; +} + +// ---- Hand-off: Commit to Plate, New Design, Export STEP ----------------------------------------- + +// Commit to Plate as the split button does, in `mode` (by default the button's, which this leaves +// alone), then delete the `replace` objects. With `replace` the deletions and the commit are one +// Prepare undo step: the commit's own snapshot is suppressed under the outer one. +json action_commit_to_plate(DesignPanel* panel, const json& params) +{ + using Mode = DesignPanel::CommitMode; + Mode mode = panel->commit_mode(); + const json m = params.value("mode", json("")); + if (m == "assembly") mode = Mode::Assembly; + else if (m == "bodies") mode = Mode::Bodies; + else if (m != "") throw std::runtime_error("mode must be \"assembly\" or \"bodies\""); + + Plater* plater = wxGetApp().plater(); + ObjectList* obj_list = wxGetApp().obj_list(); + if (plater == nullptr || obj_list == nullptr) throw CadPrecondition("Prepare is not ready"); + Model& model = plater->model(); + const std::vector replace = cad_commit_to_plate_replace(params.value("replace", json::array()), model); + // The Delete key does not pull an object from under an open gizmo either. + if (!replace.empty()) + for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_assmeble_canvas3D()}) + if (canvas != nullptr && canvas->get_gizmos_manager().get_current_type() != GLGizmosManager::Undefined) + throw CadPrecondition("close the " + Mcp::gizmo_name(canvas->get_gizmos_manager().get_current_type()) + + " gizmo first: replace deletes objects"); + + // commit_to_plate()'s own refusals, checked first so a refused call leaves no undo step. + const CadDocument& doc = panel->mcp_doc(); + if (doc.display_mesh.its.indices.empty()) + throw CadPrecondition("Nothing to commit: the design has no body; add a feature first"); + bool any_shown = doc.display_body_meshes.size() <= 1; // a lone body is sent even when hidden + for (size_t b = 0; !any_shown && b < doc.display_body_meshes.size(); ++b) + any_shown = panel->mcp_body_shown(int(b)) && !doc.display_body_meshes[b].its.indices.empty(); + if (!any_shown) throw CadPrecondition("Every body is hidden; show one first with body_set {body, visible: true}"); + + json replaced = json::array(); + for (int i : replace) replaced.push_back(json{{"index", i}, {"name", model.objects[i]->name}}); + + std::vector sent; + std::vector made; + { + std::optional snapshot; + if (!replace.empty()) snapshot.emplace(plater, _u8L("Commit to Plate")); + for (size_t i : panel->commit_to_plate(mode, &sent)) made.push_back(model.objects[i]); + if (made.empty()) throw CadPrecondition("Commit to Plate sent nothing"); + std::vector items; + for (int i : replace) items.emplace_back(itObject, i, -1); + obj_list->delete_from_model_and_list(items); + } + + // The new objects' indices once the replaced ones are gone. + json objects = json::array(); + for (const ModelObject* o : made) { + const auto it = std::find(model.objects.begin(), model.objects.end(), o); + objects.push_back(json{{"index", int(it - model.objects.begin())}, {"object_id", o->id().id}, {"name", o->name}, + {"parts", o->volumes.size()}}); + } + json hidden = json::array(); + for (int b = 0; b < int(doc.bodies.size()); ++b) + if (std::find(sent.begin(), sent.end(), b) == sent.end() && !panel->mcp_body_shown(b)) hidden.push_back(b); + return json{{"ok", true}, {"mode", mode == Mode::Bodies ? "bodies" : "assembly"}, {"objects", std::move(objects)}, + {"bodies_sent", sent}, {"bodies_hidden", std::move(hidden)}, {"replaced", std::move(replaced)}, + {"tab", "prepare"}}; +} + +// New Design without its confirmation dialog: discard_changes confirms, as project_new's does. +json action_new_design(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const json discard = params.value("discard_changes", json(false)); + if (!discard.is_boolean()) throw std::runtime_error("discard_changes must be true or false"); + const json cleared = {{"features", doc.features.size()}, {"bodies", doc.bodies.size()}, {"variables", doc.variables.size()}}; + if (!discard.get() && !(doc.features.empty() && doc.bodies.empty() && doc.variables.empty())) + throw std::runtime_error("The design is not empty (" + cleared.dump() + + "); pass discard_changes: true to erase it. This also clears the Design undo history; " + "committed objects stay on the plate."); + panel->clear_document(); + return json{{"ok", true}, {"cleared", cleared}}; +} + +// Export STEP… to a path instead of its file dialog, with the server's output-path rules. +json action_export_step(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + if (doc.bodies.empty()) throw CadPrecondition("Nothing to export: the design has no body; add a feature first"); + const json path_arg = params.value("path", json()); + const json overwrite = params.value("overwrite", json(false)); + if (!path_arg.is_string()) throw std::runtime_error("export_step needs 'path', an absolute file path"); + if (!overwrite.is_boolean()) throw std::runtime_error("overwrite must be true or false"); + std::string err; + const auto path = Mcp::resolve_output_path(path_arg.get(), overwrite.get(), err); + if (!path) throw std::runtime_error(err); + const std::string path_utf8 = Mcp::path_to_utf8(*path); + if (!panel->export_step_to(path_utf8, err)) throw ToolFailure("STEP export failed: " + err, {{"code", "export_failed"}}); + + boost::system::error_code ec; + const auto bytes = boost::filesystem::file_size(*path, ec); + json moved = json::array(); + for (int b = 0; b < int(doc.bodies.size()); ++b) + if (panel->mcp_body_moved(b)) moved.push_back(b); + return json{{"ok", true}, {"path", path_utf8}, {"bytes", ec ? 0 : bytes}, {"bodies", doc.bodies.size()}, + {"moved_bodies", std::move(moved)}}; +} + +// select_geometry: what a click selects in the model at rest, by id (DesignPanel::mcp_select()). An argument given as +// null is left out, as its null default says. The reply is what describe_design reports of the selection. +json action_select_geometry(DesignPanel* panel, const json& params) +{ + using Kind = DesignSelection::Kind; + std::set named; + for (const char* key : {"body", "face", "edges", "vertex", "plane", "sketch", "loop", "feature"}) + if (!param(params, key).is_null()) named.insert(key); + const auto is_form = [&named](std::initializer_list form) { + return named == std::set(form.begin(), form.end()); + }; + const auto index = [¶ms](const char* key) { return params.at(key).get(); }; + DesignSelection s; + if (named.empty()) { + s.kind = Kind::None; + } else if (is_form({"body"})) { + s.kind = Kind::Body; + } else if (is_form({"body", "face"})) { + s.kind = Kind::Face; + s.face = index("face"); + } else if (is_form({"body", "edges"})) { + s.kind = Kind::Edges; + for (const json& e : params.at("edges")) { + if (!e.is_number_integer()) throw std::runtime_error("edges is a list of edge ids"); + s.edges.push_back(e.get()); + } + } else if (is_form({"body", "vertex"})) { + s.kind = Kind::Vertex; + s.vertex = index("vertex"); + } else if (is_form({"plane"})) { + const std::string plane = params.at("plane").get(); + s.kind = Kind::Plane; + s.plane = plane == "XY" ? 0 : plane == "XZ" ? 1 : plane == "YZ" ? 2 : -1; + } else if (is_form({"sketch", "loop"})) { + s.kind = Kind::Loop; + s.sketch = index("sketch"); + s.loop = index("loop"); + } else if (is_form({"feature"})) { + s.kind = Kind::Feature; + s.feature = index("feature"); + } else { + throw std::runtime_error("select_geometry takes one of: body; body with face, edges or vertex; plane; sketch with " + "loop; feature; or nothing, which clears the selection"); + } + if (named.count("body") != 0) s.body = index("body"); + std::string why; + if (!panel->mcp_select(s, why)) throw std::runtime_error(why); + json r{{"ok", true}, + {"selection", selection_json(*panel)}, + {"plane", picked_plane_json(*panel)}, + {"feature", feature_row_json(*panel)}}; + if (s.kind == Kind::Vertex) { + r["point"] = vec3(cad_body_vertices(panel->mcp_doc(), s.body).at(size_t(s.vertex))); + r["placed_point"] = vec3(panel->mcp_viewport()->selected_vertex_point()); + } + return r; +} + +// The tab's Confirm on what is open, as Enter presses it, or the Text dialog's OK. +json action_confirm_tool(DesignPanel* panel, const json&) +{ + DesignPanel::ConfirmOutcome out; + std::string why; + if (!panel->mcp_confirm_tool(out, why)) throw CadPrecondition(why); + return json{{"was", out.was}, + {"ok", out.ok}, + {"feature", out.feature >= 0 ? json(out.feature) : json()}, + {"open", out.open.empty() ? json() : json(out.open)}, + {"status", into_u8(panel->mcp_status())}}; +} + +// The tab's Cancel on what is open, with no dialog, or the Text dialog's Cancel. +json action_cancel_tool(DesignPanel* panel, const json&) +{ + std::string was, why; + if (!panel->mcp_cancel_tool(was, why)) throw CadPrecondition(why); + return json{{"was", was}, {"status", into_u8(panel->mcp_status())}}; +} + +} // namespace + +// Every silent form, by the id of the Design table's entry whose tool block describes it: run_design_tool() and +// register_design_tools() read these, and the block gives its access. The Document heading's are here, the other +// headings' beside their functions. +const std::vector& silent_forms() +{ + static const std::vector forms = [] { + std::vector all = { + {"describe_design", [](DesignPanel* panel, const json&) { return describe_design(panel); }}, + {"select_geometry", action_select_geometry}, + {"confirm_tool", action_confirm_tool}, + {"cancel_tool", action_cancel_tool}, + {"import_step", import_step}, + {"import_mesh", import_mesh}, + {"set_variable", action_set_variable}, + {"commit_to_plate", action_commit_to_plate}, + {"new_design", action_new_design}, + {"export_step", action_export_step}, + }; + sketch_silent_forms(all); + solid_silent_forms(all); + surface_silent_forms(all); + construct_silent_forms(all); + inspect_silent_forms(all); + body_silent_forms(all); + history_silent_forms(all); + return all; + }(); + return forms; +} + +json run_guarded(const std::function& run) +{ + try { + return run(); + } catch (const ToolFailure& ex) { + // Its own refusal, code included; one that names no cause is read as a plain exception is. + if (ex.details.is_object() && ex.details.contains("code")) + throw; + throw ToolFailure(ex.what(), with_code(ex.details)); + } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes before it + throw ToolFailure(std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"), {{"code", "kernel_failure"}}); + } catch (const CadKernelFailure& ex) { + throw ToolFailure(std::string("OCCT: ") + ex.what(), {{"code", "kernel_failure"}}); + } catch (const CadPrecondition& ex) { + throw ToolFailure(ex.what(), {{"code", "precondition"}}); + } catch (const std::exception& ex) { + throw ToolFailure(ex.what(), {{"code", "invalid_argument"}}); + } +} + +ToolFailure no_design_tab() +{ + if (!wxGetApp().is_editor()) + return ToolFailure("The G-code viewer has no Design tab", {{"code", "design_unavailable"}}); + if (!wxGetApp().is_enable_cad_feature()) + return ToolFailure(kCadOffNow, {{"code", "design_unavailable"}}); + return ToolFailure("The Design tab isn't available in this window yet; retry, and if it stays unavailable restart " + "OrcaSlicer (turning the CAD feature on takes effect after a restart)", + {{"code", "design_unavailable"}}); +} + +ToolFailure no_design_view() +{ + return ToolFailure("The Design view is not built in this window; restart OrcaSlicer if it stays so", + {{"code", "design_unavailable"}}); +} + +ToolFailure design_busy(const std::string& why) +{ + return ToolFailure("Design tab busy: " + why, + {{"code", "design_busy"}, + {"hint", "confirm_tool keeps what is open when its Confirm is on (a card, the Text dialog, a body Move, " + "a sketch, Constrain mode) and cancel_tool discards it; a rebuild ends by itself, so call " + "again after it"}}); +} + +std::optional design_generation(const json& args) +{ + if (!args.is_object() || !args.contains("generation")) + return std::nullopt; + // The numbers the schema's integer type takes (is_whole_number(): a whole float within int64 among them), not + // negative. + const json& g = args["generation"]; + if (!is_whole_number(g) || (!g.is_number_unsigned() && g.get() < 0)) + throw ToolFailure("generation must be an integer of 0 or more, as describe_design or body_describe gave it", + {{"code", "invalid_argument"}}); + return g.is_number_float() ? std::uint64_t(g.get()) : g.get(); +} + +namespace { + +// The checks every Design command passes before its function, in this order: the main window is up (not +// shutting down or still starting), the app is the editor and not the G-code viewer (design_unavailable), +// the CAD feature is on, and the Design panel can be built (design_unavailable for each); then the busy rules of +// `access` (design_busy, with a hint naming confirm_tool and cancel_tool; with Read, None and Ui only a rebuild's), the +// project's recipe loaded into an empty document (DesignPanel::hydrate_from_model()), as showing the tab would, and a +// `generation` in `args` that design_generation() refuses (invalid_argument) or that is not the model's (stale_ids). +// Returns the panel. Throws ToolFailure, whose details carry the code. UI thread only. +DesignPanel* design_gate(CadAccess access, const json& args); + +// The silent form of entry `id`, or nullptr. +DesignRun find_silent_form(const std::string& id) +{ + for (const auto& [key, run] : silent_forms()) + if (id == key) return run; + return nullptr; +} + +// Why a menu-only entry (a btn: or fly: handler) is refused for a selection it does not accept. +// TRN Refusal of a Design tab tool picked for a selection its right-click menu item is greyed for (Constrain +// sketch with a face selected). +const char* const kDoesNotApply = L("This tool does not apply to what is selected"); +// Why an entry of the sketch's vocabulary is refused outside a sketch, and one of the model's inside one. +// TRN Refusal of a Design tab tool picked outside a sketch, when it is a sketch tool (a line, a rectangle). +const char* const kSketchTool = L("This tool works in a sketch: open a sketch first"); +// TRN Refusal of a Design tab tool picked while a sketch is open, when it works on the model (Extrude, Shell). +const char* const kModelTool = L("This tool works on the model: finish or cancel the sketch first"); + +// The selection kinds the Design tab reports as what is selected (DesignPanel::offer_selection_kind()), as OfferSel +// bits: in a sketch, what is picked there; on the model, nothing, a face, an edge, a vertex, a body or a committed +// sketch's loop. Menu items accept other kinds too (two bodies, a datum, art, a sketch line on the model), which the tab +// never reports, so no selection can be one of them. +uint32_t reported_kinds(bool sketching) +{ + using S = OfferSel; + static const S in_sketch[] = {S::SkNone, S::SkLine, S::SkArc, S::SkPoint, S::Sk2Ent}; + static const S on_model[] = {S::None, S::FacePlanar, S::FaceCyl, S::FaceOther, S::EdgeStr, + S::EdgeCirc, S::Vertex, S::BodySolid, S::BodySheet, S::SkLoop}; + uint32_t bits = 0; + if (sketching) + for (const S kind : in_sketch) bits |= offer_bit(kind); + else + for (const S kind : on_model) bits |= offer_bit(kind); + return bits; +} + +// Item `item`'s handler, for a call of `command` that opens it (opened_item()), as a person's pick of the item or of +// its Speed Dial action runs it: past design_gate() with no access of its own, so that only a rebuild refuses it, as +// the Design tab's keys and menu are refused by nothing; each tool decides for itself what an open card means to it. +// The handler runs in place, so a modal dialog it opens holds the call, which the core reports as blocked by that +// dialog. +// It is refused, as open_refusal() says, in the mode the item does not belong to, where the right-click menu does not +// offer it, and for a btn: or fly: handler a selection the menu greys the item for. The reply claims nothing about +// what the handler did, which may be to open a card, start a sketch tool, act at once or tell the person why it +// cannot: it says what the tab shows after it, its busy reason (a card, a dialog or a sketch now open) and its +// status line. Its `tool` is the command called. A call that is not a person's pick, made while a row of the Feature +// list is selected and nothing is picked in the view, targets that row: an item whose handler acts on it (feature_row) +// is not refused for the selection then, and applies. A person's pick keeps the menu's rule, which greys the item. +json open_tool(const DesignTool& item, const char* command, const json& args, bool person) +{ + DesignPanel* panel = design_gate(CadAccess::None, args); + const int kind = panel->mcp_offer_selection_kind(); + const bool row_target = !person && panel->mcp_feature_row() >= 0 && kind == int(OfferSel::None) && + panel->mcp_picked_plane() < 0; + const bool applies = (row_target && item.feature_row) || (item.accepts & offer_bit(OfferSel(kind))) != 0; + if (std::optional refused = open_refusal(item, panel->mcp_sketch_map_applies(), kind, row_target)) + throw *refused; + const bool text_was_open = panel->mcp_text_dialog_open(); + panel->mcp_run_verb(item.id); + // A dialog the handler opened held the call until it was answered, unless the handler opened the Text dialog, + // which is modeless: the call returns with it open. A Text dialog open before the handler ran is not its dialog. + const bool modal = item.modal && !(panel->mcp_text_dialog_open() && !text_was_open); + std::string why; + const bool busy = panel->mcp_busy(false, false, why); + return json{{"interactive", true}, + {"tool", command}, + {"applies", applies}, + {"modal", modal}, + {"selection_kind", kind}, + {"busy", busy ? json(why) : json()}, + {"status", into_u8(panel->mcp_status())}}; +} + +// The end of the description of entry `t`'s command: the argument sets that name a menu item, its own args and those of +// the items folded into it, each once with the names of the items it opens (items folded in with one set are one tool +// under several labels, as the value items are with {}), so that a search for an item's name finds the command; empty +// when there are none. +std::string opening_calls(const DesignTool& t) +{ + std::vector> sets; // an argument set as JSON text, and its items' names + const auto add = [&sets](const DesignTool& item) { + const std::string args = json::parse(item.args).dump(); + const auto same = std::find_if(sets.begin(), sets.end(), [&args](const auto& set) { return set.first == args; }); + if (same == sets.end()) + sets.emplace_back(args, item.name); + else + same->second += std::string(", ") + item.name; + }; + if (t.action != nullptr && t.args != nullptr) + add(t); + for (const DesignTool& item : kDesignTools) + if (item.fold_into != nullptr && std::strcmp(item.fold_into, t.id) == 0) + add(item); + if (sets.empty()) + return {}; + std::string calls; + for (const auto& [args, names] : sets) + calls += (calls.empty() ? "" : ", ") + args + " (" + names + ")"; + return " Called with exactly one of these argument sets and nothing else, it opens that item's tool of the Design " + "tab for a person, as the menu item does: " + + calls + "."; +} + +// The command of the Design table's entry `t`, which has a handler, a tool block or both, and is no folded item. +NativeCommand table_command(const DesignTool& t) +{ + const json doc = t.doc != nullptr ? json::parse(t.doc) : json(); + json schema; + if (doc.is_null()) + schema = {{"type", "object"}, {"properties", json::object()}, {"additionalProperties", false}}; + else + schema = design_input_schema(doc); + // The person's form is the call with no arguments where that opens an item's tool, the entry's own or one folded + // into it: it requires nothing (with_silent()), and runs in that item's mode only. + const DesignTool* person_item = opened_item(t, json::object()); + if (person_item != nullptr && !doc.is_null()) { + schema = with_silent(std::move(schema)); + schema["properties"]["silent"]["description"] = std::string(kSilentNote) + " " + mode_note(*person_item, true); + } + + const DesignTool* entry = &t; + NativeCommand c = design_command( + t.id, t.name, std::move(schema), + [entry](const json& args, bool person) { + if (const DesignTool* item = opened_item(*entry, args)) + return open_tool(*item, entry->id, args, person); + return run_design_tool(entry->id, silent_args(args)); + }, + [entry](const json& args) { return opened_item(*entry, args) != nullptr; }); + c.has_own_action = t.action != nullptr; + c.icon = t.icon != nullptr ? t.icon : ""; + c.heading = t.section != nullptr ? t.section : ""; + // The items folded into the command keep their actions, each a call of the command with the item's arguments, + // and say what a pick does as a command with a handler only does. + for (const DesignTool& item : kDesignTools) + if (item.fold_into != nullptr && std::strcmp(item.fold_into, t.id) == 0) + c.actions.push_back({{"key", item.id}, + {"title", item.name}, + {"icon", item.icon != nullptr ? item.icon : ""}, + {"description", std::string(item.hint) + ". " + kOpensToolNote + " " + mode_note(item)}, + {"args", json::parse(item.args)}}); + if (doc.is_null()) { + c.description = std::string(t.hint) + ". " + kOpensToolNote + " " + mode_note(t); + return c; + } + if (find_silent_form(t.id) == nullptr) + throw std::logic_error(std::string("The Design table's entry ") + t.id + " has a tool block but no silent form"); + std::string description = doc.at("summary").get(); + if (const std::string details = doc.at("details").get(); !details.empty()) + description += ' ' + details; + if (t.ok_false) description += std::string(" ") + kFailureNote; + description += opening_calls(t); + c.read_only = t.access == CadAccess::Read; + // A read answers the same however often it is asked, as the listed read-only tools say of themselves. + c.idempotent = c.read_only; + c.description = std::move(description); + c.examples = doc.at("examples"); + // commit_to_plate's replace_ids names Prepare's objects by id. + return with_target_ids(std::move(c)); +} + +} // namespace + +const DesignTool* find_design_tool(const std::string& id) +{ + for (const DesignTool& t : kDesignTools) + if (id == t.id) return &t; + return nullptr; +} + +bool is_design_command(const DesignTool& t) { return (t.action != nullptr || t.doc != nullptr) && t.fold_into == nullptr; } + +const DesignTool* opened_item(const DesignTool& entry, const json& args) +{ + // A call with no arguments gives none, null as {}. + const json given = person_form(args) ? json::object() : args; + if (entry.action != nullptr && (given.empty() || (entry.args != nullptr && json::parse(entry.args) == given))) + return &entry; + for (const DesignTool& item : kDesignTools) + if (item.fold_into != nullptr && std::strcmp(item.fold_into, entry.id) == 0 && item.args != nullptr && + json::parse(item.args) == given) + return &item; + return nullptr; +} + +bool offered_in_mode(const DesignTool& t, bool sketching) { return t.sketch_mode == sketching; } + +std::vector design_actions(const CommandCatalog& catalog, bool sketching, bool cad_on) +{ + std::vector actions; + if (!cad_on) return actions; + for (const DesignTool& t : kDesignTools) { + if (t.action == nullptr || !offered_in_mode(t, sketching)) continue; + const auto [command, action] = find_command_action(catalog, t.id); + if (command != nullptr && command->group == kDesignGroup) actions.push_back({command, action}); + } + return actions; +} + +std::optional open_refusal(const DesignTool& t, bool sketching, int kind, bool row_target) +{ + // The message is the person's; the hint names the commands that change the mode. + if (!offered_in_mode(t, sketching)) + return ToolFailure(t.sketch_mode ? kSketchTool : kModelTool, + {{"code", "wrong_mode"}, + {"mode", t.sketch_mode ? "sketch" : "model"}, + // A model tool's: Constrain mode is a sketch to the menu, and the busy gate refuses + // sketch_finish and sketch_cancel there, so the hint names the two that end either. + {"hint", t.sketch_mode ? "sketch_create {plane: \"XY\"} opens a sketch on a plane, sketch_edit " + "{sketch: i} a committed one" : + "confirm_tool keeps the open sketch, or ends Constrain mode, and " + "cancel_tool drops the sketch or leaves Constrain mode"}}); + // The item's handler acts on the Feature list's selected row, and says itself what it cannot do with it. + if (row_target && t.feature_row) + return std::nullopt; + const std::string handler(t.action); + const bool applies = (t.accepts & offer_bit(OfferSel(kind))) != 0; + // Only an item that accepts a kind the tab can report in its mode is greyed for the others; one that accepts none + // (Boolean's items take two bodies, Rib a sketch line) opens as its toolbar button does, whatever is selected. + const bool greyable = (handler.rfind("btn:", 0) == 0 || handler.rfind("fly:", 0) == 0) && + (t.accepts & reported_kinds(t.sketch_mode)) != 0; + if (applies || !greyable) + return std::nullopt; + // The item's own refusal is about the document (no body, no second sketch), which the menu shows only for + // an item that takes the selection; here the selection is the obstacle, so the reply names what to pick. + json accepts = json::array(); + for (int sel = 0; sel < int(OfferSel::Count); ++sel) + if ((t.accepts & offer_bit(OfferSel(sel))) != 0) + accepts.push_back(kDesignSelectionIds[sel]); + return ToolFailure(kDoesNotApply, {{"code", "wrong_selection"}, + {"selection_kind", kind}, + {"selection", kDesignSelectionIds[kind]}, + {"accepts", std::move(accepts)}}); +} + +namespace { + +DesignPanel* design_gate(CadAccess access, const json& args) +{ + // The MCP server answers before the main window exists and while the app closes. + ui_plater(); + if (!wxGetApp().is_editor() || !wxGetApp().is_enable_cad_feature()) + throw no_design_tab(); + // The panel is built on first use, and in a headless session nobody clicks the tab that would + // build it, so it is built here rather than refused. It is null when no page was made at startup + // (the CAD feature was turned on later), while the page is mid-build, and after its build failed. + DesignPanel* panel = DesignPanel::ensure(); + if (panel == nullptr) + throw no_design_tab(); + + // Only Read commands, the opening of a tool and the Ui commands, which act on what is open, may run under a GUI + // editor or a sketch session they do not own. None may run during a rebuild, not even these: the rebuild's busy + // loop runs this call while the GUI's worker thread holds the document. Checked before hydrating, which writes it. + std::string why; + const bool under_open = access == CadAccess::Read || access == CadAccess::None || access == CadAccess::Ui; + if (panel->mcp_busy(under_open, access == CadAccess::Sketch, why)) + throw design_busy(why); + + // A project opened without ever showing the Design tab has its recipe only in the Model; + // load it, as showing the tab would, before anything reads or writes the document. + panel->hydrate_from_model(); + + // Stale-id guard, checked here rather than in each command's function. + // + // Global face and edge ids are indices into TopExp::MapShapes, valid only against the + // topology that produced them. Every dress-up rewrites those maps, so the natural way to + // drive the Design tab — read the scene once, then issue several operations — silently + // addresses the WRONG edge on every call after the first. Measured on a box: four chamfers + // with ids re-read each time remove 0.400/0.397/0.397/0.395 mm3; the same four with ids + // captured up front remove 0.400/0.008/0.397/0.280. Neither run errors, because a stale id + // still resolves to a real edge — just not the one that was asked for. + // + // So a caller may pass back the "generation" it got from describe_design or body_describe, + // and a mismatch is refused instead of silently obeyed. Optional by design: a call without it + // is not checked, and supplying it is what buys the guarantee. One check here rather than one + // per command, so a command added later cannot forget it. + // + // The type is checked first (design_generation()), as a caller that skips the schema (run_design_tool() called + // directly) may pass any: a bare get() on `"generation": "x"` would surface as an internal error + // instead of a parameter error. + if (const std::optional given = design_generation(args)) { + const uint64_t want = *given; + const uint64_t have = panel->mcp_doc().topo_generation; + if (want != have) + throw ToolFailure("stale face/edge ids: they were read at generation " + std::to_string(want) + + " but the model is now at " + std::to_string(have) + + ". Re-read body_describe and use the new ids — the old ones still name real " + "edges, just not the ones you measured.", + {{"code", "stale_ids"}}); + } + return panel; +} + +} // namespace + +json run_design_tool(const std::string& id, const json& args) +{ + const DesignTool* entry = find_design_tool(id); + const DesignRun run = find_silent_form(id); + if (entry == nullptr || run == nullptr) + throw ToolFailure("No Design command runs silently as " + id, {{"code", "no_silent_form"}}); + DesignPanel* panel = design_gate(entry->access, args); + return run_guarded([&] { return run(panel, args); }); +} + +json design_undo_redo(bool redo) +{ + DesignPanel* panel = design_gate(CadAccess::Sketch, json::object()); + return run_guarded([&] { return undo_redo(panel, redo); }); +} + +json design_input_schema(const json& block) +{ + json properties = json::object(); + json required = json::array(); + for (const json& param : block.at("params")) { + const std::string name = param.at("name").get(); + const std::string type = param.at("type").get(); + json property; + if (type.find('|') != std::string::npos) { + property["type"] = json::array(); + for (std::size_t from = 0;;) { + const std::size_t bar = type.find('|', from); + property["type"].push_back(type.substr(from, bar == std::string::npos ? std::string::npos : bar - from)); + if (bar == std::string::npos) break; + from = bar + 1; + } + } else { + property["type"] = type; + } + if (param.contains("min")) property["minimum"] = param["min"]; + if (param.contains("exclusive_min")) property["exclusiveMinimum"] = param["exclusive_min"]; + if (param.contains("max")) property["maximum"] = param["max"]; + if (param.contains("enum")) property["enum"] = param["enum"]; + if (param.contains("default")) property["default"] = param["default"]; + else required.push_back(name); + // A param whose default is null is one its function reads as left out when it is null (no limit, the open + // sketch), so a call may give null. One marked "nullable": false, whose function reads a null as given, + // keeps its type. + if (param.contains("default") && param["default"].is_null() && param.value("nullable", true)) { + if (!property["type"].is_array()) property["type"] = json::array({property["type"]}); + property["type"].push_back("null"); + if (property.contains("enum")) property["enum"].push_back(nullptr); + } + std::string description = param.value("description", std::string()); + if (const std::string unit = param.value("unit", std::string()); !unit.empty()) + description = description.empty() ? "In " + unit + "." : description + " (" + unit + ")"; + if (!description.empty()) property["description"] = std::move(description); + properties[name] = std::move(property); + } + properties["generation"] = {{"type", "integer"}, {"minimum", 0}, {"description", kGenerationNote}}; + json schema{{"type", "object"}, {"properties", std::move(properties)}, {"additionalProperties", false}}; + if (!required.empty()) schema["required"] = std::move(required); + return schema; +} + +namespace { + +// A Design function's value as its command replies with it: without "ok": true and an empty "error", which say +// nothing that a reply other than an error doesn't. An ok false, and an error's text beside it, stay. +json design_reply(json value) +{ + if (value.is_object()) { + if (const auto ok = value.find("ok"); ok != value.end() && *ok == true) + value.erase(ok); + if (const auto error = value.find("error"); error != value.end() && *error == "") + value.erase(error); + } + return value; +} + +} // namespace + +NativeCommand design_command(std::string key, std::string title, json schema, + std::function fn, std::function opens) +{ + NativeCommand c; + c.key = std::move(key); + c.title = std::move(title); + c.group = kDesignGroup; + c.input_schema = std::move(schema); + c.run = [fn = std::move(fn), opens = std::move(opens)](const json& args, ToolContext& ctx) { + if (ctx.person()) { + try { + return ToolResult::ok(design_reply(fn(args, true))); + } catch (const ToolFailure& refused) { + // What the person reads, in the UI's language where the text is a msgid (an entry's refusal). Looked + // up in the application's catalogue only, as the right-click menu's items are (show_offer_menu()), so + // that a wxWidgets entry cannot answer for it. + throw ToolFailure(into_u8(wxGetTranslation(wxString::FromUTF8(refused.what()), SLIC3R_APP_KEY)), refused.details); + } + } + // `generation` guards ids within this session only: a replay rebuilds the same ids by replaying + // the history, but reaches another generation number, so a recorded one would refuse the replay. + // Journal the call without it. + json recorded = args; + if (recorded.is_object()) recorded.erase("generation"); + // A call that ran may be recorded, without its generation, as one that opens a tool (one with no arguments): + // with silent, its replay runs too. + if (opens && recorded.is_object() && !opens(args) && opens(recorded)) + recorded["silent"] = true; + ctx.set_journal_args(std::move(recorded)); + json result = ctx.run_ui([&] { return fn(args, false); }); + settle(ctx); + return ToolResult::ok(design_reply(std::move(result))); + }; + return c; +} + +void register_design_tools(CommandCatalog& catalog) +{ + // Heading by heading, as tool_list's description indexes them, so that its listing of the group reads in the + // same order. Every command has a heading (DesignTool::section). + for (const char* section : kDesignSections) + for (const DesignTool& t : kDesignTools) + if (is_design_command(t) && t.section != nullptr && std::strcmp(t.section, section) == 0) + catalog.add(table_command(t)); +} + +void leave_out_design_tools(CommandCatalog& catalog, bool editor) +{ + // A folded item's id too, which is no command but names an action. + for (const DesignTool& t : kDesignTools) + if (t.action != nullptr || t.doc != nullptr) + catalog.leave_out(t.id, editor ? kCadOffAtStartup : kNoDesignInViewer, "design_unavailable"); +} + +std::string design_command_index() +{ + std::string index = " The Design tab's CAD commands (sketches, solid and surface features, bodies, measurements) follow " + "by heading; `tool_list {group: \"Design\"}` says what each does and `tool_describe {tool}` gives one's " + "manual. One whose schema has `silent` does what its menu item does when called with no arguments, " + "unless `silent` is true."; + for (const char* section : kDesignSections) { + std::string names; + for (const DesignTool& t : kDesignTools) + if (t.section != nullptr && std::strcmp(t.section, section) == 0) + names += (names.empty() ? "" : ", ") + std::string("`") + t.id + "`"; + index += std::string(" ") + section; + if (std::strcmp(section, "Menu items") == 0) + index += ", which take no arguments and do what their item of the right-click menu does"; + index += ": " + names + "."; + } + return index; +} + +json cad_note(const CommandCatalog& catalog) +{ + if (!wxGetApp().is_editor()) + return nullptr; + const std::vector& commands = catalog.commands(); + const bool registered = std::any_of(commands.begin(), commands.end(), [](const NativeCommand& c) { return c.group == kDesignGroup; }); + return registered && wxGetApp().is_enable_cad_feature() ? json() : json(kCadOffNote); +} + +std::vector cad_commit_to_plate_replace(const json& replace, const Model& model) +{ + if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (object_list)"); + const int count = int(model.objects.size()); + std::vector out; + for (const json& v : replace) { + if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (object_list), not " + v.dump()); + const auto i = v.get(); + if (i < 0 || i >= count) + throw std::runtime_error("object " + std::to_string(i) + " is out of range; the project has " + std::to_string(count) + + " objects"); + if (std::find(out.begin(), out.end(), int(i)) != out.end()) + throw std::runtime_error("object " + std::to_string(i) + " is listed twice in replace"); + // Deleting one opens the "part of a cut object" warning, which the person answers. + if (model.objects[size_t(i)]->is_cut()) + throw CadPrecondition("object " + std::to_string(i) + + " is part of a cut object; delete it with object_select, then object_delete, which asks first"); + out.push_back(int(i)); + } + std::sort(out.begin(), out.end()); + return out; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp b/src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp new file mode 100644 index 0000000000..a549d8d64c --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp @@ -0,0 +1,531 @@ +// The place Filaments: filament_list, the filament list as the sidebar shows it; the filament slot commands made from +// the + and - buttons above it and a slot's menu items; the mixed filaments, a slot's colour and the flushing, set +// as their dialogs' OK sets them; filament_sync_ams; and filament_install and filament_uninstall, what the System +// Filaments dialog's Confirm installs, on the operations of GUI/Operations/InstallOps.hpp. + +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/format.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MixedFilamentDialog.hpp" +#include "slic3r/GUI/NativeCommandMenuItems.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/InstallOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PresetOps.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/PresetComboBoxes.hpp" + +#include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/FilamentMixer.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +// What a slot's colour button does with the colour its picker gives: the slot's colour, then its +// EVT_FILAMENT_COLOR_CHANGED, which recalculates the flushing volumes where Auto flush after changing is on. UI thread. +void apply_slot_colour(std::size_t slot, const std::string& colour) +{ + auto& combos = ui_plater().sidebar().combos_filament(); + auto combo = std::find_if(combos.begin(), combos.end(), + [slot](PlaterPresetComboBox* c) { return c != nullptr && c->get_filament_idx() == int(slot); }); + if (combo == combos.end()) + throw ToolFailure("Filament slot " + std::to_string(slot + 1) + " has no colour button"); + (*combo)->sync_colour_config({colour}, false); + wxCommandEvent* evt = new wxCommandEvent(EVT_FILAMENT_COLOR_CHANGED); + evt->SetInt(int(slot)); + wxQueueEvent(&ui_plater(), evt); +} + +// filament_set_colour: one slot's colour, checked as check_filament_colours() checks a colour list. The reply reads it +// back once the change has settled. +ToolResult set_filament_colour(const json& args, ToolContext& ctx) +{ + const int slot = arg_int(args, "filament_slot", 1); + const std::string colour = arg_string(args, "colour"); + bool changed = false; + ctx.run_ui([&]() -> json { + ui_plater(); + const std::vector& current = + wxGetApp().preset_bundle->project_config.option("filament_colour")->values; + if (slot < 1 || std::size_t(slot) > current.size()) + throw ToolFailure("filament_slot must be 1.." + std::to_string(current.size())); + std::vector colours = current; + colours[std::size_t(slot) - 1] = colour; + colours = check_filament_colours(colours, current, mixed_slots()); + changed = colours[std::size_t(slot) - 1] != current[std::size_t(slot) - 1]; + if (changed) + apply_slot_colour(std::size_t(slot) - 1, colours[std::size_t(slot) - 1]); + return json(); + }); + settle(ctx); + return ToolResult::ok(ctx.run_ui([&]() -> json { + const std::vector& colours = + wxGetApp().preset_bundle->project_config.option("filament_colour")->values; + return {{"filament_slot", slot}, {"colour", colours[std::size_t(slot) - 1]}, {"changed", changed}}; + })); +} + +// filament_list: the filament list as the sidebar shows it, a row per slot in config order (the physical filaments, +// then the mixed ones), with the flushing its Flushing volumes and Purge mode buttons set. UI thread. +json filament_list() +{ + Sidebar& sidebar = ui_plater().sidebar(); + PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::vector& colours = bundle.project_config.option("filament_colour")->values; + const auto* components = bundle.project_config.option("filament_mixed_components"); + const std::vector broken = sidebar.broken_mixed_filaments(); + json rows = json::array(); + for (std::size_t i = 0; i < colours.size(); ++i) { + const bool mixed = bundle.is_mixed_filament(i); + json row{{"filament_slot", i + 1}, {"mixed", mixed}, {"colour", colours[i]}}; + if (!mixed) { + const std::string name = i < bundle.filament_presets.size() ? bundle.filament_presets[i] : std::string(); + Preset* preset = bundle.filaments.find_preset(name); + std::string display; + row["preset"] = name; + row["type"] = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); + rows.push_back(std::move(row)); + continue; + } + // The components as stored, a deleted one as 0; the ratios and the gradient as the Edit Mixed Filament dialog + // reads them. + json parts = json::array(); + if (components != nullptr && i < components->size()) + for (const unsigned int component : parse_mixed_components(components->values[i])) + parts.push_back(component); + const MixedFilamentResult mix = sidebar.mixed_filament_result(i); + row["components"] = std::move(parts); + row["ratios"] = mix.ratios; + row["gradient"] = nullptr; + if (mix.gradient_enabled && mix.components.size() == 2) { + // Direction 0 starts with the first component's share high: it leads at the bottom (filament_mixed_gradient_range). + const bool first_at_bottom = mix.gradient_direction == 0; + row["gradient"] = {{"bottom", first_at_bottom ? mix.components[0] : mix.components[1]}, + {"top", first_at_bottom ? mix.components[1] : mix.components[0]}, + {"per_part", mix.per_part_gradient}, + {"curve", mix.gradient_curve.empty() ? "linear" : "custom"}}; + } + row["broken"] = std::find(broken.begin(), broken.end(), i) != broken.end(); + rows.push_back(std::move(row)); + } + const DynamicPrintConfig settings = project_settings(); + json out{{"filaments", std::move(rows)}, + {"flush_multiplier", settings.option("flush_multiplier")->values}, + {"flush_volumes_matrix", settings.option("flush_volumes_matrix")->values}, + {"prime_volume_mode", settings.opt_serialize("prime_volume_mode")}}; + if (std::vector offered = project_offered("prime_volume_mode"); !offered.empty()) + out["prime_volume_modes"] = std::move(offered); + return out; +} + +// ---- The filament slot commands made from menu items ---- + +// What a filament slot command answers for a refusal: as information where its menu item told it so (no slots to change, no +// + and - buttons for the printer, no room for another slot, the only slot), else as an error. +AppActionRunResult slot_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + const bool info = code == "filaments_unavailable" || code == "one_filament_per_extruder" || code == "too_many_filaments" || + code == "last_filament_slot"; + return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); +} + +// What a filament slot command that ran shows a person, `message`, and replies to a call: `reply` with how many slots +// the project has afterwards. +AppActionRunResult filament_reply(const wxString& message, json reply) +{ + reply["filament_slots"] = wxGetApp().preset_bundle->filament_presets.size(); + AppActionRunResult result{AppActionRunResult::Level::Succeeded, message}; + result.reply = reply.dump(); + return result; +} + +AppActionRunResult filament_add_command(const json&) +{ + const Ops::Outcome added = Ops::add_filament_slot(); + if (!added) + return slot_refused(added.refusal()); + // TRN %1% is a filament slot number. + return filament_reply(format_wxstr(_L("Added filament slot %1%."), added.value()), {{"filament_slot", added.value()}}); +} + +AppActionRunResult filament_delete_command(const json& args) +{ + Ops::DeleteFilamentArgs op; + if (args.contains("filament_slot")) + op.filament_slot = arg_int(args, "filament_slot", 1); + if (args.contains("merge_into")) + op.merge_into = arg_int(args, "merge_into", 1); + if (args.contains("break_mix")) + op.break_mix = arg_bool(args, "break_mix", false); + const Ops::Outcome deleted = Ops::delete_filament_slot(op); + if (!deleted) + return slot_refused(deleted.refusal()); + json reply{{"filament_slot", deleted.value().filament_slot}}; + if (deleted.value().merged_into) + reply["merged_into"] = *deleted.value().merged_into; + if (!deleted.value().broken_mixed.empty()) + reply["broken_mixed"] = deleted.value().broken_mixed; + // TRN %1% is a filament slot number. + return filament_reply(format_wxstr(_L("Deleted filament slot %1%."), deleted.value().filament_slot), std::move(reply)); +} + +// filament_sync_ams: with no arguments, as its Speed Dial action, the sync dialog's run, which asks and warns; with +// mode, the sync with that choice of the dialog, which opens nothing. Reply: each slot's preset and colour afterwards. +AppActionRunResult sync_ams_command(const json& args) +{ + if (!args.contains("mode")) + return MenuItems::sync_ams(); + const Ops::AmsSyncMode mode = arg_string(args, "mode") == "map" ? Ops::AmsSyncMode::Map : Ops::AmsSyncMode::Overwrite; + const Ops::Outcome synced = Ops::sync_filaments_from_ams(mode); + if (!synced) + return NativeCommands::refused(synced.refusal(), AppActionRunResult::Level::Error); + json slots = json::array(); + for (std::size_t slot = 0; slot < synced.value().presets.size(); ++slot) { + json item{{"filament_slot", slot + 1}, {"preset", synced.value().presets[slot]}}; + if (slot < synced.value().colours.size()) + item["colour"] = synced.value().colours[slot]; + slots.push_back(std::move(item)); + } + json reply{{"mode", arg_string(args, "mode")}, {"filaments", std::move(slots)}}; + if (!synced.value().unknowns.empty()) + reply["mapped_to_generic"] = synced.value().unknowns; + return menu_reply(reply); +} + +// What the filament commands reply when an operation refuses: the names a refusal carries under the key that says +// what they are. +ToolFailure filament_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + if (code == "no_such_filament" || code == "no_filament_vendor") + return refused(refusal, "preset_list {type: \"filament\", include_uninstalled: true} lists the system filaments.", "similar"); + if (code == "fits_no_printer") + return refused(refusal, "Name one of its presets.", "presets"); + if (code == "no_matching_filament") + return refused(refusal, "", "filament_types"); + if (code == "filament_in_use") + return refused(refusal, "Select another filament for the slot first (preset_select with filament_slot).", "presets"); + return refused(refusal); +} + +// filament_install's and filament_uninstall's function: the names, or the vendor and filament type, a call gives. +CommandFn change_filaments(bool install) +{ + return [install](const json& args, ToolContext& ctx) { + Ops::InstallFilamentsArgs op; + if (const auto names = args.find("names"); names != args.end()) + for (const json& name : *names) + op.names.push_back(name.get()); + op.vendor = arg_string(args, "vendor"); + op.filament_type = arg_string(args, "filament_type"); + if (op.names.empty() && op.vendor.empty() && op.filament_type.empty()) + throw ToolFailure("Give names, or vendor and filament_type"); + if (!op.names.empty() && (args.contains("vendor") || args.contains("filament_type"))) + throw ToolFailure("Give names, or vendor and filament_type, not both"); + if (op.names.empty() && (op.vendor.empty() || op.filament_type.empty())) + throw ToolFailure("vendor and filament_type go together"); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome done = install ? Ops::install_filaments(op) : Ops::uninstall_filaments(op); + if (!done) + throw filament_refused(done.refusal()); + json out{{install ? "installed" : "uninstalled", done.value().changed}}; + if (!done.value().unchanged.empty()) + out[install ? "installed_already" : "not_installed"] = done.value().unchanged; + if (!done.value().defaults_installed.empty()) + out["filaments_installed"] = done.value().defaults_installed; + return out; + }); + settle(ctx); + return ToolResult::ok(reply); + }; +} + +} // namespace + +void register_filament_tools(CommandCatalog& catalog) +{ + using NativeCommands::action; + + // The + and - buttons above the filament list and a slot's Delete menu item, each named as the button or menu item is, in the Speed + // Dial's section Filament. + const std::string slot_buttons = "Refused for a printer that has one filament per extruder, which shows no + and - buttons."; + catalog.add(inspect_tool( + "filament_list", L("List the filaments"), + "Read the filament list as the sidebar shows it. filaments has a row per slot in config order, the physical " + "filaments first, then the mixed ones: `filament_slot` (1-based), mixed, colour (#RRGGBB) and, for a physical " + "filament, preset and type; for a mixed filament, components (the physical slots it mixes, 1-based, 0 for one " + "deleted), ratios (whole percentages, as `filament_add_mixed` takes them), gradient (null, or `{bottom, top: the " + "components that lead at the bottom and at the top, per_part, curve: linear or custom}`) and broken (a component " + "deleted or of another filament type: the sidebar marks it, slicing an object on it is refused, and " + "`filament_edit_mixed` repairs it). Then the flushing the list's Flushing volumes and Purge mode buttons set: " + "`flush_multiplier` (one per nozzle), `flush_volumes_matrix` (per nozzle, slots x slots from row to column in config " + "order over every slot, before the multiplier: the dialog shows each entry multiplied by its nozzle's multiplier, " + "and the G-code purges that product) and `prime_volume_mode`, with `prime_volume_modes` where the printer offers a " + "choice. The printer keeps all of it across new projects and restarts; a saved project keeps its own.", + object_schema({}), + [](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([] { + ui_plater(); + return filament_list(); + })); + })); + catalog.add(reaching({"add_filament_slot"}, + own_action(menu_command("filament_add", L("Add Filament Slot"), + "Add a filament slot, as the + button above the filament list does. It takes the next " + "colour and the last slot's preset (change them with `filament_set_colour` and " + "`preset_select` `filament_slot`). It goes after the physical slots: mixed " + "filaments move up by one, and objects on them follow. " + + slot_buttons + " Reply: `filament_slot` (the new slot) and `filament_slots` (how many the " + "project has).", + object_schema({}), json(), filament_add_command), + L("Filament"), "add_filament"))); + catalog.add(reaching( + {"delete_filament_slot"}, + own_action(menu_command("filament_delete", L("Delete Filament Slot"), + "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; " + "with `merge_into`, as its Merge with item does, the objects on it taking that slot. The slots after " + "it move down by one. A mixed filament (`filament_list`'s mixed rows) is deleted as the mixed " + "filament list deletes it, and not merged. A physical filament that a mixed filament mixes is " + "deleted as the sidebar deletes it: the mix is broken (`broken_mixed`) until `filament_edit_mixed` " + "names its filaments again. A merge into a mixed filament that mixes the slot asks first, as Merge " + "with does, and replies `blocked_by_dialog`, unless `break_mix` answers: `true` merges, `false` refuses " + "(`mixed_uses_slot`). Refused: the only physical slot, and a mixed filament while one physical " + "slot is left, where the sidebar hides the mixed filaments (`filament_add` first). " + + slot_buttons + " Not in the undo history. Reply: `filament_slot` (the slot deleted), `merged_into` " + "(the slot its objects went to, as numbered afterwards), `filament_slots`, and " + "`broken_mixed` (the mixed filaments broken afterwards, as numbered then) where " + "there are any.", + object_schema({{"filament_slot", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The 1-based filament slot. Default: the last " + "physical slot, as the - button."}}}, + {"merge_into", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The 1-based slot the objects on it go to, as Merge " + "with does. Default: they take the first filament."}}}, + {"break_mix", prop("boolean", "The answer to Merge with's question about a merge into " + "a mixed filament that mixes the slot: `true` merges, " + "`false` merges nothing. Default: the question opens.")}}), + json(), filament_delete_command), + L("Filament"), "delete_filament"))); + + // The Add and Edit Mixed Filament dialogs' controls, for an agent that drives a dialog to set a gradient. + const std::string mixed_dialog = + "replies `blocked_by_dialog`. Its controls are named `filament_1` to `filament_3` (the components), gradient, " + "`gradient_direction` (item 0 puts the first filament at the bottom, item 1 the second) and `per_part_gradient`, for " + "`widget_set_value` with within the dialog's title; the gradient shows for a mix of two filaments only, and its curve " + "is drawn, changed only by dragging it (`mouse_gesture`). Its OK makes what it shows; Cancel changes nothing."; + const auto mix_props = [](const char* components) { + return std::vector{ + {"components", array_prop({{"type", "integer"}, {"minimum", 1}}, components)}, + {"ratios", array_prop({{"type", "integer"}, {"exclusiveMinimum", 0}}, + "Each component's share in percent, in the order of components, adding up to 100.")}}; + }; + const auto mix_args = [](const json& args, std::vector& components, std::vector& ratios) { + for (const json& component : args.value("components", json::array())) + components.push_back(component.get()); + for (const json& ratio : args.value("ratios", json::array())) + ratios.push_back(ratio.get()); + }; + const std::vector add_props = mix_props("The physical filament slots to mix, 1-based, two or more, each once, of " + "filaments of one type. Omitted with ratios: the dialog opens."); + NativeCommand mixed = reaching( + {"add_mixed_filament"}, + mutate_tool( + "filament_add_mixed", L("Add Mixed Filament"), + "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as " + "the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots " + "(1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to " + "100. It goes after every other slot. A mix the project has already is not added again: the reply names its " + "slot. With neither components nor ratios it opens the Add Mixed Filament dialog, as the sidebar's button does, " + "and " + mixed_dialog + " Not in the undo history. Reply: `filament_slot` (1-based, where one was added or " + "found) and added (false for a mix the project had, or a dialog cancelled).", + object_schema({add_props[0], add_props[1]}), + [mix_args](const json& args, ToolContext& ctx) { + Ops::AddMixedFilamentArgs op; + mix_args(args, op.components, op.ratios); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome mixed = Ops::add_mixed_filament(op); + if (!mixed) + throw refused(mixed.refusal()); + json out{{"added", mixed.value().added}}; + if (mixed.value().filament_slot > 0) + out["filament_slot"] = mixed.value().filament_slot; + return out; + }); + settle(ctx); + return ToolResult::ok(reply); + })); + mixed.examples = json::parse(R"json([ + {"title": "Mix the first two filaments half and half", "calls": [ + {"tool": "filament_add_mixed", "args": {"components": [1, 2], "ratios": [50, 50]}}]}, + {"title": "Mix three filaments, the third the most", "calls": [ + {"tool": "filament_add_mixed", "args": {"components": [1, 2, 3], "ratios": [25, 25, 50]}}]}])json"); + catalog.add(std::move(mixed)); + + const std::vector edit_props = mix_props("The physical filament slots it mixes from now on, as `filament_add_mixed` " + "takes them. Omitted with ratios: the dialog opens."); + NativeCommand edit_mixed = reaching( + {"edit_mixed_filament"}, + mutate_tool( + "filament_edit_mixed", L("Edit Mixed Filament"), + "Change a mixed filament (`filament_list`'s mixed rows) as the Edit Mixed Filament dialog's OK does: components " + "and ratios as `filament_add_mixed` takes them. The slot keeps its number and the objects on it, and its colour " + "becomes the blend; a gradient stays for a mix of two filaments and goes for more, as the dialog shows none for " + "them. An edit that names its filaments again repairs a broken mix. With `filament_slot` alone it opens the Edit " + "Mixed Filament dialog on the mix, as a click on its swatch does, and " + mixed_dialog + + " Not in the undo history. Reply: `filament_slot` and changed.", + object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The mixed filament's 1-based slot."}}}, + edit_props[0], edit_props[1]}, + {"filament_slot"}), + [mix_args](const json& args, ToolContext& ctx) { + Ops::EditMixedFilamentArgs op; + op.filament_slot = arg_int(args, "filament_slot", 1); + mix_args(args, op.components, op.ratios); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome edited = Ops::edit_mixed_filament(op); + if (!edited) + throw refused(edited.refusal()); + return json{{"filament_slot", edited.value().filament_slot}, {"changed", edited.value().changed}}; + }); + settle(ctx); + return ToolResult::ok(reply); + })); + edit_mixed.examples = json::parse(R"json([ + {"title": "Make the mixed filament in slot 3 mostly its first filament", "calls": [ + {"tool": "filament_edit_mixed", "args": {"filament_slot": 3, "components": [1, 2], "ratios": [75, 25]}}]}])json"); + catalog.add(std::move(edit_mixed)); + + catalog.add(mutate_tool( + "filament_set_colour", L("Set a filament's colour"), + "Set a physical filament slot's colour, as its colour button's picker does: colour is #RRGGBB. Where Auto flush " + "after changing is on, the flushing volumes are recalculated, so set `flush_volumes_matrix` (`filament_set_flushing`) " + "after the colours. A mixed filament's colour is its components' blend and is not set. Reply: `filament_slot`, " + "colour (as stored, upper case) and changed.", + object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The 1-based filament slot."}}}, + {"colour", prop("string", "#RRGGBB.")}}, + {"filament_slot", "colour"}), + [](const json& args, ToolContext& ctx) { return set_filament_colour(args, ctx); })); + + catalog.add(mutate_tool( + "filament_set_flushing", L("Set the flushing"), + "Change the flushing the filament list's Flushing volumes and Purge mode buttons set, as their dialogs' OK does, " + "any of: `flush_multiplier` (one per nozzle, or one value for all, within the Flushing volumes dialog's range), " + "`flush_volumes_matrix` (per nozzle, slots x slots from row to column in config order over every slot, before the " + "multiplier; whole, or one entry as `{index, value}`; a mixed filament's entries, which are never flushed, must be " + "given as they are) and `prime_volume_mode` (one of `filament_list`'s `prime_volume_modes`). A colour change " + "(`filament_set_colour`) can recalculate the matrix, so set it after the colours. Values are checked before " + "anything changes. Reply: applied and changed.", + object_schema({{"flush_multiplier", {{"type", {"number", "array"}}, {"description", "One value, or one per nozzle."}}}, + {"flush_volumes_matrix", {{"type", {"array", "object"}}, {"description", "The whole matrix, or `{index, value}`."}}}, + {"prime_volume_mode", prop("string", "The purge mode, e.g. \"Default\".")}}), + [](const json& args, ToolContext& ctx) { + json values = json::object(); + for (const char* key : {"flush_multiplier", "flush_volumes_matrix", "prime_volume_mode"}) + if (args.contains(key)) + values[key] = args[key]; + if (values.empty()) + throw ToolFailure("Give flush_multiplier, flush_volumes_matrix or prime_volume_mode"); + return set_project_values(values, ctx, true); + })); + + const std::string ams = "Synchronize the filament list from the connected printer's AMS."; + NativeCommand sync_ams = reaching( + {"sync_filaments_from_ams"}, + menu_command("filament_sync_ams", L("Synchronize Filament List from AMS"), + ams + " With mode, as the sync dialog's Synchronize now does with that choice, without the dialog: map maps " + "each of the project's filaments to a slot, as the dialog's Mapping first does, which takes a project " + "with objects; overwrite replaces the filament list with the slots' filaments. Called with no arguments, " + "as its Speed Dial action, it opens the sync dialog where the project has objects (`blocked_by_dialog`), and " + "a warning where it cannot sync. With no printer connected, no AMS or no filament it is refused, saying so. " + "Not in the undo history. Reply: mode, filaments (each slot's preset and colour afterwards) and " + "`mapped_to_generic` (slots whose filament is unknown, mapped to a generic preset).", + object_schema({{"mode", enum_prop({"map", "overwrite"}, "The sync dialog's choice: map or overwrite.")}}), + json::array({action("sync_ams", L("Synchronize Filament List from AMS"), L("Printer"), "ams_fila_sync", json::object(), + ams)}), + sync_ams_command)); + // It reads the connected printer's AMS. + sync_ams.open_world = true; + catalog.add(std::move(sync_ams)); + + const json names_prop = {{"type", "array"}, + {"minItems", 1}, + {"items", {{"type", "string"}}}, + {"description", "System filaments: a preset's name, or the short name the filament selector " + "shows (\"Bambu PLA Basic\"), which stands for its preset of every installed " + "printer it fits."}}; + const std::string kept = "The app keeps an installed printer's default filaments installed while no other installed filament " + "fits it: where the call leaves one so, they are installed again and listed under " + "`filaments_installed`, as the next start would. The other filaments, and the presets' unsaved " + "changes, are kept, and the selectors are refreshed. Not in the undo history."; + NativeCommand install_filaments = reaching( + {"install_filaments"}, + mutate_tool("filament_install", L("Install system filaments"), + "Install system filaments, for good, as ticking them in the System Filaments dialog and pressing Confirm " + "does: the filament selectors offer them. Name them by names, or with vendor and `filament_type` every " + "filament of that vendor and type that an installed printer fits. `preset_list {type: \"filament\", " + "include_uninstalled: true}` lists the system filaments, those not installed with `installed: false`. A name " + "no filament has is refused with the closest names. " + + kept + " Reply: installed (the presets installed), `installed_already`, `filaments_installed`.", + object_schema({{"names", names_prop}, + {"vendor", prop("string", "With `filament_type`, in place of names: a filament maker (\"Bambu " + "Lab\", \"Generic\"), in any case.")}, + {"filament_type", prop("string", "With vendor: a filament type (\"PLA\"), in any case.")}}), + change_filaments(true))); + install_filaments.examples = json::parse(R"json([ + {"title": "Install a filament by the name the selector shows", "calls": [ + {"tool": "preset_list", "args": {"type": "filament", "include_uninstalled": true, "query": "PETG HF"}}, + {"tool": "filament_install", "args": {"names": ["Bambu PETG HF"]}}]}, + {"title": "Install every filament of a vendor and type", "calls": [ + {"tool": "filament_install", "args": {"vendor": "Generic", "filament_type": "PETG"}}]}])json"); + catalog.add(std::move(install_filaments)); + + NativeCommand uninstall_filaments = reaching( + {"uninstall_filaments"}, + mutate_tool("filament_uninstall", L("Uninstall system filaments"), + "Uninstall system filaments, for good, as unticking them in the System Filaments dialog and pressing " + "Confirm does: the filament selectors no longer offer them. names as `filament_install` takes them. A " + "filament a slot of the project uses is refused, naming the slot. " + + kept + " Reply: uninstalled (the presets uninstalled), `not_installed`, `filaments_installed`.", + object_schema({{"names", names_prop}}, {"names"}), change_filaments(false))); + uninstall_filaments.examples = json::parse(R"json([ + {"title": "Uninstall a filament", "calls": [ + {"tool": "filament_uninstall", "args": {"names": ["Bambu PETG HF"]}}]}])json"); + catalog.add(std::move(uninstall_filaments)); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp similarity index 84% rename from src/slic3r/GUI/Mcp/McpToolsUi.cpp rename to src/slic3r/GUI/Mcp/Tools/GuiTools.cpp index d18d2bc952..4b43979fe8 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp @@ -1,27 +1,27 @@ -// GUI automation: look at the widget tree, click, type, press keys, drag on the 3D canvas, answer -// dialogs and run JavaScript in web views. +// The place Driving the GUI: look at the widget tree, click, type, press keys, drag on the 3D canvas, answer dialogs +// and run JavaScript in web views. -#include "JobRegistry.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "McpCore.hpp" -#include "McpPaths.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" -#include "WindowNames.hpp" -#include "ModalTracker.hpp" -#include "ScreenCapture.hpp" -#include "UiInspector.hpp" -#include "WebPages.hpp" -#include "WindowControl.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/ScreenCapture.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/Mcp/WebPages.hpp" +#include "slic3r/GUI/Mcp/WindowControl.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" +#include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/Camera.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoSVG.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/Gizmos/GLGizmoSVG.hpp" -#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp" -#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/Plater.hpp" @@ -33,27 +33,21 @@ #include #include #include -#include #include -#include #include -#include -#include #include +#include #include #include -#include #include #include -#include +#include #include #include -#include #include #include #include -#include #include #include #include @@ -114,22 +108,6 @@ wxWindow* target_window(const UiTarget& t) return t.kind == UiTarget::Kind::Window || t.kind == UiTarget::Kind::Row ? t.window.get() : nullptr; } -// The journal replays locators, never refs: refs mean nothing in another session. -void journal_with_locator(ToolContext& ctx, const json& args, const json& locator) -{ - json recorded = args; - if (recorded.contains("target") && recorded["target"].is_string() && !locator.is_null()) - recorded["target"] = locator; - ctx.set_journal_args(std::move(recorded)); -} - -NativeCommand recover_input_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) -{ - NativeCommand d = mutate_tool(std::move(name), std::move(title), std::move(description), std::move(schema), std::move(handler)); - d.guard = GuardClass::Recover; - return d; -} - const json kPopupItemSchema = prop("string", "The item to run of a menu the input opens (a context menu, a button's menu), by " "label path (\"Add Modifier>Cylinder\"; \"#2\": a repeated label's second). Without " "it the reply lists the menu (`popup_menu`) instead of showing it."); @@ -1066,334 +1044,10 @@ wxWebView* key_page(AutomationRuntime& runtime) return webs.size() == 1 && !own_widget ? webs.front() : nullptr; } -// The window window_set's target names: the main window, the topmost modal dialog, or the window a ref or -// locator is in. Refuses one no tool may size or move. `locator` gets what the journal records for a -// ref. UI thread. -wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, json& locator) -{ - wxWindow* window = nullptr; - if (target == "main") { - window = wxGetApp().mainframe; - if (window == nullptr) - throw ToolFailure("The main window is not up yet"); - } else if (target == "dialog") { - window = runtime.modals().top(); - if (window == nullptr) - throw ToolFailure(no_modal_dialog(runtime.modals())); - } else { - UiTarget t; - try { - t = runtime.inspector().resolve(target); - } catch (const ToolFailure& e) { - // A window's ref goes stale once the window is destroyed, and window_list gives the open ones'. - if (!target.is_string()) - throw; - throw ToolFailure(std::string(e.what()) + ", or window_list for the open windows", e.details); - } - locator = runtime.inspector().locator_for(t); - window = t.window.get() != nullptr ? wxGetTopLevelParent(t.window.get()) : nullptr; - } - if (dynamic_cast(window) != nullptr) - throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (window_list)"); - auto* tlw = dynamic_cast(window); - if (tlw == nullptr) - throw ToolFailure("The target is in no window"); - if (tlw->GetName() == kHiddenFromAutomation) - throw ToolFailure("The window is the person's own, which no tool reaches"); - if (auto* dlg = dynamic_cast(tlw); dlg != nullptr && is_native_dialog(dlg)) - throw ToolFailure("A native dialog is placed by the system; answer it with dialog_answer"); - // A closed dialog may be hidden rather than destroyed, so its ref still resolves. - if (!tlw->IsShown()) - throw ToolFailure("The window is closed; window_list lists the open windows"); - return *tlw; -} - -// `window` while it is still one of the app's top-level windows, else null: window_set keeps a plain -// pointer across its UI closures and checks it before following it. UI thread. -wxTopLevelWindow* live_window(wxTopLevelWindow* window) -{ - for (wxWindow* w : wxTopLevelWindows) - if (w == window) - return window; - return nullptr; -} - -// window_set: checks the request and applies it in one UI closure, waits for the window to take it, -// then replies with what the window became. A size or position applies to the normal window, so a -// maximized or minimized one is restored first. Where the window system restores it later (GTK), the call -// waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to -// the restore sizes the window again, and wx would size it by the maximized window's decorations. A window -// brought back from the minimized state is finished restoring once it is back (finish_restore(), macOS). -ToolResult set_window(AutomationRuntime& runtime, ToolContext& ctx, const json& args) -{ - const json target = args.value("target", json("main")); - json locator; - // Never followed off the UI thread, and checked by live_window() on it: a wxWeakRef can't be made or - // dropped on this thread. - wxTopLevelWindow* window = nullptr; - bool main = false, modal = false, restoring = false, unminimizing = false; - WindowSettling settling; - const bool placing = args.contains("size") || args.contains("position"); - const std::string state = arg_string(args, "state"); - const auto minimized = [](const wxTopLevelWindow& w) { return std::string(window_state(w)) == "minimized"; }; - // The request, less the restore that comes before a size or position. UI thread. - const auto apply = [&](wxTopLevelWindow& w) { - if (args.contains("size")) - settling.limited = resize_window(w, wxSize(args["size"][0].get(), args["size"][1].get())); - // -1 is a place on a screen left of or above the primary one, not "keep this coordinate". - if (args.contains("position")) - w.Move(args["position"][0].get(), args["position"][1].get(), wxSIZE_ALLOW_MINUS_ONE); - if (state == "maximized") { - maximize_window(w); - } else if (state == "minimized") { - minimize_window(w); - } else if (state == "normal") { - settling.activation = settling.activation || (restore_needs_activation() && minimized(w)); - unminimizing = unminimizing || minimized(w); - restore_window(w); - } - if (arg_bool(args, "raise", false)) - raise_window(w); - }; - ctx.run_ui([&] { - wxTopLevelWindow& w = window_target(runtime, target, locator); - auto* dlg = dynamic_cast(&w); - main = &w == wxGetApp().mainframe; - modal = dlg != nullptr && dlg->IsModal(); - WindowAbilities abilities; - abilities.main = main; - abilities.modal = modal; - abilities.can_maximize = w.HasFlag(wxMAXIMIZE_BOX); - abilities.can_minimize = w.HasFlag(wxMINIMIZE_BOX); - abilities.positions_known = window_positions_known(); - if (const std::string refusal = window_request_refusal(args, abilities); !refusal.empty()) - throw ToolFailure(refusal); - window = &w; - if (placing && std::string(window_state(w)) != "normal") { - settling.activation = restore_needs_activation() && minimized(w); - unminimizing = minimized(w); - restoring = restore_window(w); - } - if (!restoring) - apply(w); - return json(); - }); - journal_with_locator(ctx, args, locator); - - // The window manager may apply a request later (X11) or animate it (macOS): a wait ends at two equal - // readings in a row in the state asked for. `holds` takes a reading and says whether the window held - // still in `wanted` (any state when empty). UI thread. - const char* closed = "The request was applied before the window closed"; - json last; - const auto holds = [&](const std::string& wanted) { - wxTopLevelWindow* w = live_window(window); - if (w == nullptr) - throw ToolFailure(closed); - const wxPoint pos = w->GetScreenPosition(); - const wxSize size = window_size(*w); - const std::string now = window_state(*w); - const json reading{pos.x, pos.y, size.x, size.y, now}; - return reading == std::exchange(last, reading) && (wanted.empty() || now == wanted); - }; - const auto cancelled = [] { return ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped"); }; - if (restoring) { - // The rest of the request goes to the window the restore left, normal or not. - poll_until(ctx, [&] { return holds("normal") ? json(true) : json(); }, state_change_timeout("normal"), std::chrono::milliseconds(50)); - if (ctx.cancelled()) - throw cancelled(); - ctx.run_ui([&] { - wxTopLevelWindow* w = live_window(window); - if (w == nullptr) - throw ToolFailure(closed); - apply(*w); - return json(); - }); - last = json(); - } - - // For the main window the wait also lasts until its 3D view has drawn at the new size, which a - // minimized window never does. - std::string wanted = state; - if (wanted.empty() && placing) - wanted = "normal"; - const std::chrono::seconds timeout = state_change_timeout(wanted); - settling.seconds = int(timeout.count()); - const json done = poll_until( - ctx, - [&]() -> json { - if (wxTopLevelWindow* w = live_window(window); w != nullptr && unminimizing) - unminimizing = !finish_restore(*w); - settling.held = holds(wanted); - if (!settling.held) - return json(); - return !main || minimized(*live_window(window)) || view_drawn_at_size() ? json(true) : json(); - }, - timeout, std::chrono::milliseconds(50)); - if (done.is_null() && ctx.cancelled()) - throw cancelled(); - settling.drawn = !done.is_null(); - if (settling.held && !settling.drawn) - settling.undrawn = undrawn_window(ctx); - - json out = ctx.observe_ui([&] { - wxTopLevelWindow* w = live_window(window); - if (w == nullptr) - throw ToolFailure(closed); - // window_list's own entry, so the two report a window alike. - const json entry = runtime.inspector().window_entry(*w, modal); - json reply{{"title", entry["title"]}, {"kind", entry["kind"]}, {"ref", entry["ref"]}, {"size", {entry["width"], entry["height"]}}}; - if (entry.contains("x")) - reply["position"] = {entry["x"], entry["y"]}; - reply["state"] = entry["state"]; - reply["resizable"] = entry["resizable"]; - reply["scale"] = w->GetContentScaleFactor(); - // A minimized window may be on no display; the primary one stands for it then. - int index = wxDisplay::GetFromWindow(w); - for (unsigned i = 0; index == wxNOT_FOUND && i < wxDisplay::GetCount(); ++i) - if (wxDisplay(i).IsPrimary()) - index = int(i); - reply["display"] = display_area(unsigned(std::max(index, 0))); - if (arg_bool(args, "raise", false)) - reply["active"] = w->IsActive(); - return reply; - }); - add_window_notes(args, settling, out); - return ToolResult::ok(out); -} - } // namespace -bool view_drawn_at_size() +void register_gui_tools(CommandCatalog& catalog) { - GLCanvas3D* canvas = shown_canvas(); - if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) - return true; - // What render() gives the viewport: the canvas's size in GL pixels, at least 10. - const Size size = canvas->get_canvas_size(); - const std::array& viewport = ui_plater().get_camera().get_viewport(); - if (viewport[2] == std::max(10, size.get_width()) && viewport[3] == std::max(10, size.get_height())) - return true; - canvas->set_as_dirty(); - return false; -} - -void add_window_notes(const json& args, const WindowSettling& settling, json& reply) -{ - json adjusted = json::array(); - for (const std::string field : {"size", "position", "state"}) - if (args.contains(field) && reply.contains(field) && reply[field] != args[field]) - adjusted.push_back(field); - std::string note = settling.limited ? "size is held to the window's minimum or maximum size" : ""; - const auto add = [¬e](const std::string& why) { note += (note.empty() ? "" : "; ") + why; }; - if (!settling.held && settling.activation) - add("the compositor did not bring the window back: Wayland lets an app restore its minimized window only by " - "activating it, which the compositor allows only while the app may take the focus, so the person restores it " - "from the taskbar"); - else if (!settling.held) - add("the window manager did not apply the request within " + std::to_string(settling.seconds) + " s"); - else if (!settling.drawn) - add("the 3D view did not draw at the window's size within " + std::to_string(settling.seconds) + " s" + - (settling.undrawn.empty() ? "" : ": " + settling.undrawn)); - else if (note.empty() && !adjusted.empty()) - note = "the window manager adjusted the request"; - if (!adjusted.empty()) - reply["adjusted"] = std::move(adjusted); - if (!note.empty()) - reply["note"] = note; -} - -std::string window_request_refusal(const json& args, const WindowAbilities& window) -{ - const bool size = args.contains("size"), position = args.contains("position"); - if (!size && !position && !args.contains("state") && !args.contains("raise")) - return "Give at least one of size, position, state or raise; window_list reads a window's geometry without changing it"; - // Two whole numbers that fit wx's int coordinates, both positive for a size. Whole floats pass, as - // they pass the schema's integer type. - const auto is_pair = [](const json& value, bool positive) { - const auto whole = [positive](const json& n) { - if (!n.is_number()) - return false; - const double d = n.get(); - return d == std::floor(d) && d >= (positive ? 1.0 : double(std::numeric_limits::min())) && - d <= double(std::numeric_limits::max()); - }; - return value.is_array() && value.size() == 2 && std::all_of(value.begin(), value.end(), whole); - }; - if (size && !is_pair(args.at("size"), true)) - return "Give size as [width, height], two positive integers"; - if (position && !is_pair(args.at("position"), false)) - return "Give position as [x, y], two integers"; - const json state = args.value("state", json()); - if ((state == "maximized" || state == "minimized") && (size || position)) - return "A " + state.get() + - " window's size and position are set by the system: give state alone, or size and position without state"; - if (state == "maximized" && !window.main && !window.can_maximize) - return "This window's title bar has no maximize button: give it a size instead"; - if (state == "minimized" && window.modal) - return "A modal dialog never minimizes, as the app would stay blocked with nothing showing: close the dialog instead"; - if (state == "minimized" && !window.main && !window.can_minimize) - return "This window's title bar has no minimize button: move it aside with position, or close it, instead"; - if (position && !window.positions_known) - return "position needs X11: Wayland gives an app no way to place its window or to read where it is. Leave position " - "out, or start OrcaSlicer with GDK_BACKEND=x11 to run it under XWayland, where every field works"; - return {}; -} - -json display_area(unsigned index) -{ - const wxRect area = wxDisplay(index).GetClientArea(); - return {{"index", index}, {"x", area.x}, {"y", area.y}, {"width", area.width}, {"height", area.height}}; -} - -void register_ui_tools(CommandCatalog& catalog) -{ - catalog.add(inspect_tool( - "window_list", L("List the windows"), - "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an " - "object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the " - "topmost last. A window's ref goes to `window_screenshot` as target to capture that window, to `widget_list` as target to " - "list it alone, and to `keyboard_press` as target; its title is the within of locators for its widgets.\n" - "Reply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, " - "ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state " - "(normal, maximized or minimized) and resizable (it has a resize border); `window_set` changes them.\n" - "A native dialog (a message box, a file picker) has `native: true` and no ref: `dialog_answer` answers it. `hidden: " - "true` marks the person's own windows (the Run Script panel floating, its prompts and Action Replay's, the Python " - "scripts setting), which no tool reaches and screenshots leave out.", - object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 100."}}}, - {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - return ToolResult::ok(page(ctx.run_ui([&] { return runtime.inspector().windows(); }), args)); - })); - - { - NativeCommand def = recover_input_tool( - "window_set", L("Size, move or raise a window"), - "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one " - "`window_list` lists, also while a modal dialog is open. Size the main window before `view_set` fits the camera and " - "before `recording_start`, as a recording keeps its first frame's size. size and position are in the units " - "`window_list` reports, whose x/y and width/height are read as position and size too. A size or position restores " - "a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog " - "never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn " - "at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per " - "window unit), display (its work area), active with raise, and adjusted with a note: what the OS or a size limit " - "changed.", - object_schema({{"target", {{"type", json::array({"string", "object"})}, - {"description", "main (default), dialog (the topmost modal " - "dialog), or a window's ref or locator from `window_list`; a widget's ref or " - "locator picks the window it is in."}}}, - {"size", array_prop({{"type", "integer"}}, "`[width, height]`, held to the window's minimum and maximum size.")}, - {"position", array_prop({{"type", "integer"}}, "`[x, y]` of the window's top-left corner on screen; not on Wayland.")}, - {"state", enum_prop({"normal", "maximized", "minimized"}, - "normal restores a maximized or minimized window; maximized and minimized take no size " - "or position.")}, - {"raise", prop("boolean", "Bring the window in front of the app's other windows; active in the reply says " - "whether it became the active one.")}}), - [](const json& args, ToolContext& ctx) { return set_window(ctx.runtime(), ctx, args); }); - def.allowed_during_operation = true; - catalog.add(def); - } - { NativeCommand def = inspect_tool( "widget_list", L("List the widgets"), diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp similarity index 79% rename from src/slic3r/GUI/Mcp/McpToolsScene.cpp rename to src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp index aa1777672a..3e24263c66 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp @@ -1,78 +1,89 @@ -// object_list, object_select, object_transform, part_add, object_arrange, plate_slice and job_cancel: the model on the plates, the -// arrange and Fill bed jobs, and the slice operation, which reports its own outcome per plate (see -// Operations/RunStatus). The object and part commands made from menu items: those that add a primitive, delete, rename, -// set the number of instances, make instances separate objects, split, assemble, order, mirror, centre, scale to fit, -// drop and orient objects and change a part's type take their targets (McpTargets.hpp) and run their operations -// (Operations/ObjectOps, ProjectOps); the others run their menu items' functions (NativeCommandMenuItems.hpp) on the selection. -// The object and part commands of menu items with no Speed Dial action, which mark objects printable, turn their Auto -// Drop on or off, repair their meshes, clone them, reload them from their files and replace a part's mesh, take their -// targets and run their operations too. +// The places Objects and Parts: the model on the plates. object_list, object_select, object_transform, part_add and +// object_arrange, with the arrange and Fill bed jobs. The object and part commands made from menu items: those that +// add a primitive, delete, rename, set the number of instances, make instances separate objects, split, assemble, +// order, mirror, centre, scale to fit, drop and orient objects and change a part's type take their targets +// (McpTargets.hpp) and run their operations (Operations/ObjectOps, ProjectOps); the others run their menu items' +// functions (NativeCommandMenuItems.hpp) on the selection. The object and part commands of menu items with no Speed +// Dial action, which mark objects printable, turn their Auto Drop on or off, repair their meshes, clone them, reload +// them from their files and replace a part's mesh, take their targets and run their operations too. +// +// The gizmo commands: a named target's gizmo opened on it (object_paint, object_measure, object_simplify, +// part_boolean, object_cut, object_lay_on_face, object_set_brim_ears). A call that names only its targets opens the +// gizmo and the client works it with the GUI tools; a command whose gizmo has an entry point that asks nothing also +// acts from its acting arguments (gizmo_acting_args()), with no gizmo: a cut by a plane, a lay on face by a +// direction, brim ears by position. +// +// object_set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier), given as +// the whole set of ranges, whose settings the settings tools set. object_set_variable_layer_height: the Variable +// layer height panel's Adaptive, Smooth and Reset on an object. And how object_list reports both. -#include "CanvasTarget.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "JobRegistry.hpp" -#include "McpCore.hpp" -#include "libslic3r/Config.hpp" -#include "libslic3r/Point.hpp" -#include "McpPaths.hpp" -#include "AutomationRuntime.hpp" -#include "McpArguments.hpp" -#include "McpTargets.hpp" -#include "McpTools.hpp" -#include "UiInspector.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/CanvasTarget.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GCodeViewer.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_Factories.hpp" #include "slic3r/GUI/GUI_Geometry.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" -#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/NotificationManager.hpp" #include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/Operations/GizmoOps.hpp" #include "slic3r/GUI/Operations/ObjectOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/Operations/ProjectOps.hpp" -#include "slic3r/GUI/Operations/RunStatus.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/Selection.hpp" #include "slic3r/Utils/UndoRedo.hpp" #include "libslic3r/BoundingBox.hpp" +#include "libslic3r/BrimEarsPoint.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" #include "libslic3r/EmbossShape.hpp" -#include "libslic3r/GCode/GCodeProcessor.hpp" -#include "libslic3r/GCode/GCodeStatistics.hpp" #include "libslic3r/Geometry.hpp" +#include "libslic3r/libslic3r.h" #include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Slicing.hpp" #include "libslic3r/TextConfiguration.hpp" #include "libslic3r/TextureDisplacement.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/TriangleSelector.hpp" -#include "libslic3r/Utils.hpp" -#include "libslic3r/libslic3r.h" -#include -#include #include #include -#include + +#include + +#include #include #include #include #include -#include #include #include #include @@ -81,17 +92,13 @@ #include #include #include +#include #include #include namespace Slic3r { namespace GUI { namespace Mcp { using nlohmann::json; -using Ops::PlateObservation; -using Ops::PlateOutcome; -using Ops::SliceObservation; -using Ops::SliceTicketState; -using Ops::TicketStatus; namespace { @@ -149,9 +156,9 @@ std::optional select_everything(GLCanvas3D& canvas) return std::nullopt; } -} // namespace - -// Refused in the assemble view, which shows another canvas, and while a gizmo owns the selection. +// The Prepare canvas, for edits made through the object list and the canvas selection as a person makes them: +// switches to it from another tab. Refused in the assemble view, which shows another canvas, and while a gizmo owns +// the selection. UI thread. GLCanvas3D& require_prepare_scene(Plater& plater) { if (GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); assemble != nullptr && plater.get_current_canvas3D() == assemble) @@ -166,6 +173,8 @@ GLCanvas3D& require_prepare_scene(Plater& plater) return canvas; } +} // namespace + // The 3D view then selects a part on instance 0, since nothing else is selected. void select_rows(ModelObject* object, ModelVolume* volume) { @@ -321,14 +330,6 @@ json list_objects(const json& args) return out; } -// The plate_slice tool's view of its request: slice_status()'s state, which adds when the tool started -// waiting to what the operation's ticket holds. -struct SliceTicket -{ - SliceTicketState state; - std::vector plates; -}; - // object_transform on an instance: written straight into the ModelInstance, then dropped, registered with // its plate and reloaded. Arguments are checked before anything changes. json transform_instance(Plater& plater, int oi, const json& args) @@ -681,6 +682,20 @@ json add_part(Plater& plater, int oi, const json& args) return {{"object", oi}, {"part", vi}, {"part_count", object->volumes.size()}, {"part_info", volume_info(*volume, vi)}}; } +// An object's height range modifiers as object_list and object_set_height_ranges report them: +// [{min_z, max_z, values: {key: value serialized as settings_get returns it}}], lowest first. +json layer_config_ranges_json(const t_layer_config_ranges& ranges) +{ + json out = json::array(); + for (const auto& [range, config] : ranges) { + json values = json::object(); + for (const std::string& key : config.keys()) + values[key] = config.opt_serialize(key); + out.push_back({{"min_z", range.first}, {"max_z", range.second}, {"values", std::move(values)}}); + } + return out; +} + } // namespace int instance_plate(PartPlateList& plates, int object, int instance) @@ -982,56 +997,6 @@ Vec3d size_factors(const Vec3d& current, const json& size) return given == 1 ? Vec3d::Constant(factors[axis]) : factors; } -json plate_summary(const json& statistics, const GCodeProcessorResult& result) -{ - const auto hundredths = [](double value) { return std::round(value * 100.) / 100.; }; - const json& summary = statistics.at("summary"); - const double seconds = summary.at("time").get(); - json out{{"time_s", std::lround(seconds)}, - {"time", get_time_dhms(float(seconds))}, - {"filament_g", hundredths(summary.at("weight").get())}, - {"filament_cost", summary.at("filament_cost")}, - {"layers", summary.at("layer_count")}, - {"filament_changes", summary.at("filament_changes")}}; - // The processor leaves the silent-mode time 0 when the printer has no such estimate. - const PrintEstimatedStatistics& estimates = result.print_statistics; - const double silent = estimates.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].time; - if (silent > 0.) - out["silent_time_s"] = std::lround(silent); - if (estimates.total_extruder_changes > 0) - out["extruder_changes"] = estimates.total_extruder_changes; - double max_z = 0.; - for (const json& layer : statistics.at("layers")) - max_z = std::max(max_z, layer.at("z").get()); - out["max_z"] = max_z; - - json filaments = json::array(); - const auto add_slot = [&filaments] { - filaments.push_back({{"slot", filaments.size() + 1}, {"m", 0.}, {"g", 0.}, {"model_g", 0.}, {"support_g", 0.}, - {"flush_g", 0.}, {"tower_g", 0.}}); - }; - while (filaments.size() < result.filaments_count) - add_slot(); - double length = 0.; - for (const json& used : summary.at("filaments")) { - const size_t slot = used.at("id").get(); - while (filaments.size() < slot) - add_slot(); - const auto grams = [&used, &hundredths](const char* use) { return hundredths(used.at(use).at("weight").get()); }; - json& f = filaments[slot - 1]; - f["m"] = hundredths(used.at("length").get() / 1000.); - f["g"] = hundredths(used.at("weight").get()); - f["model_g"] = grams("model"); - f["support_g"] = grams("support"); - f["flush_g"] = grams("flush"); - f["tower_g"] = grams("prime_tower"); - length += used.at("length").get(); - } - out["filament_m"] = hundredths(length / 1000.); - out["filaments"] = std::move(filaments); - return out; -} - namespace { // The Prepare view's selection, the view shown first when another is, as the object menu items read it: what a command made @@ -1097,6 +1062,7 @@ struct SplitRow Targets target; bool object_row = false; }; + Ops::Outcome split_row(bool to_objects) { Ops::show_prepare_view(); @@ -2150,7 +2116,7 @@ json fix_reply(const Model& model, const Ops::FixedModels& fixed) // The object and part commands of the GUI's menus that have no Speed Dial action: Printable, Auto Drop, Fix Model, // Clone, Reload from disk and Replace 3D file. Each reads its targets through resolve_targets() and runs its operation. -void register_object_tools(CommandCatalog& catalog) +void register_actionless_object_commands(CommandCatalog& catalog) { NativeCommand printable = reaching( {"set_objects_printable"}, @@ -2475,9 +2441,459 @@ void register_object_tools(CommandCatalog& catalog) catalog.add(std::move(replace)); } +using EType = GLGizmosManager::EType; + +// How a call's targets become what its gizmo opens on: `kinds` and `one` read them (resolve_targets()), and `to_gizmo` +// turns them into the selection the gizmo works on. +struct GizmoTargets +{ + unsigned kinds = kObjects; + bool one = true; + Targets (*to_gizmo)(const Model& model, Targets named) = nullptr; +}; + +// One instance of one object: the instance named, else the object's first. +Targets one_instance(const Model&, Targets named) +{ + if (!named.objects.empty()) { + named.instances = {{named.objects.front(), 0}}; + named.objects.clear(); + } + return named; +} + +// One part: the part named, else the only part of an object of one part. An object of several parts stays as it is, +// which the operation refuses as Simplify's panel would. +Targets one_part(const Model& model, Targets named) +{ + if (!named.objects.empty() && model.objects[std::size_t(named.objects.front())]->volumes.size() == 1) { + named.parts = {{named.objects.front(), 0}}; + named.objects.clear(); + } + return named; +} + +// Opens the gizmo of `type` on what `args` name, else on the selection as it is: a call that names no target does not +// read the selection as targets, so the gizmo's own condition decides what it opens on (Measure on a part). The reply +// is the gizmo, that it is open, and what is selected. +json open_on(const json& args, EType type, const GizmoTargets& reading) +{ + Plater& plater = ui_plater(); + Ops::OpenGizmoArgs op; + op.type = type; + if (names_targets(args)) { + const Ops::Outcome named = resolve_targets(plater.model(), nullptr, args, reading.kinds, reading.one); + if (!named) + throw refused(named.refusal()); + op.targets = reading.to_gizmo != nullptr ? reading.to_gizmo(plater.model(), named.value()) : named.value(); + } else + op.targets.from_selection = true; + const Ops::Outcome opened = Ops::open_gizmo(op); + if (!opened) + throw refused(opened.refusal()); + json reply = targets_reply(plater.model(), opened.value().on); + reply["gizmo"] = gizmo_name(int(type)); + reply["active"] = true; + return reply; +} + +// What every gizmo command's description says of working the open gizmo. +const char* const kWorkTheGizmo = + " Read the gizmo's panel with `widget_list {include_imgui: true}`, set its fields with `widget_set_value`, press its " + "buttons with `widget_click`, and click or drag on the model with `mouse_gesture`; `object_select {none: true}` closes it. " + "The gizmo already open on the same target stays open. Reply: gizmo (its name, as `app_state.gizmo` gives it), active, " + "and what is selected (objects, instances, parts)."; + +// Whether a call of `command` gives one of its acting arguments, and so does the job with no gizmo. +bool acts(const json& args, const std::string& command) +{ + for (const std::string& name : gizmo_acting_args(command)) + if (args.contains(name)) + return true; + return false; +} + +Ops::CutPlacement placement(const std::string& name) +{ + return name == "as_cut" ? Ops::CutPlacement::AsCut : name == "flip" ? Ops::CutPlacement::Flip : Ops::CutPlacement::PlaceOnCut; +} + +// What an object of the model is in a cut's reply: its index, id and name, and the open edges its parts have, which +// object_fix repairs. +json piece(const Model& model, int index) +{ + const ModelObject& object = *model.objects[std::size_t(index)]; + std::size_t open_edges = 0; + for (const ModelVolume* volume : object.volumes) + open_edges += its_num_open_edges(volume->mesh().its); + return {{"index", index}, {"object_id", object.id().id}, {"name", object.name}, {"open_edges", open_edges}}; +} + +// The one instance a gizmo command acts on: the instance or object named (the object's first instance), else the one +// selected. +std::pair acted_on(Plater& plater, const json& args) +{ + const Ops::Outcome named = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, + kObjects | kInstances, true); + if (!named) + throw refused(named.refusal()); + return one_instance(plater.model(), named.value()).instances.front(); +} + +// object_cut from its acting arguments. The arguments the Cut gizmo's panel could not set together are refused before +// anything is read: z with plane, a placement for a piece not kept, and placements or one piece with Cut to parts. +json cut_from_args(const json& args) +{ + if (args.contains("z") && args.contains("plane")) + throw ToolFailure("Give z or plane, not both."); + if (!args.contains("z") && !args.contains("plane")) + throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_plane", + L("A cut needs its plane: give z or plane with keep, upper, lower or to_parts.")}); + Ops::CutObjectArgs op; + if (args.contains("plane")) { + op.point = to_vec3(args["plane"]["point"], "plane.point"); + op.normal = to_vec3(args["plane"]["normal"], "plane.normal"); + if (op.normal.norm() < EPSILON) + throw ToolFailure("plane.normal is zero: give the direction the upper piece lies in."); + } + const std::string keep = args.value("keep", std::string("both")); + op.keep_upper = keep != "lower"; + op.keep_lower = keep != "upper"; + if (args.contains("upper") && !op.keep_upper) + throw ToolFailure("upper places the upper piece, but the upper piece is not kept (keep \"lower\")."); + if (args.contains("lower") && !op.keep_lower) + throw ToolFailure("lower places the lower piece, but the lower piece is not kept (keep \"upper\")."); + op.to_parts = args.value("to_parts", false); + if (op.to_parts && keep != "both") + throw ToolFailure("to_parts keeps both pieces, as two parts of one object; leave keep out."); + if (op.to_parts && (args.contains("upper") || args.contains("lower"))) + throw ToolFailure("to_parts places no piece: both stay as cut; leave upper and lower out."); + if (args.contains("upper")) + op.upper = placement(args["upper"].get()); + if (args.contains("lower")) + op.lower = placement(args["lower"].get()); + + Plater& plater = ui_plater(); + std::tie(op.object, op.instance) = acted_on(plater, args); + if (args.contains("z")) { + // A level plane that high above the bed, through the instance. + op.point = plater.model().objects[std::size_t(op.object)]->instances[std::size_t(op.instance)]->get_offset(); + op.point.z() = args["z"].get(); + op.normal = Vec3d::UnitZ(); + } + + const Ops::Outcome cut = Ops::cut_object(op); + if (!cut) + throw refused(cut.refusal()); + const Model& model = plater.model(); + json reply; + if (op.to_parts) { + reply["object"] = piece(model, cut.value().objects.front()); + reply["parts"] = targets_reply(model, cut.value()).value("parts", json::array()); + } else { + reply["pieces"] = json::array(); + for (int index : cut.value().objects) + reply["pieces"].push_back(piece(model, index)); + } + return reply; +} + +// object_lay_on_face from its acting arguments. +json lay_from_args(const json& args) +{ + if (!args.contains("normal")) + throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_normal", + L("Laying an object on a face needs the face's direction: give normal with frame.")}); + Plater& plater = ui_plater(); + Ops::LayOnFaceArgs op; + std::tie(op.object, op.instance) = acted_on(plater, args); + op.normal = to_vec3(args["normal"], "normal"); + op.world = args.value("frame", std::string("object")) == "world"; + const Ops::Outcome turned = Ops::lay_on_face(op); + if (!turned) + throw refused(turned.refusal()); + const Vec3d degrees = turned.value() * (180. / PI); + return {{"object", op.object}, {"instance", op.instance}, {"rotation", {degrees.x(), degrees.y(), degrees.z()}}}; +} + +// object_set_brim_ears from its acting arguments. +json brim_ears_from_args(const json& args) +{ + if (args.contains("points") && args.contains("clear")) + throw ToolFailure("Give points or clear, not both."); + Plater& plater = ui_plater(); + Ops::SetBrimEarsArgs op; + std::tie(op.object, op.instance) = acted_on(plater, args); + for (const json& point : args.value("points", json::array())) { + const json& at = point.at("position"); + if (!at.is_array() || at.size() != 2) + throw ToolFailure("points[].position must be [x, y]"); + Ops::BrimEar ear; + ear.position = Vec2d(at[0].get(), at[1].get()); + if (point.contains("radius")) + ear.radius = point["radius"].get(); + op.ears.push_back(ear); + } + const Ops::Outcome set = Ops::set_brim_ears(op); + if (!set) + throw refused(set.refusal()); + json ears = json::array(); + for (const BrimPoint& ear : set.value().ears) + ears.push_back({{"position", {ear.pos.x(), ear.pos.y(), ear.pos.z()}}, {"radius", ear.head_front_radius}}); + return {{"object", op.object}, {"ears", std::move(ears)}, {"brim_type", set.value().brim_type}, + {"takes_effect", set.value().takes_effect}}; +} + +NativeCommand gizmo_command(std::string name, std::string title, std::string description, json schema, EType type, + GizmoTargets reading, json examples) +{ + NativeCommand command = with_target_ids(mutate_tool(std::move(name), std::move(title), description + kWorkTheGizmo, + std::move(schema), [type, reading](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { return open_on(args, type, reading); }); + settle(ctx); + return ToolResult::ok(out); + })); + command.examples = std::move(examples); + return reaching({"open_gizmo"}, std::move(command)); +} + +// The painting gizmos, by object_paint's type. +const std::vector> kPaintTypes{ + {"supports", EType::FdmSupports}, {"seam", EType::Seam}, {"color", EType::MmSegmentation}, {"fuzzy_skin", EType::FuzzySkin}}; + } // namespace -void register_scene_tools(CommandCatalog& catalog) +const std::vector& gizmo_acting_args(const std::string& command) +{ + // The gizmo commands' acting arguments: a call with any of them does the job and opens no gizmo. + static const std::map> acting{ + {"object_paint", {}}, {"object_measure", {}}, {"object_simplify", {}}, {"part_boolean", {}}, + {"object_cut", {"z", "plane", "keep", "upper", "lower", "to_parts"}}, + {"object_lay_on_face", {"normal", "frame"}}, + {"object_set_brim_ears", {"points", "clear"}}}; + static const std::vector none; + const auto found = acting.find(command); + return found != acting.end() ? found->second : none; +} + +namespace { + +ToolFailure overlap(const Slic3r::t_layer_height_range& lower, const Slic3r::t_layer_height_range& upper) +{ + return ToolFailure("Ranges " + height_range_text(lower) + " and " + height_range_text(upper) + + " overlap; ranges may touch, one's max_z being the next one's min_z"); +} + +bool same_ranges(const t_layer_config_ranges& a, const t_layer_config_ranges& b) +{ + return a.size() == b.size() && + std::equal(a.begin(), a.end(), b.begin(), [](const auto& x, const auto& y) { return x.first == y.first && x.second.get() == y.second.get(); }); +} + +// What the GUI tells a person about an object's layer heights, as warnings: the dialog it shows before +// variable layer heights or height ranges when the process mixes colours in sublayers, and what the +// object list's variable layer height mark implies for the ranges. +json layer_height_warnings(const ModelObject& object) +{ + json warnings = json::array(); + const bool variable = !layer_height_profile_json(object.layer_height_profile.get()).is_null(); + if (!variable && object.layer_config_ranges.empty()) + return warnings; + const auto* mixed = wxGetApp().preset_bundle->prints.get_edited_preset().config.option("enable_mixed_color_sublayer"); + if (mixed != nullptr && mixed->value) + warnings.push_back("Using variable layer height together with mixed color sublayer may result in poor color mixing quality."); + if (variable && !object.layer_config_ranges.empty()) + warnings.push_back("The object's variable layer height profile, not the ranges' layer_height, decides its layer heights."); + return warnings; +} + +// The index of the object a layer call names, else of the one selected in the Prepare view (or of the object of the +// selected instance or part), on an FFF printer. +int layer_object(Plater& plater, const json& args) +{ + if (plater.printer_technology() != ptFFF) + throw ToolFailure("Height range modifiers and variable layer heights are for FFF printers"); + const Ops::Outcome target = + resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, kObjects | kObjectOfSelection, true); + if (!target) + throw refused(target.refusal()); + return target.value().objects.front(); +} + +// The reply's naming of object `oi`, as every command with a target gives it. +json named_object(const Plater& plater, int oi) +{ + Ops::Targets object; + object.objects = {oi}; + return targets_reply(plater.model(), object); +} + +// The object object_set_variable_layer_height names, or the one selected, after the checks that need no view, such as +// an argument that goes with another action. +int profile_object(Plater& plater, const json& args) +{ + const int oi = layer_object(plater, args); + const std::string action = arg_string(args, "action"); + if (args.contains("quality") && action != "adaptive") + throw ToolFailure("quality goes with action adaptive"); + if ((args.contains("radius") || args.contains("keep_min")) && action != "smooth") + throw ToolFailure("radius and keep_min go with action smooth"); + return oi; +} + +// What the panel's Adaptive, Smooth and Reset buttons run, on the object selected as the panel's +// object is, without opening the panel. Reset of an object without a profile changes nothing. +json set_variable_layer_height(Plater& plater, const json& args) +{ + const int oi = profile_object(plater, args); + ModelObject& object = *plater.model().objects[std::size_t(oi)]; + const std::string action = arg_string(args, "action"); + GLCanvas3D& canvas = require_prepare_scene(plater); + + if (action != "reset" || !object.layer_height_profile.empty()) { + select_rows(&object, nullptr); + // The rule that enables the toolbar's Variable layer height item, with the reason it fails. + if (!plater.can_layers_editing()) + throw ToolFailure(object.max_z() <= SINKING_Z_THRESHOLD ? + "object " + std::to_string(oi) + " is below the bed, where its layer heights can't be edited" : + !canvas.is_layers_editing_allowed() ? + "The variable layer height tool needs an OpenGL shader that this system did not load" : + "object " + std::to_string(oi) + " could not be selected for the variable layer height tool"); + if (action == "adaptive") + canvas.adaptive_layer_height_profile(float(arg_double(args, "quality", 0.5))); + else if (action == "smooth") + canvas.smooth_layer_height_profile(HeightProfileSmoothingParams(unsigned(arg_int(args, "radius", 5)), arg_bool(args, "keep_min", false))); + else + canvas.reset_layer_height_profile(); + } + + json out = named_object(plater, oi); + out.update({{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}}); + if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null()) + out["layer_height_profile"] = std::move(profile); + if (json warnings = layer_height_warnings(object); !warnings.empty()) + out["warnings"] = std::move(warnings); + return out; +} + +// What the object list does when a person adds and removes ranges, with the whole set given at once, on the object the +// call names or the one selected. A range's settings are the settings tools' (target height_range). Everything the +// arguments can tell is checked before anything changes. +json set_height_ranges(Plater& plater, const json& args) +{ + const int oi = layer_object(plater, args); + ModelObject* object = plater.model().objects[std::size_t(oi)]; + ObjectList* list = wxGetApp().obj_list(); + t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), object->layer_config_ranges, + list->get_default_layer_config(oi)); + require_prepare_scene(plater); + + if (!same_ranges(ranges, object->layer_config_ranges)) { + // The object's row, as right-clicking it selects it, so no row or sidebar editor of the old ranges + // stays in use while they are replaced. + select_rows(object, nullptr); + plater.take_snapshot("Edit height ranges"); + object->layer_config_ranges = std::move(ranges); + list->reload_layer_rows(oi); + plater.changed_object(oi); + } + + json out = named_object(plater, oi); + out.update({{"object", oi}, + {"height", object->instance_bounding_box(0).max.z()}, + {"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}}); + if (json warnings = layer_height_warnings(*object); !warnings.empty()) + out["warnings"] = std::move(warnings); + return out; +} + +} // namespace + +std::string height_range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); } + +std::vector layer_range_option_keys(int filaments) +{ + // A range's page in the sidebar edits layer_height and the per-region settings, of which the object + // list's Add settings menus offer a part or a range those with a category (no internal option), + // leaving out support settings, and per-feature filaments and wipe options while there is one + // filament (SettingsFactory's is_improper_category()). + std::vector keys{"layer_height"}; + for (const std::string& key : PrintRegionConfig().keys()) { + const ConfigOptionDef* def = print_config_def.get(key); + if (def == nullptr || def->category.empty() || def->category == "Support material" || + (filaments == 1 && (def->category == "Extruders" || def->category == "Wipe options"))) + continue; + keys.push_back(key); + } + // The filament column of a range's row. + keys.push_back("extruder"); + return keys; +} + +t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, + const t_layer_config_ranges& current, + const DynamicPrintConfig& defaults) +{ + if (!ranges.is_array()) + throw ToolFailure("ranges must be a list of {min_z, max_z}"); + t_layer_config_ranges out; + for (const json& r : ranges) { + if (!r.is_object()) + throw ToolFailure("A range is {min_z, max_z}"); + const Slic3r::t_layer_height_range range{arg_double(r, "min_z", -1.), arg_double(r, "max_z", -1.)}; + if (!(range.first >= 0. && range.first < range.second)) + throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + height_range_text(range)); + if (out.count(range) != 0) + throw overlap(range, range); + // A range of the object's with these heights keeps its settings, as the object list keeps a range it is not asked + // to change. + const auto kept = current.find(range); + if (kept != current.end()) + out[range].assign_config(kept->second.get()); + else + out[range].assign_config(defaults); + } + // Sorted by min_z; the slicer would trim an overlap silently, which from an agent is always a mistake. + const Slic3r::t_layer_height_range* lower = nullptr; + for (const auto& entry : out) { + if (lower != nullptr && entry.first.first + EPSILON < lower->second) + throw overlap(*lower, entry.first); + lower = &entry.first; + } + return out; +} + +void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range, + const std::function(int extruder)>& layer_height_bounds) +{ + // Only a layer height given is checked, as the range editor checks only what a person types. + if (!values.has("layer_height")) + return; + const DynamicPrintConfig& source = values.has("extruder") ? values : range; + const int extruder = source.has("extruder") ? source.opt_int("extruder") : 0; + const double height = values.opt_float("layer_height"); + const std::pair bounds = layer_height_bounds(extruder); + if (!(height >= bounds.first && height <= bounds.second)) + throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second)); +} + +json layer_height_profile_json(const std::vector& profile) +{ + // The object list marks an object's layer height as variable when its profile is more than a flat + // bottom-to-top pair. + if (profile.size() <= 4) + return nullptr; + double low = profile[1], high = profile[1]; + for (std::size_t i = 3; i < profile.size(); i += 2) { + low = std::min(low, profile[i]); + high = std::max(high, profile[i]); + } + // Computed heights, to the G-code's 0.001 mm. + const auto um = [](double h) { return std::round(h * 1000.) / 1000.; }; + return {{"points", profile.size() / 2}, {"min_height", um(low)}, {"max_height", um(high)}}; +} + +void register_object_tools(CommandCatalog& catalog) { catalog.add(inspect_tool( "object_list", L("List objects"), @@ -2692,7 +3108,7 @@ void register_scene_tools(CommandCatalog& catalog) }))); register_object_menu_commands(catalog); - register_object_tools(catalog); + register_actionless_object_commands(catalog); NativeCommand arrange = reaching({"start_arrange"}, mutate_tool( "object_arrange", L("Arrange objects or fill the bed"), @@ -2756,189 +3172,225 @@ void register_scene_tools(CommandCatalog& catalog) with_target_ids(std::move(arrange)), [](const json&) { return MenuItems::obj_arrange(); }, /*person_form_behind_dialogs=*/false, std::vector{json::object()})); - NativeCommand slice = reaching({"start_slice"}, mutate_tool( - "plate_slice", L("Slice"), - "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for " - "the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok, " - "error, cancelled, empty or skipped; the whole operation is superseded when someone else started a slice or " - "edited the project while it ran. An ok plate has `time_s` (`silent_time_s` when the printer estimates it), " - "`filament_m` and `filament_g` including flush, `filament_cost`, layers, `max_z`, `filament_changes`, and filaments[i] for " - "slot i+1 with m, g and the grams of `model_g`, `support_g`, `flush_g` and `tower_g`. Other changes are refused until it " - "finishes; `job_cancel` stops it. The Preview tab shows the result, as after the Slice button; `preview: true`, alone " - "or with plates \"all\", is the call of Slice and Preview or Slice All Plates, whose pick starts the slice as a job " - "and shows its result as a notification.", - object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), \"all\", or a plate index."}}}, - {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless `job_cancel` stops it."}}}, - {"preview", prop("boolean", "Show the Preview tab, as every slice does: the argument of the Slice and " - "Preview and Slice All Plates actions.")}}), + std::vector paint_types; + for (const auto& [name, type] : kPaintTypes) + paint_types.push_back(name); + NativeCommand paint = with_target_ids(mutate_tool( + "object_paint", L("Paint on an object"), + std::string("Open a painting gizmo on an object's instance, the first unless instance is given: type supports opens " + "Support Painting, seam Seam Painting, color Color Painting (two filaments or more) and `fuzzy_skin` Paint-on " + "fuzzy skin. Painting is left to the gizmo: pick a tool and a brush in its panel and paint with " + "`mouse_gesture` strokes on the model. With no target, it opens on the selection as it is.") + + kWorkTheGizmo, + with_targets(object_schema({{"type", enum_prop(paint_types, "The painting gizmo to open.")}}, {"type"}), kObjects | kInstances, true), [](const json& args, ToolContext& ctx) { - const json plates_arg = args.value("plates", json("current")); - if (plates_arg.is_string() && plates_arg != "all" && plates_arg != "current") - throw ToolFailure("plates is \"all\", \"current\" or a plate index"); - auto ticket = std::make_shared(); - // Held from before the wait below, so no call admitted meanwhile can change the project - // under the slice, and a cancel meanwhile finds the operation. - const uint64_t cancels_before = ctx.run_ui([&] { - ctx.begin_operation(); - return json(ui_plater().slice_cancel_seq()); - }).get(); - // A change made just before (settings_set, project_open) is validated by an update - // scheduled a moment later; a slice requested first would be refused on the old state. + EType type = EType::FdmSupports; + for (const auto& [name, t] : kPaintTypes) + if (name == args.value("type", std::string())) + type = t; + json out = ctx.run_ui([&] { return open_on(args, type, {kObjects | kInstances, true, one_instance}); }); + settle(ctx); + return ToolResult::ok(out); + })); + paint.examples = json::parse(R"json([ + {"title": "Paint support enforcers on object 0", "calls": [ + {"tool": "object_paint", "args": {"object": 0, "type": "supports"}}]}, + {"title": "Paint colors on the second instance of object 1", "calls": [ + {"tool": "object_paint", "args": {"object": 1, "instance": 1, "type": "color"}}]}])json"); + catalog.add(reaching({"open_gizmo"}, std::move(paint))); + + catalog.add(gizmo_command( + "object_measure", L("Measure"), + "Open the Measure gizmo on objects, else on the selection as it is (a part selected is measured as a part). " + "Measuring is left to the gizmo: click two features of the model with `mouse_gesture` (Shift-click for a point) and " + "read the results in its panel.", + with_targets(object_schema({}), kObjects, false), EType::Measure, {kObjects, false, nullptr}, + json::parse(R"json([ + {"title": "Measure between objects 0 and 1", "calls": [{"tool": "object_measure", "args": {"objects": [0, 1]}}]}, + {"title": "Measure the selected part", "calls": [ + {"tool": "object_select", "args": {"parts": [[0, 1]]}}, {"tool": "object_measure", "args": {}}]}])json"))); + + catalog.add(gizmo_command( + "object_simplify", L("Simplify Model"), + "Open the Simplify gizmo on a part: the part named, else the only part of the object named (an object of several " + "parts needs part), else the selected part. The detail level or ratio and Apply are left to the gizmo.", + with_targets(object_schema({}), kObjects | kParts, true), EType::Simplify, {kObjects | kParts, true, one_part}, + json::parse(R"json([ + {"title": "Simplify object 0, an object of one part", "calls": [{"tool": "object_simplify", "args": {"object": 0}}]}, + {"title": "Simplify part 1 of object 2", "calls": [{"tool": "object_simplify", "args": {"object": 2, "part": 1}}]}])json"))); + + catalog.add(gizmo_command( + "part_boolean", L("Mesh Boolean"), + "Open the Mesh Boolean gizmo on an object of two parts or more, its first instance. The operation (Union, Difference " + "or Intersection), the two parts and Delete input are left to the gizmo: pick each part with a `mouse_gesture` click " + "on a point of it the camera can see, then press the operation's button.", + with_targets(object_schema({}), kObjects, true), EType::MeshBoolean, {kObjects, true, one_instance}, + json::parse(R"json([ + {"title": "Open Mesh Boolean on object 0", "calls": [{"tool": "part_boolean", "args": {"object": 0}}]}, + {"title": "Open Mesh Boolean on the selected object", "calls": [{"tool": "part_boolean", "args": {}}]}])json"))); + + const std::vector placements{"as_cut", "place_on_cut", "flip"}; + json point = array_prop({{"type", "number"}}, "`[x, y, z]` mm: a point of the plane, in the 3D view's coordinates."); + json normal = array_prop({{"type", "number"}}, "`[x, y, z]`: the direction the upper piece lies in; any length but zero."); + point["minItems"] = normal["minItems"] = 3; + json plane = object_schema({{"point", std::move(point)}, {"normal", std::move(normal)}}, {"point", "normal"}); + plane["description"] = "Cut along this plane. Not with z."; + NativeCommand cut = with_target_ids(mutate_tool( + "object_cut", L("Cut"), + std::string( + "Cut an object's instance, the first unless instance is given, along a plane, as the Cut gizmo's Perform cut does. " + "Acts from arguments: `z`, `plane`, `keep`, `upper`, `lower`, `to_parts`. With none of them it opens the Cut gizmo. z cuts " + "level, that many mm above the bed; plane `{point, normal}` cuts along any plane, the upper piece being the one " + "the normal points into. keep: both (default), upper or lower. upper and lower place a kept piece: `as_cut`, " + "`place_on_cut` (laid on its cut face) or flip; by default the upper piece is laid on its cut face and the lower " + "one stays as cut. `to_parts` keeps both pieces as two parts of one object, with no placement. A cut is one undo " + "step and replaces the object: its pieces go to the end of the object list, upper first, and the reply gives " + "them as pieces [`{index, object_id, name, open_edges}`], or with `to_parts` the object and its parts. A piece with " + "open edges is repaired by `object_fix`. Connectors, the dovetail and a cut along a contour are left to the gizmo: " + "open it with `object_cut` naming only the object.") + + kWorkTheGizmo, + with_targets(object_schema({{"z", prop("number", "mm above the bed: cut level at this height. Not with plane.")}, + {"plane", std::move(plane)}, + {"keep", enum_prop({"both", "upper", "lower"}, "The pieces kept. Default both.")}, + {"upper", enum_prop(placements, "Where the upper piece goes. Default `place_on_cut`.")}, + {"lower", enum_prop(placements, "Where the lower piece goes. Default `as_cut`.")}, + {"to_parts", prop("boolean", "Keep both pieces as two parts of one object, as the gizmo's " + "Cut to parts does. Default false.")}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_cut") ? cut_from_args(args) : open_on(args, EType::Cut, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + cut.examples = json::parse(R"json([ + {"title": "Cut object 0 in two, 10 mm above the bed", "calls": [{"tool": "object_cut", "args": {"object": 0, "z": 10}}]}, + {"title": "Keep the part of object 1 above a tilted plane", "calls": [ + {"tool": "object_cut", "args": {"object": 1, "plane": {"point": [100, 100, 10], "normal": [1, 0, 1]}, "keep": "upper"}}]}])json"); + catalog.add(reaching({"open_gizmo", "cut_object"}, std::move(cut))); + + NativeCommand lay = with_target_ids(mutate_tool( + "object_lay_on_face", L("Lay on face"), + std::string( + "Lay an object's instance, the first unless instance is given, on one of its faces, as a click on that face in " + "the Lay on Face gizmo does. Acts from arguments: `normal`, `frame`. With none of them it opens the Lay on Face " + "gizmo. normal is the direction the face points out to: in the object's own frame (frame object, the default, " + "where `[0, 0, -1]` is the face that was its bottom) or in the 3D view's (frame world, where the face points now). " + "The instance turns so that face lies on the bed and drops onto it, one undo step; the object's other instances " + "turn with it. No flat face is looked for: the direction is laid down as given. A call that acts replies object, " + "instance and rotation, the instance's rotation in degrees as `object_list` gives it.") + + kWorkTheGizmo, + with_targets(object_schema({{"normal", array_prop({{"type", "number"}}, "`[x, y, z]`: the direction the face to lay on the bed " + "points out to; any length but zero.")}, + {"frame", enum_prop({"object", "world"}, "The frame normal is in: the object's own (default) or " + "the 3D view's. Needs normal.")}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_lay_on_face") ? lay_from_args(args) : + open_on(args, EType::Flatten, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + lay.examples = json::parse(R"json([ + {"title": "Lay object 0 on the face that points down in its own frame", "calls": [ + {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [0, 0, -1]}}]}, + {"title": "Lay object 0 on the face that now points to +X", "calls": [ + {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [1, 0, 0], "frame": "world"}}]}])json"); + catalog.add(reaching({"open_gizmo", "lay_on_face"}, std::move(lay))); + + json ear = object_schema({{"position", array_prop({{"type", "number"}}, "`[x, y]` mm: where on the bed.")}, + {"radius", prop("number", "mm. Default: the gizmo's, eight first-layer line widths.")}}, + {"position"}); + NativeCommand brim = with_target_ids(mutate_tool( + "object_set_brim_ears", L("Brim ears"), + std::string( + "Set an object's brim ears from positions on the bed, as the Brim Ears gizmo places them, through the instance " + "named, the first unless instance is given. Acts from arguments: `points`, `clear`. With none of them it opens the " + "Brim Ears gizmo. points replaces the object's ears with those given, each at a bed position, with a radius " + "from 0.1 to 100 mm or the gizmo's default; clear removes them all. The ears are taken on the bed and stored in " + "the object's coordinates, so they are the object's, shared by its instances. One undo step. They print only " + "with the painted brim type: `settings_set` on the object sets `brim_type`. A call that acts replies object, ears " + "as stored ({position: `[x, y, z]` in the object's coordinates, radius}), `brim_type`, the brim type the object " + "prints with, and `takes_effect`, whether that is painted.") + + kWorkTheGizmo, + with_targets(object_schema({{"points", array_prop(std::move(ear), "The ears, in place of the object's.")}, + {"clear", {{"type", "boolean"}, {"enum", {true}}, {"description", "Remove every ear. Not with points."}}}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_set_brim_ears") ? brim_ears_from_args(args) : + open_on(args, EType::BrimEars, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + brim.examples = json::parse(R"json([ + {"title": "Paint object 0's brim as two ears at its front corners", "calls": [ + {"tool": "settings_set", "args": {"target": "object", "object": 0, "values": {"brim_type": "painted"}}}, + {"tool": "object_set_brim_ears", "args": {"object": 0, "points": [{"position": [90, 90], "radius": 3}, {"position": [110, 90]}]}}]}, + {"title": "Remove object 1's ears", "calls": [{"tool": "object_set_brim_ears", "args": {"object": 1, "clear": true}}]}])json"); + catalog.add(reaching({"open_gizmo", "set_brim_ears"}, std::move(brim))); + + const json range = object_schema({{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}}, + {"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}}, + {"min_z", "max_z"}); + + catalog.add(with_target_ids(mutate_tool( + "object_set_height_ranges", L("Set height range modifiers"), + "Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed " + "with its own `layer_height`, filament and process settings, which `settings_get` and `settings_set` read and write with " + "the target `height_range`. A range given with the `min_z` and `max_z` of one the object has keeps its settings; a new " + "one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. " + "The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. " + "Reply: the object (objects, object), its height and its ranges as `object_list` shows them, with their settings, and " + "warnings, such as a variable layer height profile deciding the layer heights instead.", + with_targets(object_schema({{"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, {"ranges"}), kObjects, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { return set_height_ranges(ui_plater(), args); }); + settle(ctx); + return ToolResult::ok(out); + }))); + + catalog.add(with_target_ids(mutate_tool( + "object_set_variable_layer_height", L("Set a variable layer height profile"), + "Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive " + "computes layer heights from the object's shape (inside a height range, the range's `layer_height`), smooth smooths " + "its profile (or the one its height ranges give), reset goes back to its layer height and ranges. The object is " + "the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the " + "object (objects, object), its height, its `layer_height_profile {points, min_height, max_height}` as `object_list` " + "shows it (absent after reset), and warnings.", + with_targets(object_schema({{"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")}, + {"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1}, + {"description", "`adaptive`: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}}, + {"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}}, + {"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}}, + {"action"}), + kObjects, true), + [](const json& args, ToolContext& ctx) { + // Refused calls leave the view alone. The Prepare canvas edits layer heights only once it has drawn: + // GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home. The object is read once, + // before the wait, and named in the call that follows it. + json call = args; + ctx.run_ui([&] { + Plater& plater = ui_plater(); + call["object"] = profile_object(plater, args); + require_prepare_scene(plater); + return json(); + }); poll_ui( ctx, - [cancels_before]() -> json { - const Plater& plater = ui_plater(); - const bool pending = plater.is_background_process_update_scheduled(); - return pending && plater.slice_cancel_seq() == cancels_before ? json() : json(true); + []() -> json { + const GLCanvas3D* canvas = ui_plater().canvas3D(); + return canvas->is_initialized() && !canvas->is_reload_delayed() ? json(true) : json(); }, - std::chrono::seconds(10), "the pending update of the slicing state"); - const bool cancelled = ctx.run_ui([&] { - Plater& plater = ui_plater(); - Ops::SliceArgs slice; - slice.all_plates = plates_arg.is_string() && plates_arg.get() == "all"; - if (plates_arg.is_number_integer()) - slice.plate = plates_arg.get(); - const Ops::Outcome> plates = Ops::slice_plates(slice); - if (!plates) - throw refused(plates.refusal()); - ticket->plates = plates.value(); - // A cancel that came while the update was pending stops the slice before it starts. - if (plater.slice_cancel_seq() != cancels_before) - return json(true); - ticket->state.started = std::chrono::steady_clock::now(); - const Ops::Outcome started = Ops::start_slice(slice); - if (!started) - throw refused(started.refusal()); - ticket->state.run_seq_before = started.value().run_seq_before; - ticket->state.revision_at_start = started.value().revision; - ticket->state.request_seq_mine = started.value().request_seq; - ticket->state.seen_running = started.value().slicing; - ticket->state.adopted_run = started.value().adopted_run; - return json(false); - }).get(); - if (cancelled) { - json plates = json::array(); - for (int index : ticket->plates) - plates.push_back({{"index", index}, {"outcome", to_string(PlateOutcome::Cancelled)}}); - return ToolResult::ok({{"status", "done"}, {"plates", std::move(plates)}}); - } - const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 1800)); - json result = poll_ui( - ctx, - [ticket]() -> json { - Plater& plater = ui_plater(); - SliceObservation obs; - obs.slicing_any = plater.is_slicing_any(); - obs.request_seq = plater.slice_request_seq(); - obs.interrupted = plater.slice_request_interrupted(ticket->state.request_seq_mine); - obs.current_revision = plater.project_revision(); - const uint64_t first = ticket->state.adopted_run != 0 ? ticket->state.adopted_run : ticket->state.run_seq_before + 1; - for (uint64_t seq = first; seq <= plater.slice_run_seq(); ++seq) - if (auto run = plater.slice_run(seq)) - obs.runs_since_start.push_back({run->seq, run->finished, run->cancelled, run->ok, run->error, - run->revision_at_finish, run->request_seq_at_finish, - run->request_seq_at_start, run->for_request, run->plate}); - ticket->state.seen_running = ticket->state.seen_running || obs.slicing_any || !obs.runs_since_start.empty(); - const TicketStatus status = slice_status(ticket->state, obs, std::chrono::steady_clock::now()); - if (status == TicketStatus::Pending) - return json(); - json out{{"status", status == TicketStatus::Done ? "done" : "superseded"}}; - PartPlateList& list = plater.get_partplate_list(); - std::vector observed; - for (int index : ticket->plates) - if (PartPlate* plate = list.get_plate(index)) - observed.push_back({index, plate->is_slice_result_valid(), !plate->has_printable_instances(), - plater.plate_validation_error(index)}); - const auto results = classify_plates(ticket->plates, observed, own_runs(ticket->state, obs)); - json plates = json::array(); - for (size_t i = 0; i < ticket->plates.size(); ++i) { - json p{{"index", ticket->plates[i]}, {"outcome", to_string(results[i].outcome)}}; - if (results[i].outcome == PlateOutcome::Ok) { - // The statistics are the plate's current result, so only while the - // project is as the operation sliced it and nobody sliced the plate since. - // They are read in this closure, which decides the outcome, since a later UI - // call would wait behind the preview's loading of the new result; the - // serializer's one pass over the moves is short next to that. - PartPlate* plate = list.get_plate(ticket->plates[i]); - const GCodeProcessorResult* gcode = plate != nullptr ? plate->get_slice_result() : nullptr; - if (gcode != nullptr && plate->is_slice_result_valid() && - plater.project_revision() == ticket->state.revision_at_start && - plate_result_is_own(ticket->plates[i], ticket->state, obs)) - p.update(plate_summary(json::parse(gcode_statistics_json(*gcode)), *gcode)); - else - p["note"] = "The plate changed after it was sliced; slice again for its statistics."; - } - if (!results[i].error.empty()) - p["error"] = results[i].error; - plates.push_back(std::move(p)); - } - out["plates"] = std::move(plates); - json notes = json::array(); - for (const NotificationSummary& n : plater.get_notification_manager()->summaries()) - if (n.level == "warning" || n.level == "error") - notes.push_back({{"level", n.level}, {"text", n.text}}); - if (!notes.empty()) - out["notifications"] = std::move(notes); - return out; - }, - timeout, "slicing to finish"); - return ToolResult::ok(result); - })); - slice.budget_ms = 45000; - slice.actions = json::array( - {NativeCommands::action("slice_and_preview", L("Slice and Preview"), L("Slice & Export"), "media_play", {{"preview", true}}, - "Slice the current plate and show the Preview tab; the call waits for the result, and a pick starts " - "the slice as a job."), - NativeCommands::action("slice_all", L("Slice All Plates"), L("Slice & Export"), "media_play", - {{"plates", "all"}, {"preview", true}}, - "Slice every plate and show the Preview tab; the call waits for the results, and a pick starts the " - "slice as a job.")}); - catalog.add(std::move(slice)); - - NativeCommand cancel = mutate_tool( - "job_cancel", L("Cancel a job"), - "Stop the running operation: a slice or G-code export, as the slicing progress's cancel button does, or a " - "background job an MCP call started (an arrange, orient or fill bed). Its job then reports cancelled; a background " - "job keeps other changes out until it has really stopped. With job, only that job is stopped: the running " - "operation, an `object_fix`, a `script_run` run or a `recording_encode`. Allowed while an operation holds the project. Reply: " - "`was_running`, and job when one was stopped.", - object_schema({{"job", prop("string", "The operation's job to cancel, e.g. \"j12\".")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - const auto ops = runtime.jobs().running_operations(); - // A plugin stops only what its own calls started, so it names the job. - if (!ctx.caller_plugin().empty() && !args.contains("job")) - throw ToolFailure("A plugin cancels only the jobs of its own calls: give the job"); - if (args.contains("job")) - require_own_job(ctx, runtime.jobs(), arg_string(args, "job"), "cancels"); - if (args.contains("job")) { - const std::string job = arg_string(args, "job"); - if (std::find(ops.begin(), ops.end(), job) == ops.end()) { - // A call that is no operation but can be stopped: its handler watches for the stop. - const NativeCommand* def = NativeCommands::instance().find(runtime.jobs().running_tool(job)); - if (def == nullptr || !def->cancellable) - throw ToolFailure("Job " + job + " is not a running operation", {{"running", ops}}); - runtime.jobs().request_stop(job); - return ToolResult::ok({{"was_running", true}, {"job", job}}); - } - } - json out = ctx.run_ui([&]() -> json { - // Only a job an MCP call started: a person's (Text typing) is theirs to stop. - for (const std::string& op : ops) - if ((!args.contains("job") || op == arg_string(args, "job")) && runtime.core().cancel_worker(op)) - return {{"was_running", true}, {"job", op}}; - Plater& plater = ui_plater(); - // A slice operation still waiting to request its slice counts: the cancel keeps it from starting. - const bool running = plater.is_slicing_any() || !ops.empty(); - plater.cancel_slicing(); - return json{{"was_running", running}}; - }); + std::chrono::seconds(15), "the Prepare view to draw"); + json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), call); }); + settle(ctx); return ToolResult::ok(out); - }); - cancel.allowed_during_operation = true; - // Recovery: it must get through a dialog the operation opened and another call's nested loop. - cancel.guard = GuardClass::Recover; - catalog.add(cancel); + }))); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/PlateTools.cpp b/src/slic3r/GUI/Mcp/Tools/PlateTools.cpp new file mode 100644 index 0000000000..b6204c41d3 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/PlateTools.cpp @@ -0,0 +1,2102 @@ +// The place Plates: plate_list, plate_get_settings and plate_set_settings, a plate's own settings, written through +// the code of the Plate Settings dialog and the filament grouping; the plate commands made from menu items, which +// act on the plate a call names, else on the current plate, through the plate operations (Operations/PlateOps.hpp), +// plate_add running its menu item's function (NativeCommandMenuItems.hpp); plate_slice, which reports its own +// outcome per plate (see Operations/RunStatus), and plate_slice_stats, what the Preview shows of a sliced plate; +// plate_set_custom_gcode, the pauses, custom G-codes and filament changes of a plate's layers, through the Preview's +// layer slider; and calibration_generate_test, the Calibration menu's tests, which start a new project. + +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/calib_dlg.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/FilamentMapPanel.hpp" +#include "slic3r/GUI/GCodeViewer.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/IMSlider.hpp" +#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandMenuItems.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/NotificationManager.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PlateOps.hpp" +#include "slic3r/GUI/Operations/RunStatus.hpp" +#include "slic3r/GUI/PartPlate.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/PlateSettingsDialog.hpp" +#include "slic3r/GUI/PresetComboBoxes.hpp" +#include "slic3r/GUI/TickCode.hpp" +#include "slic3r/Utils/UndoRedo.hpp" + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/calib.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/GCode/GCodeStatistics.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/ParameterUtils.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Slicing.hpp" +#include "libslic3r/Utils.hpp" +#include "libvgcode/include/ColorRange.hpp" +#include "libvgcode/include/Types.hpp" +#include "libvgcode/include/Viewer.hpp" + +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; +using Ops::PlateObservation; +using Ops::PlateOutcome; +using Ops::SliceObservation; +using Ops::SliceTicketState; +using Ops::TicketStatus; + +namespace { + +bool is_plate_setting(const std::string& key) +{ + const std::vector& keys = plate_setting_keys(); + return std::find(keys.begin(), keys.end(), key) != keys.end(); +} + +// The plate settings plate_list and an unnamed plate_get_settings show: the filament grouping only on a printer with +// several extruders, whose plates show the filament map icon (a plate keeps a mode of its own on any printer). UI thread. +std::vector listed_plate_keys() +{ + std::vector keys = plate_setting_keys(); + if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) + keys.erase(std::remove_if(keys.begin(), keys.end(), + [](const std::string& key) { return key == "filament_map_mode" || key == "filament_map"; }), + keys.end()); + return keys; +} + +// The plate the call's `plate` argument names, the current one without it. UI thread. +int scope_plate(const json& args) +{ + PartPlateList& plates = ui_plater().get_partplate_list(); + const int index = arg_int(args, "plate", plates.get_curr_plate_index()); + if (index < 0 || index >= plates.get_plate_count()) + throw ToolFailure(no_such_plate(index, plates.get_plate_count())); + return index; +} + +// How many filaments the filament grouping dialog groups: one per slot of the project. +int grouped_filaments() +{ + const auto* colours = ui_plater().config()->option("filament_colour"); + return colours != nullptr ? int(colours->size()) : 0; +} + +// The extruder of each filament as the plate's filament grouping dialog shows it: the plate's own map, else the +// project's, extruder 1 for a filament it lacks. With `volumes`, the nozzle volume type of each filament the same way, +// Standard for one it lacks. +std::vector shown_filament_map(const PartPlate& plate, bool volumes = false) +{ + const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; + std::vector map = volumes ? plate.get_real_filament_volume_maps(project) : plate.get_real_filament_maps(project); + map.resize(std::size_t(grouped_filaments()), volumes ? 0 : 1); + return map; +} + +// The filament_map_mode values the plate's filament grouping dialog offers: none on a printer with one extruder, whose +// plates show no filament map icon, and Auto For Match, which groups by the filaments a printer has loaded, once that +// printer is synced and has no filament track switch ready. UI thread. +std::vector offered_map_modes() +{ + if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) + return {}; + Plater& plater = ui_plater(); + std::vector modes{"Auto For Flush"}; + if (plater.get_machine_sync_status() && !plater.sidebar().is_fila_switch_ready()) + modes.push_back("Auto For Match"); + modes.push_back("Manual"); + return modes; +} + +// A plate's filament_map_mode as plate_set_settings takes it: an offered mode, or null, no mode of the plate's own, so +// that it follows the project's grouping (PartPlate::set_filament_map_mode() with fmmDefault; the plate's grouping +// dialog offers no page for it). UI thread. +FilamentMapMode filament_map_mode_value(const json& value) +{ + if (value.is_null()) + return fmmDefault; + const std::vector offered = offered_map_modes(); + if (!value.is_string() || std::find(offered.begin(), offered.end(), value.get()) == offered.end()) + throw ToolFailure("filament_map_mode is a mode the plate's filament grouping offers (meta.offered of plate_get_settings), " + "or null for the project's grouping" + + std::string(value == "Auto For Match" ? "; Auto For Match groups by the filaments a printer has " + "loaded, and is offered once that printer is synced" : + ""), + {{"offered", offered}}); + return FilamentMapMode(ConfigOptionEnum::get_enum_values().at(value.get())); +} + +// A plate setting in the form plate_set_settings takes: the plate's own value, null where it follows the +// project's plate type, the process, Auto or the project's filament grouping; or with `effective` what the plate +// prints with. +json plate_value(PartPlate& plate, const std::string& key, bool effective) +{ + if (key == "filament_map_mode") { + const FilamentMapMode mode = effective ? plate.get_real_filament_map_mode(wxGetApp().preset_bundle->project_config) : + plate.get_filament_map_mode(); + return mode == fmmDefault ? json() : json(ConfigOptionEnum(mode).serialize()); + } + if (key == "filament_map") { + const std::vector own = plate.get_filament_maps(); + return effective ? json(shown_filament_map(plate)) : own.empty() ? json() : json(own); + } + if (key == "curr_bed_type") { + const BedType type = plate.get_bed_type(effective); + return type == btDefault ? json() : json(ConfigOptionEnum(type).serialize()); + } + if (key == "print_sequence") { + const PrintSequence sequence = effective ? plate.get_real_print_seq() : plate.get_print_seq(); + return sequence == PrintSequence::ByDefault ? json() : json(ConfigOptionEnum(sequence).serialize()); + } + if (key == "spiral_mode") + return effective || plate.has_spiral_mode_config() ? json(plate.get_spiral_vase_mode()) : json(); + if (key == "first_layer_print_sequence") { + const std::vector order = plate.get_first_layer_print_sequence(); + return order.empty() ? json() : json(order); + } + const std::vector ranges = plate.get_other_layers_print_sequence(); + return ranges.empty() ? json() : layer_sequences_json(ranges); +} + +// Every listed setting of a plate (listed_plate_keys()): its own value, or with `effective` what it prints with. +json plate_values(PartPlate& plate, bool effective) +{ + json out = json::object(); + for (const std::string& key : listed_plate_keys()) + out[key] = plate_value(plate, key, effective); + return out; +} + +// plate_get_settings: every key, or those named, with the plate's own value and the one it prints with. UI thread. +json plate_settings(const json& args) +{ + const int index = scope_plate(args); + PartPlate& plate = *ui_plater().get_partplate_list().get_plate(index); + std::vector keys = listed_plate_keys(); + json unknown = json::array(); + if (args.contains("keys")) { + keys.clear(); + for (const json& k : args["keys"]) { + const std::string key = k.get(); + if (is_plate_setting(key)) + keys.push_back(key); + else + unknown.push_back(key); + } + } + json items = json::array(); + for (const std::string& key : keys) { + json item{{"key", key}, {"value", plate_value(plate, key, false)}, {"effective", plate_value(plate, key, true)}}; + if (arg_bool(args, "include_meta", true)) { + item["meta"] = option_meta(*print_config_def.get(key)); + if (key == "curr_bed_type") + item["meta"]["offered"] = project_offered(key); + if (key == "filament_map_mode") + item["meta"]["offered"] = offered_map_modes(); + } + items.push_back(std::move(item)); + } + json out = page(items, args, 100); + out["plate"] = index; + add_unknown_keys(out, unknown, listed_plate_keys()); + return out; +} + +// plate_set_settings. The Plate Settings dialog's values go through its OK (Plater::apply_plate_settings()) with the +// plate's other values as they are, after selecting the plate as its settings icon does; the filament grouping's go +// through the OK of the dialog the plate's filament map icon opens (Plater::open_filament_map_setting_dialog()), which +// takes no undo snapshot of its own. Everything is checked before anything changes, a key a plate's settings lack +// before the app is read, and the call is one undo step. +ToolResult set_plate_settings(const json& args, ToolContext& ctx) +{ + const json values_in = args.value("values", json::object()); + if (values_in.empty()) + throw ToolFailure("values must be a non-empty object {key: value}"); + int index = -1; + json reply = ctx.run_ui([&]() -> json { + for (auto it = values_in.begin(); it != values_in.end(); ++it) + if (!is_plate_setting(it.key())) + throw unknown_setting(it.key(), "plate", {{"keys", plate_setting_keys()}}); + Plater& plater = ui_plater(); + if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) + throw ToolFailure("Plates are a filament (FFF) feature"); + index = scope_plate(args); + PartPlateList& plates = plater.get_partplate_list(); + PartPlate& plate = *plates.get_plate(index); + const json before = plate_values(plate, false); + // The dialog's choices, starting from the plate's own. + const int own_spiral = plate.has_spiral_mode_config() ? (plate.get_spiral_vase_mode() ? 1 : 2) : 0; + BedType bed_type = plate.get_bed_type(); + PrintSequence sequence = plate.get_print_seq(); + int spiral = own_spiral; + std::vector first_layer = plate.get_first_layer_print_sequence(); + std::vector other_layers = plate.get_other_layers_print_sequence(); + const int slots = wxGetApp().filaments_cnt(); + // The filament grouping dialog's choices: its mode, and the map its Custom page sets. + const FilamentMapMode own_mode = plate.get_filament_map_mode(); + FilamentMapMode map_mode = own_mode; + std::optional> map; + const int extruders = wxGetApp().preset_bundle->get_printer_extruder_count(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) { + const std::string& key = it.key(); + const json& value = it.value(); + if (key == "curr_bed_type") { + bed_type = btDefault; // "Same as Global Plate Type" + if (value.is_null()) + continue; + const std::vector offered = project_offered(key); + if (offered.empty()) + throw ToolFailure("curr_bed_type: this printer has a single plate type"); + if (!value.is_string() || std::find(offered.begin(), offered.end(), value.get()) == offered.end()) + throw ToolFailure("This printer does not offer curr_bed_type " + value.dump(), {{"offered", offered}}); + bed_type = BedType(ConfigOptionEnum::get_enum_values().at(value.get())); + } else if (key == "print_sequence") { + const auto& names = ConfigOptionEnum::get_enum_values(); + if (!value.is_null() && (!value.is_string() || names.count(value.get()) == 0)) + throw ToolFailure("print_sequence is \"by layer\", \"by object\" or null (the process's)"); + sequence = value.is_null() ? PrintSequence::ByDefault : PrintSequence(names.at(value.get())); + } else if (key == "spiral_mode") { + if (!value.is_null() && !value.is_boolean()) + throw ToolFailure("spiral_mode is true, false or null (the process's)"); + spiral = value.is_null() ? 0 : value.get() ? 1 : 2; + } else if (key == "first_layer_print_sequence" || key == "other_layers_print_sequence") { + // The dialog greys the custom orders out while a slot is a mixed filament, which prints a different + // physical filament from layer to layer. + if (!value.is_null() && wxGetApp().preset_bundle->num_mixed_filaments() > 0) + throw ToolFailure(key + " cannot be set while the project has mixed filaments (filament_list's mixed rows); " + "null sets Auto"); + if (key == "first_layer_print_sequence") + first_layer = value.is_null() ? std::vector() : filament_order(value, slots); + else + other_layers = value.is_null() ? std::vector() : layer_sequences(value, slots); + } else { + // The plate shows its filament map icon on a printer with several extruders alone. + if (extruders < 2) + throw ToolFailure(key + " groups the filaments onto the extruders of a printer that has several; this one has one"); + if (key == "filament_map_mode") { + map_mode = filament_map_mode_value(value); + } else { + if (!value.is_array() || + std::any_of(value.begin(), value.end(), [](const json& extruder) { return !extruder.is_number_integer(); })) + throw ToolFailure("filament_map is the extruder of each filament, 1-based, e.g. [1, 2, 2]"); + map = value.get>(); + } + } + } + if (map) { + const std::string mode = map_mode == fmmDefault ? std::string() : ConfigOptionEnum(map_mode).serialize(); + if (const std::string err = filament_map_error(mode, *map, grouped_filaments(), extruders); !err.empty()) + throw ToolFailure(err); + } + const bool settings = bed_type != plate.get_bed_type() || sequence != plate.get_print_seq() || + first_layer != plate.get_first_layer_print_sequence() || + other_layers != plate.get_other_layers_print_sequence() || spiral != own_spiral; + // The grouping dialog's OK: in the Manual mode the map and nozzle volume types its Custom page shows become the + // plate's own, and the slice is invalidated when the mode or what the plate prints with changes. + const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; + const std::vector old_maps = plate.get_real_filament_maps(project); + const std::vector old_volumes = plate.get_real_filament_volume_maps(project); + const std::vector new_maps = map ? *map : shown_filament_map(plate); + const std::vector new_volumes = shown_filament_map(plate, true); + const bool manual = map_mode == fmmManual; + const bool regrouped = map_mode != own_mode || old_maps != new_maps || old_volumes != new_volumes; + const bool own_map = manual && (plate.get_filament_maps() != new_maps || + plate.get_filament_volume_maps() != new_volumes); + const bool grouping_given = values_in.contains("filament_map_mode") || values_in.contains("filament_map"); + const bool grouping = grouping_given && (regrouped || own_map); + // The Custom page disables the dialog's OK while an extruder its map gives a filament the plate prints has no + // nozzle of the volume type that filament needs. + if (const std::optional shortage = manual && grouping_given ? + manual_map_nozzle_shortage(nozzle_inventory(*wxGetApp().preset_bundle), plate.get_extruders(true), new_maps, + new_volumes) : + std::nullopt) { + const std::string type = ConfigOptionEnum(shortage->volume_type).serialize(); + const char* side = shortage->extruder == 0 ? " (left)" : shortage->extruder == 1 ? " (right)" : ""; + throw ToolFailure("The manual grouping gives extruder " + std::to_string(shortage->extruder + 1) + side + + " a filament that prints with a " + type + " nozzle, and the extruder has no " + type + + " nozzle, so the filament grouping dialog does not take this map: give that filament another " + "extruder, or set the extruder's nozzles first", + {{"code", "no_nozzle_for_grouping"}, {"extruder", shortage->extruder + 1}, {"nozzle_volume_type", type}}); + } + if (settings || grouping) { + // The settings and filament map icons select their plate first; the dialogs work on the current plate. + if (index != plates.get_curr_plate_index()) + plater.select_plate(index); + Plater::SingleSnapshot single(&plater); + plater.take_snapshot("Plate Settings"); + if (settings) + plater.apply_plate_settings(index, bed_type, first_layer, other_layers, sequence, spiral); + if (grouping) { + if (map_mode != own_mode) + plate.set_filament_map_mode(map_mode); + if (manual) { + plate.set_filament_maps(new_maps); + plate.set_filament_volume_maps(new_volumes); + } + if (regrouped) { + plate.update_slice_result_valid_state(false); + plater.set_plater_dirty(true); + plater.update(); + } + } + } + const json after = plate_values(plate, false); + json applied = json::object(); + json effective = json::object(); + json changed = json::object(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) { + applied[it.key()] = after.value(it.key(), json()); + effective[it.key()] = plate_value(plate, it.key(), true); + } + for (auto it = after.begin(); it != after.end(); ++it) + if (it.value() != before.value(it.key(), json())) + changed[it.key()] = it.value(); + return json{{"plate", index}, {"applied", applied}, {"changed", changed}, {"effective", effective}}; + }); + // A replay sets the same plate, whichever is current then. + if (!args.contains("plate")) { + json recorded = args; + recorded["plate"] = index; + ctx.set_journal_args(std::move(recorded)); + } + settle(ctx); + return ToolResult::ok(reply); +} + +// How many objects have an instance on plate `plate`; object_list lists them. +int objects_on_plate(const Model& model, PartPlateList& plates, int plate) +{ + int objects = 0; + for (std::size_t o = 0; o < model.objects.size(); ++o) { + const std::size_t instances = model.objects[o]->instances.size(); + std::size_t j = 0; + while (j < instances && instance_plate(plates, int(o), int(j)) != plate) + ++j; + objects += j < instances; + } + return objects; +} + +// plate_list: every plate's name, lock, settings as it prints them, what it sets itself, its objects, place on the bed, +// slice state, prime tower position and layer G-codes. UI thread. +json list_plates(const json& args) +{ + Plater& plater = ui_plater(); + PartPlateList& plates = plater.get_partplate_list(); + const Model& model = plater.model(); + const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; + const auto* tower_x = project.option("wipe_tower_x"); + const auto* tower_y = project.option("wipe_tower_y"); + json items = json::array(); + for (int i = 0; i < plates.get_plate_count(); ++i) { + PartPlate& plate = *plates.get_plate(i); + json entry = plate_values(plate, true); + entry["index"] = i; + entry["name"] = plate.get_plate_name(); + entry["locked"] = plate.is_locked(); + entry["current"] = i == plates.get_curr_plate_index(); + json overrides = json::array(); + for (const std::string& key : listed_plate_keys()) + if (!plate_value(plate, key, false).is_null()) + overrides.push_back(key); + entry["overrides"] = std::move(overrides); + entry["objects"] = objects_on_plate(model, plates, i); + entry.update(plate_place(plate)); + entry["sliced"] = plate.is_slice_result_valid(); + if (tower_x != nullptr && tower_y != nullptr && !tower_x->empty() && !tower_y->empty()) + entry["wipe_tower"] = {tower_x->get_at(std::size_t(i)), tower_y->get_at(std::size_t(i))}; + // Layer numbers only from an up-to-date slice that no slice is rewriting. + const auto codes = model.plates_custom_gcodes.find(i); + std::vector layer_zs; + if (codes != model.plates_custom_gcodes.end() && !codes->second.gcodes.empty() && plate.is_slice_result_valid() && + !plater.is_slicing_any() && plate.get_slice_result() != nullptr) + layer_zs = gcode_layer_zs(*plate.get_slice_result()); + entry["layer_gcode"] = codes != model.plates_custom_gcodes.end() ? layer_gcode_json(codes->second, layer_zs) : json::array(); + items.push_back(std::move(entry)); + } + return page(items, args, 100); +} + +// ---- The plate commands made from menu items ---- + +// What a plate command made from menu items answers for a refusal: as information where its item told it so (no plates to +// edit, the only plate, no room for another, a slice running), else as an error. +AppActionRunResult plate_refused(const Ops::Refusal& refusal) +{ + const std::string code = refusal.code; + const bool info = refusal.kind == Ops::RefusalKind::Busy || code == "no_plates" || code == "last_plate" || + code == "too_many_plates"; + return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); +} + +// The plate a call's `plate` argument names; none without it, for the current plate. +std::optional named_plate(const json& args) +{ + return args.contains("plate") ? std::optional(arg_int(args, "plate", 0)) : std::nullopt; +} + +// The plates as a command that adds or removes one replies with them afterwards: each plate's index, name and how many +// objects stand on it, and the current plate. UI thread. +json plates_reply() +{ + Plater& plater = ui_plater(); + PartPlateList& plates = plater.get_partplate_list(); + json items = json::array(); + for (int i = 0; i < plates.get_plate_count(); ++i) + items.push_back( + {{"index", i}, {"name", plates.get_plate(i)->get_plate_name()}, {"objects", objects_on_plate(plater.model(), plates, i)}}); + return {{"plates", std::move(items)}, {"current", plates.get_curr_plate_index()}}; +} + +AppActionRunResult plate_delete_command(const json& args) +{ + const Ops::Outcome deleted = Ops::delete_plate({named_plate(args)}); + if (!deleted) + return plate_refused(deleted.refusal()); + json reply = plates_reply(); + reply["plate"] = deleted.value(); + return menu_reply(reply); +} + +AppActionRunResult plate_duplicate_command(const json& args) +{ + const Ops::Outcome made = Ops::duplicate_plate({named_plate(args)}); + if (!made) + return plate_refused(made.refusal()); + json reply = plates_reply(); + reply["plate"] = made.value().plate; + reply["new_plate"] = made.value().copy; + return menu_reply(reply); +} + +// plate_rename: a call with no arguments asks for the current plate's name in its name dialog, as the menu item does; any +// other gives it. +AppActionRunResult plate_rename_command(const json& args) +{ + Ops::RenamePlateArgs op; + op.plate = named_plate(args); + if (person_form(args)) { + if (std::optional refusal = Ops::plates_refusal()) + return plate_refused(*refusal); + PlateNameEditDialog dlg(wxGetApp().mainframe, wxID_ANY, _L("Edit Plate Name")); + dlg.set_plate_name(from_u8(ui_plater().get_partplate_list().get_curr_plate()->get_plate_name())); + // The person called it off, and knows nothing was renamed. + if (dlg.ShowModal() != wxID_YES) + return quiet_refusal(Ops::plate_not_renamed()); + op.name = into_u8(dlg.get_plate_name()); + } else { + op.name = arg_string(args, "name"); + } + const Ops::Outcome renamed = Ops::rename_plate(op); + if (!renamed) + return plate_refused(renamed.refusal()); + const PartPlate& plate = *ui_plater().get_partplate_list().get_plate(renamed.value()); + return menu_reply({{"plate", renamed.value()}, {"name", plate.get_plate_name()}}); +} + +AppActionRunResult plate_lock_command(const json& args) +{ + Ops::SetPlateLockedArgs op; + op.plate = named_plate(args); + if (args.contains("locked")) + op.locked = arg_bool(args, "locked", true); + const Ops::Outcome locked = Ops::set_plate_locked(op); + if (!locked) + return plate_refused(locked.refusal()); + return menu_reply({{"plate", locked.value().plate}, {"locked", locked.value().locked}, {"changed", locked.value().changed}}); +} + +// plate_select: Ops::select_plate() also serves the commands that select a plate on the way, so the check of the menu items, +// that the project has plates to select, is made here. +AppActionRunResult plate_select_command(const json& args) +{ + if (std::optional refusal = Ops::plates_refusal()) + return plate_refused(*refusal); + Ops::SelectPlateArgs op; + op.plate = arg_int(args, "plate", ui_plater().get_partplate_list().get_curr_plate_index()); + if (const Ops::Outcome selected = Ops::select_plate(op); !selected) + return plate_refused(selected.refusal()); + return menu_reply({{"plate", op.plate}}); +} + +} // namespace + +json plate_place(PartPlate& plate) +{ + // The plate's shape on the bed, moved to where the plate list places the plate; the extended box holds the grabber + // in front of it too. + const BoundingBoxf3& box = plate.get_bounding_box(); + const auto rounded_mm =[](double v) { return rounded(v, 1000.) + 0.; }; + return {{"origin", {rounded_mm(box.min.x()), rounded_mm(box.min.y())}}, + {"size", {rounded_mm(box.size().x()), rounded_mm(box.size().y())}}}; +} + +const std::vector& plate_setting_keys() +{ + static const std::vector keys{"curr_bed_type", + "print_sequence", + "spiral_mode", + "first_layer_print_sequence", + "other_layers_print_sequence", + "filament_map_mode", + "filament_map"}; + return keys; +} + +std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders) +{ + if (mode != "Manual") + return "filament_map is a plate's own grouping, which filament_map_mode \"Manual\" takes: the automatic modes group the " + "filaments when the plate slices, and null follows the project's grouping"; + if (int(map.size()) != filaments) + return "filament_map gives one extruder per filament: " + std::to_string(filaments) + " filaments, " + + std::to_string(map.size()) + " given"; + for (const int extruder : map) + if (extruder < 1 || extruder > extruders) + return "filament_map names extruder " + std::to_string(extruder) + "; this printer has extruders 1 to " + + std::to_string(extruders); + return {}; +} + +std::vector filament_order(const json& order, int slots) +{ + std::vector out; + if (order.is_array()) + for (const json& slot : order) + out.push_back(slot.is_number_integer() ? slot.get() : 0); + std::vector sorted = out; + std::sort(sorted.begin(), sorted.end()); + std::vector every(std::size_t(std::max(slots, 0))); + std::iota(every.begin(), every.end(), 1); + if (sorted != every) + throw ToolFailure("A filament order lists every filament slot 1.." + std::to_string(slots) + " once, e.g. [2, 1]; got " + + order.dump()); + return out; +} + +std::vector layer_sequences(const json& ranges, int slots) +{ + // The dialog's "End" of a range: up to the last layer. + constexpr int last_layer = INT_MAX - 1; + if (!ranges.is_array() || ranges.empty()) + throw ToolFailure("other_layers_print_sequence is [{from, to, order}, ...] or null for Auto"); + std::vector out; + for (const json& range : ranges) { + const bool shaped = range.is_object() && range.contains("from") && range["from"].is_number_integer() && range.contains("order") && + (!range.contains("to") || range["to"].is_number_integer()) && range.size() == (range.contains("to") ? 3u : 2u); + if (!shaped) + throw ToolFailure("A range is {\"from\": layer, \"to\": layer, \"order\": [slots]}, to optional (the last layer); got " + range.dump()); + const int from = range["from"].get(); + const int to = range.value("to", last_layer); + if (from < 2) + throw ToolFailure("Ranges start at layer 2 or later; the first layer's order is first_layer_print_sequence"); + if (to < from) + throw ToolFailure("Range " + range.dump() + " ends before it starts"); + out.push_back({{from, std::min(to, last_layer)}, filament_order(range["order"], slots)}); + } + std::sort(out.begin(), out.end(), [](const LayerPrintSequence& a, const LayerPrintSequence& b) { return a.first < b.first; }); + for (std::size_t i = 1; i < out.size(); ++i) + if (out[i].first.first <= out[i - 1].first.second) + throw ToolFailure("Layer ranges overlap: one " + + (out[i - 1].first.second == last_layer ? std::string("runs to the last layer") : + "ends at layer " + std::to_string(out[i - 1].first.second)) + + ", the next starts at layer " + std::to_string(out[i].first.first)); + return out; +} + +json layer_sequences_json(const std::vector& ranges) +{ + json out = json::array(); + for (const LayerPrintSequence& range : ranges) { + json item{{"from", range.first.first}, {"order", range.second}}; + // The dialog's "End" is INT_MAX - 1, the plate tab's default INT_MAX. + if (range.first.second < INT_MAX - 1) + item["to"] = range.first.second; + out.push_back(std::move(item)); + } + return out; +} + +std::vector gcode_layer_zs(const GCodeProcessorResult& result) +{ + // GCodeViewer::load() and libvgcode::Layers::update(): layers numbered consecutively over the moves + // there are, each labelled with its last extrusion's height, or a belt print's with its print Z. + const bool belt = result.belt_tilt_angle > 0.f; + std::vector zs; + unsigned int layer = std::numeric_limits::max(); + for (std::size_t i = 1; i < result.moves.size(); ++i) { + const GCodeProcessorResult::MoveVertex& move = result.moves[i]; + if (move.layer_id != layer) { + layer = move.layer_id; + zs.push_back(belt ? double(move.print_z) : 0.); + } + if (!belt && move.type == EMoveType::Extrude && move.extrusion_role != erCustom) + zs.back() = double(move.position.z()); + } + return zs; +} + +json layer_gcode_json(const CustomGCode::Info& codes, const std::vector& layer_zs) +{ + std::vector items = codes.gcodes; + std::stable_sort(items.begin(), items.end()); + json out = json::array(); + for (const CustomGCode::Item& item : items) { + json code{{"z", std::round(item.print_z * 1000.) / 1000.}}; + // IMSlider::get_tick_from_value(z, true): the first layer whose top is at or above the height. + const auto layer = std::lower_bound(layer_zs.begin(), layer_zs.end(), item.print_z - epsilon()); + if (layer != layer_zs.end()) + code["layer"] = int(layer - layer_zs.begin()) + 1; + const bool change = item.type == CustomGCode::ToolChange || item.type == CustomGCode::ColorChange; + switch (item.type) { + case CustomGCode::PausePrint: code["type"] = "pause"; break; + case CustomGCode::Custom: code["type"] = "custom"; break; + case CustomGCode::Template: code["type"] = "template"; break; + case CustomGCode::ToolChange: code["type"] = "change_filament"; break; + case CustomGCode::ColorChange: code["type"] = "color_change"; break; + default: code["type"] = "unknown"; break; + } + if (change && item.extruder > 0) + code["filament"] = item.extruder; + if (change && !item.color.empty()) + code["color"] = item.color; + if (item.type == CustomGCode::Custom && !item.extra.empty()) + code["gcode"] = item.extra; + out.push_back(std::move(code)); + } + return out; +} + +namespace { + +// The plate_slice tool's view of its request: slice_status()'s state, which adds when the tool started +// waiting to what the operation's ticket holds. +struct SliceTicket +{ + SliceTicketState state; + std::vector plates; +}; + +} // namespace + +json plate_summary(const json& statistics, const GCodeProcessorResult& result) +{ + const auto hundredths = [](double value) { return std::round(value * 100.) / 100.; }; + const json& summary = statistics.at("summary"); + const double seconds = summary.at("time").get(); + json out{{"time_s", std::lround(seconds)}, + {"time", get_time_dhms(float(seconds))}, + {"filament_g", hundredths(summary.at("weight").get())}, + {"filament_cost", summary.at("filament_cost")}, + {"layers", summary.at("layer_count")}, + {"filament_changes", summary.at("filament_changes")}}; + // The processor leaves the silent-mode time 0 when the printer has no such estimate. + const PrintEstimatedStatistics& estimates = result.print_statistics; + const double silent = estimates.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].time; + if (silent > 0.) + out["silent_time_s"] = std::lround(silent); + if (estimates.total_extruder_changes > 0) + out["extruder_changes"] = estimates.total_extruder_changes; + double max_z = 0.; + for (const json& layer : statistics.at("layers")) + max_z = std::max(max_z, layer.at("z").get()); + out["max_z"] = max_z; + + json filaments = json::array(); + const auto add_slot = [&filaments] { + filaments.push_back({{"slot", filaments.size() + 1}, {"m", 0.}, {"g", 0.}, {"model_g", 0.}, {"support_g", 0.}, + {"flush_g", 0.}, {"tower_g", 0.}}); + }; + while (filaments.size() < result.filaments_count) + add_slot(); + double length = 0.; + for (const json& used : summary.at("filaments")) { + const size_t slot = used.at("id").get(); + while (filaments.size() < slot) + add_slot(); + const auto grams = [&used, &hundredths](const char* use) { return hundredths(used.at(use).at("weight").get()); }; + json& f = filaments[slot - 1]; + f["m"] = hundredths(used.at("length").get() / 1000.); + f["g"] = hundredths(used.at("weight").get()); + f["model_g"] = grams("model"); + f["support_g"] = grams("support"); + f["flush_g"] = grams("flush"); + f["tower_g"] = grams("prime_tower"); + length += used.at("length").get(); + } + out["filament_m"] = hundredths(length / 1000.); + out["filaments"] = std::move(filaments); + return out; +} + +namespace { + +// The plate plate_set_custom_gcode names (default: the current one), after the checks that need neither its +// layers nor a view. +int gcode_plate(Plater& plater, const json& args) +{ + if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) + throw ToolFailure("Layer G-codes are for the plates of an FFF project"); + const bool edits = arg_bool(args, "clear", false) || !args.value("add", json::array()).empty() || + !args.value("remove", json::array()).empty(); + if (!edits) + throw ToolFailure("Give add, remove or clear; plate_list lists each plate's layer_gcode"); + PartPlateList& plates = plater.get_partplate_list(); + const int index = arg_int(args, "plate", plates.get_curr_plate_index()); + if (index < 0 || index >= plates.get_plate_count()) + throw ToolFailure(no_such_plate(index, plates.get_plate_count())); + PartPlate& plate = *plates.get_plate(index); + const std::string name = "plate " + std::to_string(index); + // The slider's menus offer no codes on a plate printed by object, and it erases them all when it + // shows one; a sliced G-code shown without its objects (.gcode.3mf) has no menus either. + if (!plate.has_printable_instances()) + throw ToolFailure(name + " has nothing to print, so no layers to place codes on"); + if (plate.get_real_print_seq() == PrintSequence::ByObject) + throw ToolFailure(name + " prints by object (print_sequence), which takes no layer G-codes"); + // A slice would replace the layers under the edit. + if (plater.is_slicing_any()) + throw ToolFailure("Slicing is in progress; app_wait {for: \"idle\"} first"); + return index; +} + +// Whether the Preview shows the plate's layers: its layer slider holds that plate's layers and codes, +// as when a person opened it. A plate edited after its slice and still shown keeps them, so a person +// can go on editing it, and so can MCP. +bool preview_shows_plate(Plater& plater, int index) +{ + PartPlateList& plates = plater.get_partplate_list(); + GLCanvas3D* preview = plater.get_preview_canvas3D(); + if (index != plates.get_curr_plate_index() || !plater.is_preview_shown() || preview == nullptr) + return false; + GCodeViewer& viewer = preview->get_gcode_viewer(); + return viewer_holds(viewer, plates.get_plate(index)->get_slice_result()) && + viewer.get_layers_slider()->GetMaxValue() + 1 == int(preview->get_gcode_layers_zs().size()); +} + +// A plate's codes as plate_list's layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer +// (1-based) where `zs` has a layer at or above z, the slider's rule for a stored height. +json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector& zs) +{ + std::vector items = codes.gcodes; + std::stable_sort(items.begin(), items.end()); + json out = json::array(); + for (const CustomGCode::Item& item : items) { + json code{{"z", std::round(item.print_z * 1000.) / 1000.}, {"type", custom_gcode_type_name(item.type)}}; + const auto layer = std::lower_bound(zs.begin(), zs.end(), item.print_z - epsilon()); + if (layer != zs.end()) + code["layer"] = int(layer - zs.begin()) + 1; + const bool change = item.type == CustomGCode::ToolChange || item.type == CustomGCode::ColorChange; + if (change && item.extruder > 0) + code["filament"] = item.extruder; + if (change && !item.color.empty()) + code["color"] = item.color; + if (item.type == CustomGCode::Custom && !item.extra.empty()) + code["gcode"] = item.extra; + out.push_back(std::move(code)); + } + return out; +} + +// plate_set_custom_gcode's reply, once the plater has the slider's codes. UI thread. +json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args) +{ + const Model& model = plater.model(); + const auto codes = model.plates_custom_gcodes.find(index); + const std::vector zs = plater.get_preview_canvas3D()->get_gcode_layers_zs(); + json out{{"plate", index}, + {"layers", zs.size()}, + {"changed", changed}, + {"layer_gcode", codes != model.plates_custom_gcodes.end() ? plate_layer_gcode(codes->second, zs) : json::array()}}; + if (changed) + out["note"] = "The plate's slice no longer matches its codes; slice it again before exporting."; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + for (const json& item : args.value("add", json::array())) + if (arg_string(item, "type") == "pause" && bundle.printers.get_edited_preset().config.opt_string("machine_pause_gcode").empty()) { + out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with settings_set type printer)"}); + break; + } + return out; +} + +// Selects the plate plate_set_custom_gcode names and shows it in the Preview, unless the Preview shows its layers +// already, and returns its index. Refused calls leave the view alone. Only a plate with an up-to-date slice +// is opened: opening the Preview on one that is not starts a slice. +int show_plate_layers(Plater& plater, const json& args) +{ + const int index = gcode_plate(plater, args); + if (preview_shows_plate(plater, index)) + return index; + PartPlateList& plates = plater.get_partplate_list(); + if (!plates.get_plate(index)->is_slice_result_valid()) + throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (plate_slice {plates: " + + std::to_string(index) + "})"); + plater.select_view_3D("Preview"); + // What clicking a sliced plate in the Preview's plate toolbar does: select it and load its result, which + // a plate switch alone leaves to the next slice while the Preview shows. + plater.select_sliced_plate(index, true); + if (MainFrame* frame = wxGetApp().mainframe) + frame->select_tab(wxString(TAB_ID_PREVIEW)); + return index; +} + +// The edit itself: the plate's layers are in the Preview's layer slider, which takes the codes, and the +// next frame (or this call, at once) hands them to the plater, as for a person's edit. +json set_custom_gcode_at_layer(Plater& plater, int index, const json& args, CustomGCode::Info& handed_over) +{ + gcode_plate(plater, args); + if (!preview_shows_plate(plater, index)) + throw ToolFailure("The Preview no longer shows plate " + std::to_string(index) + "'s layers; call again"); + GLCanvas3D& preview = *plater.get_preview_canvas3D(); + IMSlider& slider = *preview.get_gcode_viewer().get_layers_slider(); + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const bool spiral = bundle.prints.get_edited_preset().config.opt_bool("spiral_mode"); + bool changed = false; + try { + changed = edit_layer_gcode(slider, args, int(plater.get_extruder_colors_from_plater_config(nullptr).size()), + !bundle.printers.get_edited_preset().config.opt_string("template_custom_gcode").empty(), + slider.can_change_color() ? std::string() : + spiral ? std::string("spiral vase (spiral_mode) is on") : + std::string("its objects print with different filaments")); + } catch (const ToolFailure&) { + // Only the slider refusing a change comes after earlier changes; hand those over, as the next frame would. + preview.send_layer_ticks_changes(); + throw; + } + if (!changed) + return layer_gcode_reply(plater, index, false, args); + handed_over = slider.GetTicksValues(); + preview.send_layer_ticks_changes(); + return json(); +} + +} // namespace + +const char* custom_gcode_type_name(CustomGCode::Type type) +{ + switch (type) { + case CustomGCode::PausePrint: return "pause"; + case CustomGCode::Custom: return "custom"; + case CustomGCode::Template: return "template"; + case CustomGCode::ToolChange: return "change_filament"; + case CustomGCode::ColorChange: return "color_change"; + default: return "unknown"; + } +} + +CustomGCode::Type custom_gcode_type_from_name(const std::string& name) +{ + for (const CustomGCode::Type type : {CustomGCode::PausePrint, CustomGCode::Custom, CustomGCode::Template, CustomGCode::ToolChange}) + if (name == custom_gcode_type_name(type)) + return type; + return CustomGCode::Unknown; +} + +bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool has_template, const std::string& no_filament_change) +{ + const int layers = slider.GetMaxValue() + 1; + const auto layer = [](int tick) { return "layer " + std::to_string(tick + 1); }; + // `layer` counts from 1, as the slider's labels do; `z` is the layer whose top is at or above it, where + // the slider puts a stored height. + const auto item_tick = [&](const json& item) { + const bool by_layer = item.contains("layer"); + if (by_layer == item.contains("z")) + throw ToolFailure("Give layer or z for each code"); + if (by_layer) { + const int n = arg_int(item, "layer", 0); + if (n < 1 || n > layers) + throw ToolFailure("layer must be 1.." + std::to_string(layers) + " (z " + mm(slider.GetMinValueD()) + ".." + + mm(slider.GetMaxValueD()) + ")"); + return n - 1; + } + const double z = arg_double(item, "z", 0.); + const int tick = slider.get_tick_from_value(z, true); + if (tick < 0) + throw ToolFailure("z " + mm(z) + " is above the top layer (" + mm(slider.GetMaxValueD()) + " mm)"); + return tick; + }; + const auto listed = [](const std::map& codes) { + std::string text; + for (const auto& entry : codes) + text += (text.empty() ? "" : ", ") + std::to_string(entry.first + 1); + return codes.empty() ? std::string("no codes") : (codes.size() == 1 ? "a code on layer " : "codes on layers ") + text; + }; + + // Everything is checked on a copy first, so a refused call leaves the slider as it was. + std::map before; + for (const TickCode& code : slider.GetTicks()) + before.emplace(code.tick, code); + std::map after = arg_bool(args, "clear", false) ? std::map() : before; + for (const json& item : args.value("remove", json::array())) { + const int tick = item_tick(item); + if (after.erase(tick) == 0) + throw ToolFailure("No code on " + layer(tick) + " (" + listed(after) + ")"); + } + std::set added; + for (const json& item : args.value("add", json::array())) { + const int tick = item_tick(item); + const CustomGCode::Type type = custom_gcode_type_from_name(arg_string(item, "type")); + if (type == CustomGCode::Unknown) + throw ToolFailure("type must be pause, custom, template or change_filament"); + if (!added.insert(tick).second) + throw ToolFailure("Two codes for " + layer(tick)); + if (item.contains("filament") != (type == CustomGCode::ToolChange)) + throw ToolFailure(type == CustomGCode::ToolChange ? "change_filament needs filament" : "filament goes with type change_filament"); + if (item.contains("gcode") != (type == CustomGCode::Custom)) + throw ToolFailure(type == CustomGCode::Custom ? "custom needs gcode" : "gcode goes with type custom"); + TickCode code{tick, type}; + // The menus' rules: Add Custom Template only with a template, Change Filament only with two or more + // filaments and while the slider allows it, and the custom G-code dialog's buffer. + if (type == CustomGCode::Custom) { + code.extra = arg_string(item, "gcode"); + if (code.extra.empty() || code.extra.size() > 1023) + throw ToolFailure("gcode must be 1 to 1023 bytes, as the Custom G-code dialog takes"); + } else if (type == CustomGCode::Template && !has_template) { + throw ToolFailure("The printer's template_custom_gcode is empty; set it (settings_set type printer) or use type custom"); + } else if (type == CustomGCode::ToolChange) { + // The slider colours each filament change from the filaments of the slice. + const int slots = int(slider.GetExtruderColors().size()); + if (slots != filaments) + throw ToolFailure("The filaments changed since the plate was sliced; slice it again"); + if (slots < 2) + throw ToolFailure("change_filament needs two or more filaments; on a printer without a tool changer, add a filament " + "slot and turn on manual_filament_change"); + if (!no_filament_change.empty()) + throw ToolFailure("The plate takes no filament change: " + no_filament_change); + code.extruder = arg_int(item, "filament", 0); + if (code.extruder < 1 || code.extruder > slots) + throw ToolFailure("filament must be 1.." + std::to_string(slots)); + } + // One code per layer, as the slider's menus allow: on a layer with a code they only edit it. + if (const auto it = after.find(tick); it != after.end() && it->second.type != type) + throw ToolFailure(layer(tick) + " has a " + custom_gcode_type_name(it->second.type) + " code; remove it first (remove: [{layer: " + + std::to_string(tick + 1) + "}])"); + after[tick] = code; + } + + // Then the menus' own edits: Delete, Add, Edit Custom G-code and Change Filament on a filament change. + const auto same = [](const TickCode& a, const TickCode& b) { + return a.type == b.type && (a.type != CustomGCode::ToolChange || a.extruder == b.extruder) && + (a.type != CustomGCode::Custom || a.extra == b.extra); + }; + const auto edited_in_place = [](const TickCode& from, const TickCode& to) { + return from.type == to.type && (to.type == CustomGCode::Custom || to.type == CustomGCode::ToolChange); + }; + bool changed = false; + // The plater invalidates the plate's slice on the type of the last edit, which must not be a colour + // change's when other codes changed too. + CustomGCode::Type event = CustomGCode::Unknown; + for (const auto& [tick, code] : before) { + const auto it = after.find(tick); + if (it == after.end() || (!same(code, it->second) && !edited_in_place(code, it->second))) { + slider.delete_tick(code); + changed = true; + if (code.type != CustomGCode::ColorChange) + event = code.type; + } + } + for (const auto& [tick, code] : after) { + if (const auto it = before.find(tick); it != before.end() && same(it->second, code)) + continue; + if (code.type == CustomGCode::Custom) + slider.add_custom_gcode(code.extra, tick); + else if (!slider.add_code_as_tick(code.type, code.type == CustomGCode::ToolChange ? code.extruder : -1, tick)) + throw ToolFailure(std::string("The layer slider refused the ") + custom_gcode_type_name(code.type) + " on " + layer(tick) + + (changed ? "; the codes before it changed (plate_list lists them)" : "")); + changed = true; + event = code.type; + } + if (changed && event != CustomGCode::Unknown) + slider.post_ticks_changed_event(event); + return changed; +} + +namespace { + +// The view types the legend shows a colour range for; the logarithmic layer time repeats the linear one. +constexpr libvgcode::EViewType range_view_types[] = { + libvgcode::EViewType::Height, libvgcode::EViewType::Width, + libvgcode::EViewType::Speed, libvgcode::EViewType::ActualSpeed, + libvgcode::EViewType::Acceleration, libvgcode::EViewType::Jerk, + libvgcode::EViewType::VolumetricFlowRate, libvgcode::EViewType::ActualVolumetricFlowRate, + libvgcode::EViewType::LayerTimeLinear, libvgcode::EViewType::FanSpeed, + libvgcode::EViewType::Temperature, libvgcode::EViewType::PressureAdvance}; + +// preview_state() of the Preview's toolpaths, plus which legend rows are visible and the colour range of +// every view type. Ranges span the whole print, but count travels, wipes and Custom extrusions only +// while the legend shows them. UI thread. +json preview_view(GLCanvas3D& canvas) +{ + // The viewer recomputes its ranges at its next frame after a legend change; nothing draws while + // the Preview is hidden, and nothing changes the legend then either. + canvas.set_as_dirty(); + canvas.render(); + GCodeViewer& viewer = canvas.get_gcode_viewer(); + const libvgcode::Viewer& toolpaths = viewer.get_viewer(); + json view = preview_state(viewer); + json features = json::object(); + for (const libvgcode::EGCodeExtrusionRole role : toolpaths.get_extrusion_roles()) + features[legend_feature_key(role)] = toolpaths.is_extrusion_role_visible(role); + json options = json::object(); + for (const libvgcode::EOptionType type : toolpaths.get_options()) + if (const char* key = legend_option_key(type)) + options[key] = toolpaths.is_option_visible(type); + view["legend"] = {{"features", std::move(features)}, {"options", std::move(options)}}; + json ranges = json::object(); + for (const libvgcode::EViewType type : range_view_types) { + // [FLT_MAX, -FLT_MAX] when the print has no such value. + const std::array& range = toolpaths.get_color_range(type).get_range(); + if (range[0] <= range[1]) + ranges[GCodeViewer::view_type_to_config_name(type)] = {rounded(range[0], 1e4), rounded(range[1], 1e4)}; + } + view["ranges"] = std::move(ranges); + return view; +} + +} // namespace + +json preview_features(const json& statistics) +{ + const json& summary = statistics.at("summary"); + const double total = summary.at("time").get(); + const auto row = [total](double seconds) { + return json{{"time_s", rounded(seconds, 100.)}, {"percent", total > 0. ? rounded(100. * seconds / total, 10.) : 0.}}; + }; + json out = json::object(); + for (const auto& feature : summary.at("features").items()) { + json r = row(feature.value().at("time").get()); + r["g"] = rounded(feature.value().at("weight").get(), 100.); + out[feature.key()] = std::move(r); + } + json travel = row(summary.at("travel_time").get()); + travel["mm"] = rounded(summary.at("travel_distance").get(), 10.); + out["Travel"] = std::move(travel); + return out; +} + +json preview_layers(const json& statistics, bool with_features) +{ + json items = json::array(); + double below = 0.; + for (const json& layer : statistics.at("layers")) { + const double z = layer.at("z").get(); + json item{{"layer", items.size() + 1}, + {"z", z}, + {"height", rounded(z > below ? z - below : z, 1000.)}, + {"time_s", rounded(layer.at("time").get(), 100.)}, + {"g", rounded(layer.at("weight").get(), 1000.)}}; + if (with_features) { + json features = json::object(); + for (const auto& feature : layer.at("features").items()) + features[feature.key()] = rounded(feature.value().at("time").get(), 100.); + item["features"] = std::move(features); + } + items.push_back(std::move(item)); + below = z; + } + return items; +} + +json preview_objects(const json& statistics, const std::vector& object_names) +{ + json out = json::array(); + for (const json& object : statistics.at("objects")) { + const std::string name = object.at("name").get(); + json item{{"name", name}, + {"instance", object.at("instance")}, + {"g", rounded(object.at("weight").get(), 100.)}, + {"support_g", rounded(object.at("support_weight").get(), 100.)}}; + const auto first = std::find(object_names.begin(), object_names.end(), name); + if (first != object_names.end() && std::find(std::next(first), object_names.end(), name) == object_names.end()) + item["object"] = std::distance(object_names.begin(), first); + out.push_back(std::move(item)); + } + return out; +} + +bool viewer_holds(const GCodeViewer& viewer, const GCodeProcessorResult* result) +{ + return result != nullptr && viewer.has_data() && viewer.last_result_id() == result->id; +} + +json preview_state(GCodeViewer& viewer) +{ + IMSlider* layers = viewer.get_layers_slider(); + if (!viewer.has_data() || layers == nullptr) + return nullptr; + const bool silent = viewer.get_viewer().get_time_mode() == libvgcode::ETimeMode::Stealth; + return json{{"view_type", GCodeViewer::view_type_to_config_name(viewer.get_view_type())}, + {"time_mode", silent ? "silent" : "normal"}, + {"layers", {layers->GetLowerValue() + 1, layers->GetHigherValue() + 1}}, + {"z", {rounded(layers->GetLowerValueD(), 1000.), rounded(layers->GetHigherValueD(), 1000.)}}, + {"layer_count", layers->GetMaxValue() + 1}}; +} + +namespace { + +// A number for a message, as an agent writes it: 250, not 250.0. +std::string num(double v) { return v == std::floor(v) && std::abs(v) < 1e15 ? std::to_string((long long) v) : json(v).dump(); } + +bool is_rrf(const DynamicPrintConfig& printer) +{ + const auto* flavor = printer.option>("gcode_flavor"); + return flavor != nullptr && flavor->value == GCodeFlavor::gcfRepRapFirmware; +} + +bool is_belt(const DynamicPrintConfig& printer) +{ + const auto* belt = printer.option("belt_printer"); + return belt != nullptr && belt->value; +} + +// calibration_generate_test's test_model values, as each test's dialog lists its models. +std::vector calib_test_models(CalibMode mode) +{ + switch (mode) { + case CalibMode::Calib_Temp_Tower: return {"standard", "overhang"}; + case CalibMode::Calib_Input_shaping_freq: + case CalibMode::Calib_Input_shaping_damp: return {"ringing_tower", "fast_tower"}; + case CalibMode::Calib_Cornering: return {"ringing_tower", "fast_tower", "scv_v2"}; + default: return {}; + } +} + +// The rule of the test's dialog that `p` breaks, stated with the values given. +std::string calib_rule(CalibParamsError error, const Calib_Params& p, const DynamicPrintConfig& printer) +{ + const std::string range = "got start " + num(p.start) + ", end " + num(p.end) + ", step " + num(p.step); + switch (error) { + case CalibParamsError::BeltMethod: return "PA line and pattern tests are not enabled on belt printers; use method tower"; + case CalibParamsError::AccelBelowSpeed: return "every acceleration must be greater than every speed (they look swapped)"; + case CalibParamsError::Damping: + if (p.mode == CalibMode::Calib_Input_shaping_freq) + return "damping must be at least 0 and below 1; got " + num(p.start); + return "input_shaping_damp needs 0 <= start < end <= 1; got start " + num(p.start) + ", end " + num(p.end); + default: break; + } + switch (p.mode) { + case CalibMode::Calib_Temp_Tower: + return "temperature needs start at least end + 5 °C; got start " + num(p.start) + ", end " + num(p.end); + case CalibMode::Calib_Vol_speed_Tower: return "max_volumetric needs start > 0, step > 0 and end >= start + step; " + range; + case CalibMode::Calib_Retraction_tower: return "retraction needs start >= 0, step > 0 and end >= start + step; " + range; + case CalibMode::Calib_VFA_Tower: return "vfa needs start > 10, step > 0 and end >= start + step; " + range; + case CalibMode::Calib_Input_shaping_freq: + return "input_shaping_freq needs 0 <= start < end <= 500 Hz" + std::string(is_rrf(printer) ? "" : ", and so do start_y and end_y") + + "; got " + num(p.freqStartX) + "-" + num(p.freqEndX) + (is_rrf(printer) ? "" : ", Y " + num(p.freqStartY) + "-" + num(p.freqEndY)); + case CalibMode::Calib_Input_shaping_damp: + return "input_shaping_damp needs freq_x and freq_y within 0-500 Hz; got " + num(p.freqStartX) + ", " + num(p.freqStartY); + case CalibMode::Calib_Cornering: { + const bool jd = has_junction_deviation(printer); + return "cornering needs 0 <= start < end <= " + num(cornering_end_limits(printer).first) + + (jd ? " mm (junction deviation)" : " mm/s (jerk)") + "; got start " + num(p.start) + ", end " + num(p.end); + } + default: return "pressure_advance needs start >= 0, step >= 0.001 and end >= start + step; " + range; + } +} + +// Where a test's measured value belongs, from the wiki's calibration pages. +json calib_result_keys(CalibMode mode, const DynamicPrintConfig& printer) +{ + switch (mode) { + case CalibMode::Calib_Temp_Tower: return {{"type", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}}; + case CalibMode::Calib_Vol_speed_Tower: return {{"type", "filament"}, {"keys", {"filament_max_volumetric_speed"}}}; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: return {{"type", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}}; + case CalibMode::Calib_PA_Pattern: + return {{"type", "filament"}, + {"keys", {"enable_pressure_advance", "pressure_advance", "adaptive_pressure_advance", "adaptive_pressure_advance_model"}}}; + case CalibMode::Calib_Flow_Rate: return {{"type", "filament"}, {"keys", {"filament_flow_ratio"}}}; + case CalibMode::Calib_Retraction_tower: return {{"type", "filament"}, {"keys", {"filament_retraction_length"}}}; + case CalibMode::Calib_VFA_Tower: + return {{"type", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}}; + case CalibMode::Calib_Cornering: + return {{"type", "printer"}, + {"keys", has_junction_deviation(printer) ? json{"machine_max_junction_deviation"} : json{"machine_max_jerk_x", "machine_max_jerk_y"}}}; + default: + return {{"type", "printer"}, + {"keys", {"input_shaping_emit", "input_shaping_type", "input_shaping_freq_x", "input_shaping_freq_y", "input_shaping_damp_x", + "input_shaping_damp_y"}}}; + } +} + +// What VFA's auto-adjust does to `params`, as the dialog's answer Yes would: {layer_height, end, reason} when it +// changed them; a warning when the upper blocks are left above the filament's limit. +json apply_vfa_fit(Calib_Params& params, bool auto_adjust, const PresetBundle& bundle, std::vector& warnings) +{ + const DynamicPrintConfig& printer = bundle.printers.get_edited_preset().config; + const VfaSpeedFit fit = fit_vfa_speed(params, printer, bundle.prints.get_edited_preset().config, bundle.filaments.get_edited_preset().config, + auto_adjust, vfa_candidate_layer_heights(bundle.prints, printer, params.extruder_id)); + const std::string over = "the end speed (" + num(params.end) + " mm/s) exceeds the filament's maximum volumetric speed (" + + num(fit.max_vol_speed) + " mm³/s)"; + switch (fit.kind) { + case VfaSpeedFit::ReducedLayerHeight: + params.vfa_layer_height = fit.layer_height; + return {{"layer_height", fit.layer_height}, + {"reason", over + " at the default layer height (" + num(fit.default_lh) + " mm); the layer height of a profile of this printer reaches it"}}; + case VfaSpeedFit::LoweredEnd: + params.vfa_layer_height = fit.layer_height; + params.end = fit.end; + return {{"layer_height", fit.layer_height}, + {"end", fit.end}, + {"reason", over + " even at the smallest layer height of this printer's profiles; the end speed was lowered to what it reaches"}}; + case VfaSpeedFit::Clamped: + warnings.push_back(over + ", which limits the outer wall to about " + std::to_string(std::lround(fit.speed_limit)) + + " mm/s: the blocks above print at that speed" + + (auto_adjust && params.nozzle_based_resize ? " (no compatible process profile to lower the layer height to)" : + " (auto_adjust and auto_scale lower the layer height to reach it)")); + return json(); + default: return json(); + } +} + +} // namespace + +Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig& printer, std::vector& warnings) +{ + const std::string test = arg_string(args, "test"); + // The arguments each test takes, besides test, filament_slot, silent, discard_changes and preset_changes. + std::vector takes{"start", "end", "step"}; + CalibMode mode = CalibMode::Calib_None; + std::string method; + if (test == "temperature") { + mode = CalibMode::Calib_Temp_Tower; + takes = {"start", "end", "auto_scale", "test_model"}; + } else if (test == "max_volumetric") { + mode = CalibMode::Calib_Vol_speed_Tower; + } else if (test == "pressure_advance") { + method = arg_string(args, "method", "tower"); + mode = method == "tower" ? CalibMode::Calib_PA_Tower : method == "line" ? CalibMode::Calib_PA_Line : + method == "pattern" ? CalibMode::Calib_PA_Pattern : CalibMode::Calib_None; + if (mode == CalibMode::Calib_None) + throw ToolFailure("method of pressure_advance is tower, line or pattern"); + takes.push_back("method"); + if (mode == CalibMode::Calib_PA_Line) + takes.push_back("print_numbers"); + if (mode == CalibMode::Calib_PA_Pattern) + takes.insert(takes.end(), {"accelerations", "speeds"}); + } else if (test == "flow_ratio") { + method = arg_string(args, "method", "yolo"); + if (method != "pass1" && method != "pass2" && method != "yolo" && method != "yolo_perfectionist") + throw ToolFailure("method of flow_ratio is pass1, pass2, yolo or yolo_perfectionist"); + mode = CalibMode::Calib_Flow_Rate; + takes = {"method", "top_surface_pattern"}; + } else if (test == "retraction") { + mode = CalibMode::Calib_Retraction_tower; + } else if (test == "vfa") { + mode = CalibMode::Calib_VFA_Tower; + takes.insert(takes.end(), {"auto_scale", "auto_adjust"}); + } else if (test == "input_shaping_freq") { + mode = CalibMode::Calib_Input_shaping_freq; + takes = {"start", "end", "start_y", "end_y", "damping", "shaper_type", "test_model"}; + } else if (test == "input_shaping_damp") { + mode = CalibMode::Calib_Input_shaping_damp; + takes = {"freq_x", "freq_y", "start", "end", "shaper_type", "test_model"}; + } else if (test == "cornering") { + mode = CalibMode::Calib_Cornering; + takes = {"start", "end", "test_model"}; + } else { + throw ToolFailure("Unknown test \"" + test + "\""); + } + for (auto it = args.begin(); it != args.end(); ++it) + if (it.key() != "test" && it.key() != "filament_slot" && it.key() != "silent" && it.key() != "discard_changes" && + it.key() != "preset_changes" && std::find(takes.begin(), takes.end(), it.key()) == takes.end()) + throw ToolFailure(it.key() + " does not apply to " + test + (method.empty() ? "" : " with method " + method), {{"takes", takes}}); + + // The dialog's radio picks the Bowden defaults; here the printer's extruder type does. + const auto* extruder_type = printer.option("extruder_type"); + const bool bowden = extruder_type != nullptr && !extruder_type->values.empty() && extruder_type->values.front() == int(etBowden); + const bool rrf = is_rrf(printer); + Calib_Params p = calib_default_params(mode, printer, bowden); + if (mode == CalibMode::Calib_Input_shaping_freq) { + if (rrf && (args.contains("start_y") || args.contains("end_y"))) + throw ToolFailure("RepRapFirmware takes one frequency range for both axes; leave start_y and end_y out"); + p.freqStartX = arg_double(args, "start", p.freqStartX); + p.freqEndX = arg_double(args, "end", p.freqEndX); + p.freqStartY = arg_double(args, "start_y", p.freqStartX); + p.freqEndY = arg_double(args, "end_y", p.freqEndX); + p.start = arg_double(args, "damping", p.start); + } else if (mode == CalibMode::Calib_Input_shaping_damp) { + if (rrf && args.contains("freq_y")) + throw ToolFailure("RepRapFirmware takes one frequency for both axes; leave freq_y out"); + p.freqStartX = arg_double(args, "freq_x", p.freqStartX); + p.freqStartY = arg_double(args, "freq_y", p.freqStartX); + p.start = arg_double(args, "start", p.start); + p.end = arg_double(args, "end", p.end); + } else { + p.start = arg_double(args, "start", p.start); + p.end = arg_double(args, "end", p.end); + p.step = arg_double(args, "step", p.step); + } + + if (mode == CalibMode::Calib_Temp_Tower) { + // As the dialog's fields do when they lose focus: clamp, then round down to the tower's 5 °C blocks. + for (auto [name, t] : {std::make_pair("start", &p.start), std::make_pair("end", &p.end)}) { + const double given = *t; + if (const double clamped = clamp_calib_temp(*t); clamped != *t) { + *t = clamped; + warnings.push_back(std::string(name) + " " + num(given) + " °C is outside the supported range " + num(kCalibTempMin) + + "-" + num(kCalibTempMax) + " °C; clamped to " + num(*t) + " °C"); + } + if (const double rounded = round_calib_temp(*t); rounded != *t) { + warnings.push_back(std::string(name) + " " + num(*t) + " °C rounded down to " + num(rounded) + " °C, the tower's 5 °C blocks"); + *t = rounded; + } + } + } + p.nozzle_based_resize = arg_bool(args, "auto_scale", true); + if (mode == CalibMode::Calib_PA_Line) + p.print_numbers = arg_bool(args, "print_numbers", p.print_numbers); + if (mode == CalibMode::Calib_PA_Pattern) { + for (const json& a : args.value("accelerations", json::array())) + p.accelerations.push_back(a.get()); + for (const json& v : args.value("speeds", json::array())) + p.speeds.push_back(v.get()); + } + + if (const std::vector models = calib_test_models(mode); !models.empty()) { + const std::string model = arg_string(args, "test_model", models.front()); + const auto it = std::find(models.begin(), models.end(), model); + if (it == models.end()) + throw ToolFailure("test_model of " + test + " is " + boost::algorithm::join(models, ", ")); + p.test_model = int(it - models.begin()); + // The temperature dialog shows its model picker on belt printers only. + if (mode == CalibMode::Calib_Temp_Tower && args.contains("test_model") && !is_belt(printer)) + throw ToolFailure("test_model applies to the temperature test on belt printers only"); + if (mode == CalibMode::Calib_Temp_Tower && p.test_model == 1 && !boost::filesystem::exists(belt_temp_tower_asset(p))) + throw ToolFailure("No belt temperature tower model covers " + num(p.start) + " to " + num(p.end) + + " °C; use a range the tower models cover, for example 230 to 190"); + } + if (mode == CalibMode::Calib_Input_shaping_freq || mode == CalibMode::Calib_Input_shaping_damp) { + const std::vector types = shaper_type_values(printer); + p.shaper_type = arg_string(args, "shaper_type", types.front()); + if (std::find(types.begin(), types.end(), p.shaper_type) == types.end()) + throw ToolFailure("shaper_type " + p.shaper_type + " is not offered for " + + (printer.has("gcode_flavor") ? printer.opt_serialize("gcode_flavor") : std::string("this")) + + " firmware: " + boost::algorithm::join(types, ", ")); + } + + if (const CalibParamsError error = check_calib_params(p, printer); error != CalibParamsError::None) + throw ToolFailure(calib_rule(error, p, printer)); + if (mode == CalibMode::Calib_Cornering && p.end > cornering_end_limits(printer).second) + warnings.push_back("end " + num(p.end) + " is above " + num(cornering_end_limits(printer).second) + ": high values may cause layer shifts"); + return p; +} + +json calib_params_json(const json& args, const Calib_Params& p, const DynamicPrintConfig& printer) +{ + const bool rrf = is_rrf(printer); + json out; + switch (p.mode) { + case CalibMode::Calib_Temp_Tower: + out = {{"start", p.start}, {"end", p.end}, {"auto_scale", p.nozzle_based_resize}}; + if (is_belt(printer)) + out["test_model"] = calib_test_models(p.mode)[size_t(p.test_model)]; + break; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: + case CalibMode::Calib_PA_Pattern: + out = {{"method", arg_string(args, "method", "tower")}, {"start", p.start}, {"end", p.end}, {"step", p.step}}; + if (p.mode == CalibMode::Calib_PA_Line) + out["print_numbers"] = p.print_numbers; + // Left out, the pattern's are taken from the process when it runs. + if (!p.accelerations.empty()) + out["accelerations"] = p.accelerations; + if (!p.speeds.empty()) + out["speeds"] = p.speeds; + break; + case CalibMode::Calib_Flow_Rate: + out = {{"method", arg_string(args, "method", "yolo")}, {"top_surface_pattern", arg_string(args, "top_surface_pattern", "archimedeanchords")}}; + break; + case CalibMode::Calib_VFA_Tower: + out = {{"start", p.start}, {"end", p.end}, {"step", p.step}, {"auto_scale", p.nozzle_based_resize}, {"auto_adjust", arg_bool(args, "auto_adjust", true)}}; + break; + case CalibMode::Calib_Input_shaping_freq: + out = {{"start", p.freqStartX}, {"end", p.freqEndX}}; + if (!rrf) + out.update({{"start_y", p.freqStartY}, {"end_y", p.freqEndY}}); + out.update({{"damping", p.start}, {"shaper_type", p.shaper_type}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}); + break; + case CalibMode::Calib_Input_shaping_damp: + out = {{"freq_x", p.freqStartX}}; + if (!rrf) + out["freq_y"] = p.freqStartY; + out.update({{"start", p.start}, {"end", p.end}, {"shaper_type", p.shaper_type}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}); + break; + case CalibMode::Calib_Cornering: + out = {{"start", p.start}, {"end", p.end}, {"test_model", calib_test_models(p.mode)[size_t(p.test_model)]}}; + break; + default: out = {{"start", p.start}, {"end", p.end}, {"step", p.step}}; break; + } + return out; +} + +void register_plate_tools(CommandCatalog& catalog) +{ + NativeCommand calibration = mutate_tool( + "calibration_generate_test", L("Generate a calibration test"), + "Generate a Calibration menu test as its dialog's OK does: a new project named after the test, with the test model " + "and the process, filament and printer presets changed as the test needs. It prints with `filament_slot` on the " + "extruder the filament map gives it, so the filament tab points at that slot's preset. Omitted parameters take the " + "dialog's defaults (pressure advance's by the printer's extruder type), but `filament_slot` defaults to 1, not the " + "filament tab's; temperatures are clamped to 155-500 °C and rounded down to 5 °C. Fails, changing nothing, while the " + "project has unsaved changes (pass `discard_changes`) or the presets do (pass `preset_changes`). With test alone it " + "opens that test's dialog (`blocked_by_dialog`), whose OK runs it, unless `silent: true`, which runs it with the " + "dialog's defaults. Reply: test, project, params (the values used, as the journal records them), objects, names, " + "plates, `presets_changed` (its filament names the `filament_slot`, and with several extruders the 1-based extruder " + "where the filament map decides it), `result_keys` (where the measured value belongs), warnings, adjusted (vfa), and " + "discarded and modified as `project_new`. Then `plate_slice` and `project_export`. To save a measured value: " + "`project_new {discard_changes, preset_changes: \"discard\"}`, `settings_set` the value, `preset_save`.", + object_schema( + {{"test", enum_prop({"temperature", "max_volumetric", "pressure_advance", "flow_ratio", "retraction", "vfa", "cornering", + "input_shaping_freq", "input_shaping_damp"}, + "The test, as the Calibration menu names it.")}, + {"filament_slot", {{"type", "integer"}, + {"minimum", 1}, + {"description", "The physical filament (1-based slot) to print with, as the dialog's filament " + "list offers them; not a mixed one. Default 1."}}}, + {"method", enum_prop({"tower", "line", "pattern", "pass1", "pass2", "yolo", "yolo_perfectionist"}, + "`pressure_advance`: tower (default), line or pattern; `flow_ratio`: pass1, pass2, yolo (default) or " + "`yolo_perfectionist`.")}, + {"start", prop("number", "Start of the swept value: °C, mm³/s, PA, mm, mm/s (vfa), Hz (`input_shaping_freq`), " + "damping (`input_shaping_damp`), junction deviation mm or jerk mm/s (cornering).")}, + {"end", prop("number", "End of the swept value.")}, + {"step", prop("number", "Step: `max_volumetric`, `pressure_advance`, retraction, vfa.")}, + {"start_y", prop("number", "`input_shaping_freq`: start of the Y range; default the X one.")}, + {"end_y", prop("number", "`input_shaping_freq`: end of the Y range; default the X one.")}, + {"damping", prop("number", "`input_shaping_freq`: the damping ratio printed with.")}, + {"freq_x", prop("number", "`input_shaping_damp`: the X frequency, Hz.")}, + {"freq_y", prop("number", "`input_shaping_damp`: the Y frequency, Hz; default `freq_x`.")}, + {"shaper_type", prop("string", "Input shaping: an `input_shaping_type` the printer's firmware offers; default the first.")}, + {"test_model", enum_prop({"ringing_tower", "fast_tower", "scv_v2", "standard", "overhang"}, + "Input shaping: `ringing_tower` (default) or `fast_tower`; cornering: also `scv_v2`; temperature on " + "belt printers: standard (default) or overhang.")}, + {"print_numbers", prop("boolean", "`pressure_advance` line: print the values (default true).")}, + {"accelerations", array_prop({{"type", "integer"}, {"minimum", 1}}, + "`pressure_advance` pattern: one test per acceleration and speed; default the process's.")}, + {"speeds", array_prop({{"type", "integer"}, {"minimum", 1}}, "`pressure_advance` pattern: default an optimal speed.")}, + {"top_surface_pattern", enum_prop({"archimedeanchords", "monotonic"}, "`flow_ratio` (default archimedeanchords).")}, + {"auto_scale", prop("boolean", "temperature, vfa: scale the model to the nozzle (default true).")}, + {"auto_adjust", prop("boolean", "vfa: lower the layer height, else the end speed, to stay within the filament's " + "maximum volumetric speed (default true); only with `auto_scale`.")}, + {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail; for the presets', " + "see `preset_changes`.")}, + {"preset_changes", enum_prop({"keep", "discard"}, "The presets' unsaved changes: keep them for the test or drop them " + "first. Required when there are any.")}}, + {"test"}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + json recorded = args; + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); + json out = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + if (plater.printer_technology() != ptFFF) + throw ToolFailure("Calibration tests are for filament (FFF) printers"); + PresetBundle& bundle = *wxGetApp().preset_bundle; + const bool discard_presets = arg_string(args, "preset_changes") == "discard"; + // Discarded edits are gone before the test runs, so its rules and defaults are the saved printer's. + const DynamicPrintConfig& printer = discard_presets ? bundle.printers.get_selected_preset().config : + bundle.printers.get_edited_preset().config; + std::vector warnings; + Calib_Params params = calib_params_from_args(args, printer, warnings); + // The dialog's filament list offers the physical filaments; a mixed slot is none of them. + const size_t physical = std::min(bundle.num_physical_filaments(), bundle.filament_presets.size()); + const int slot = arg_int(args, "filament_slot", 1); + if (slot < 1 || size_t(slot) > physical) + throw ToolFailure(slot >= 1 && size_t(slot) <= bundle.filament_presets.size() ? + "Filament slot " + std::to_string(slot) + " is a mixed filament; a test prints with a " + + "physical one, slot 1.." + std::to_string(physical) : + "filament_slot must be 1.." + std::to_string(physical) + ", the physical filaments"); + const int extruder = calib_filament_extruder(size_t(slot - 1)); + params.filament_id = slot - 1; + params.extruder_id = std::max(extruder, 0); + require_project_discardable(discard); + // The GUI asks whether to keep or discard modified presets here; the caller answers with preset_changes. + const json before = unsaved_changes(); + if (!before.empty() && !args.contains("preset_changes")) { + const json modified = unsaved_changes_outcome(json::object()).value("modified", json::object()); + std::string list; + for (auto it = modified.begin(); it != modified.end(); ++it) + list += std::string(list.empty() ? "" : "; ") + it.key() + " \"" + it.value()["name"].get() + + "\": " + boost::algorithm::join(it.value()["keys"].get>(), ", "); + throw ToolFailure("Presets are modified (" + list + "). Pass preset_changes: \"discard\" to drop them first, or \"keep\" " + "to run the test with them", + {{"modified", modified}}); + } + // Switching the filament tab to the test's filament must not ask about another preset's changes. + const std::string& slot_preset = bundle.filament_presets[size_t(slot - 1)]; + if (!discard_presets && bundle.filaments.get_edited_preset().name != slot_preset && bundle.filaments.current_is_dirty()) + throw ToolFailure("The filament tab edits \"" + bundle.filaments.get_edited_preset().name + + "\", which has unsaved changes, and the test prints with filament slot " + std::to_string(slot) + + " (\"" + slot_preset + "\"); pass preset_changes: \"discard\", or save or drop those changes first"); + if (discard_presets && wxGetApp().has_current_preset_changes()) + wxGetApp().discard_current_preset_changes(); + const std::string switched_from = edit_filament_slot(slot); + + // The journal keeps VFA's end as asked, since the fit recomputes it from the presets. + recorded.update(calib_params_json(args, params, printer)); + const json adjusted = params.mode == CalibMode::Calib_VFA_Tower ? + apply_vfa_fit(params, arg_bool(args, "auto_adjust", true), bundle, warnings) : + json(); + const DynamicPrintConfig process_before = bundle.prints.get_edited_preset().config; + const DynamicPrintConfig filament_before = bundle.filaments.get_edited_preset().config; + const DynamicPrintConfig printer_before = bundle.printers.get_edited_preset().config; + switch (params.mode) { + case CalibMode::Calib_Temp_Tower: plater.calib_temp(params, true); break; + case CalibMode::Calib_Vol_speed_Tower: plater.calib_max_vol_speed(params, true); break; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: + case CalibMode::Calib_PA_Pattern: plater.calib_pa(params, true); break; + case CalibMode::Calib_Flow_Rate: { + const std::string method = arg_string(args, "method", "yolo"); + plater.calib_flowrate(method == "yolo" || method == "yolo_perfectionist", + method == "pass2" || method == "yolo_perfectionist" ? 2 : 1, + arg_string(args, "top_surface_pattern") == "monotonic" ? ipMonotonic : ipArchimedeanChords, + params.filament_id, params.extruder_id, true); + break; + } + case CalibMode::Calib_Retraction_tower: plater.calib_retraction(params, true); break; + case CalibMode::Calib_VFA_Tower: plater.calib_VFA(params, true); break; + case CalibMode::Calib_Input_shaping_freq: plater.calib_input_shaping_freq(params, true); break; + case CalibMode::Calib_Input_shaping_damp: plater.calib_input_shaping_damp(params, true); break; + case CalibMode::Calib_Cornering: plater.Calib_Cornering(params, true); break; + default: break; + } + + json presets_changed = json::object(); + const auto changed_preset = [&presets_changed](const char* type, const PresetCollection& presets, const DynamicPrintConfig& config_before) { + if (json changes = changed_settings(config_before, presets.get_edited_preset().config); !changes.empty()) + presets_changed[type] = {{"name", presets.get_edited_preset().name}, {"changes", std::move(changes)}}; + }; + changed_preset("process", bundle.prints, process_before); + changed_preset("printer", bundle.printers, printer_before); + presets_changed["filament"] = {{"name", bundle.filaments.get_edited_preset().name}, + {"filament_slot", slot}, + {"changes", changed_settings(filament_before, bundle.filaments.get_edited_preset().config)}}; + // The extruder, as the dialog's filament list names it: only with several, once the filament map decides it. + if (const auto* nozzles = bundle.printers.get_edited_preset().config.option("nozzle_diameter"); + nozzles != nullptr && nozzles->size() > 1 && extruder >= 0) + presets_changed["filament"]["extruder"] = extruder + 1; + if (!switched_from.empty()) + presets_changed["filament"]["tab_switched_from"] = switched_from; + if (plater.model().objects.empty()) + throw ToolFailure("The project was replaced but the test model was not added; see app_log", + {{"presets_changed", presets_changed}}); + + json reply = calib_params_json(args, params, printer); + // The pattern's defaults are the process's acceleration and an optimal speed, which the test writes there. + if (params.mode == CalibMode::Calib_PA_Pattern) + for (const auto& [key, option] : {std::make_pair("accelerations", "outer_wall_acceleration"), std::make_pair("speeds", "outer_wall_speed")}) + if (!reply.contains(key)) + if (const auto* opt = bundle.prints.get_edited_preset().config.option(option)) + reply[key] = json::array({opt->get_at(0)}); + json o = {{"test", args["test"]}, {"project", into_u8(plater.get_project_name())}, {"params", std::move(reply)}}; + o.update(objects_summary(plater)); + o["presets_changed"] = std::move(presets_changed); + o["result_keys"] = calib_result_keys(params.mode, bundle.printers.get_edited_preset().config); + if (!warnings.empty()) + o["warnings"] = warnings; + if (!adjusted.is_null()) + o["adjusted"] = adjusted; + o.update(unsaved_changes_outcome(before)); + return o; + }); + ctx.set_journal_args(std::move(recorded)); + settle(ctx); + return ToolResult::ok(out); + }); + // The Calibration menu's items, each the dialog of its test. The tab strip's calib_sf glyph is drawn white for the dark + // tab bar and vanishes on the Speed Dial's light tile, so each item borrows the matching settings-group icon instead. + struct CalibrationMenuItem + { + const char* key; + const char* title; + const char* icon; + const char* test; + CalibKind kind; + }; + // Titles are L("...")-marked here so xgettext extracts them. + static const CalibrationMenuItem calibration_menu_items[] = { + {"calib_temperature", L("Temperature Calibration"), "param_temperature", "temperature", CalibKind::Temperature}, + {"calib_max_volumetric", L("Max Volumetric Speed Calibration"), "param_volumetric_speed", "max_volumetric", + CalibKind::MaxVolumetric}, + {"calib_pressure_advance", L("Pressure Advance Calibration"), "param_flow_ratio_and_pressure_advance", "pressure_advance", + CalibKind::PressureAdvance}, + {"calib_flow_ratio", L("Flow Ratio Calibration"), "param_flow_ratio_and_pressure_advance", "flow_ratio", CalibKind::FlowRatio}, + {"calib_retraction", L("Retraction Calibration"), "param_retraction", "retraction", CalibKind::Retraction}, + {"calib_cornering", L("Cornering Calibration"), "param_precision", "cornering", CalibKind::Cornering}, + {"calib_input_shaping_freq", L("Input Shaping Frequency Calibration"), "param_resonance_avoidance", "input_shaping_freq", + CalibKind::InputShapingFreq}, + {"calib_input_shaping_damp", L("Input Shaping Damping Calibration"), "param_resonance_avoidance", "input_shaping_damp", + CalibKind::InputShapingDamp}, + {"calib_vfa", L("VFA Calibration"), "param_speed", "vfa", CalibKind::VFA}, + }; + calibration.actions = json::array(); + for (const CalibrationMenuItem& item : calibration_menu_items) + calibration.actions.push_back(NativeCommands::action(item.key, item.title, L("Calibration"), item.icon, {{"test", item.test}}, + std::string("Open the ") + item.title + + " dialog; calibration_generate_test with the test's parameters, or " + "silent, runs it with no dialog.")); + catalog.add(NativeCommands::with_person_form(std::move(calibration), [](const json& action_args) { + const std::string test = action_args.at("test"); + for (const CalibrationMenuItem& item : calibration_menu_items) + if (test == item.test) + return MenuItems::calib(item.kind); + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("Unknown test \"" + test + "\""), false}; + })); + + const json plate_prop = {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index; default: the current plate."}}; + + catalog.add(inspect_tool( + "plate_get_settings", L("Read a plate's settings"), + "Read a plate's own settings, as the Plate Settings dialog sets them: `curr_bed_type`, `print_sequence`, `spiral_mode`, " + "`first_layer_print_sequence` and `other_layers_print_sequence`; and as its filament grouping sets them on a printer " + "with several extruders: `filament_map_mode` and `filament_map` (the extruder of each filament, 1-based). Each with " + "value (the plate's own, null where it follows the global setting or Auto), effective (what the plate prints with) " + "and meta (meta.offered lists the plate types or grouping modes this printer has). All of them, or those named in " + "keys. Reply: plate, items; `unknown_keys` for the keys a plate does not have, and similar the plate keys like them.", + object_schema({{"plate", plate_prop}, + {"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return plate_settings(args); + })); + })); + + catalog.add(mutate_tool( + "plate_set_settings", L("Change a plate's settings"), + "Change a plate's own settings, which it selects and writes as the Plate Settings dialog's OK does: `curr_bed_type`, " + "`print_sequence` (\"by layer\", \"by object\"), `spiral_mode` (true asks for confirmation), `first_layer_print_sequence` " + "(every slot once, e.g. `[2, 1]`) and `other_layers_print_sequence` ([`{from: layer >= 2, to, order}`], to omitted for " + "the last layer); and as the OK of its filament grouping does, with several extruders: `filament_map_mode` (an " + "offered mode) and, with \"Manual\", `filament_map` (one extruder per filament, e.g. `[1, 2, 2]`; on a printer whose " + "extruder holds several nozzles, refused as the dialog refuses it where an extruder it uses has no nozzle of the " + "volume type its filaments print with). null returns a value to the global setting or Auto. Values are checked " + "before anything changes, and the call is one undo step. Reply: plate, applied, changed, and effective for the " + "settings the plate prints with.", + object_schema({{"plate", plate_prop}, + {"values", {{"type", "object"}, {"description", "{key: value}"}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { return set_plate_settings(args, ctx); })); + + catalog.add(inspect_tool( + "plate_list", L("List plates"), + "Plates with name, locked, current, objects (how many are on it; `object_list` lists them), and the settings they print with: `curr_bed_type`, " + "`print_sequence`, `spiral_mode`, `first_layer_print_sequence` and `other_layers_print_sequence` (null: Auto), with several " + "extruders `filament_map_mode` and `filament_map`; overrides " + "lists those the plate sets itself (`plate_set_settings`). Also origin and size, the plate's place on the bed in " + "mm: the `[x, y]` of its front left corner and its `[width, depth]`, in the bed coordinates object positions are " + "given in, so that origin plus half the size is its middle; sliced (an up-to-date slice), `wipe_tower` `[x, y]` " + "and `layer_gcode`: the plate's pauses, custom G-code, templates and filament changes, each `{z, layer, type, " + "filament, color, gcode}`; layer is the Preview slider's number, given while the plate's slice is up to date.", + object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_plates(args); })); })); + + // The plate commands made from menu items: each acts on the plate the call names, else on the current plate, as its item + // does, and its reply names the plate. + + const std::string plates_after = "plates (each plate afterwards: index, name and objects, how many stand on it) and current " + "(the current plate)"; + catalog.add(own_action(menu_command("plate_add", L("Add Plate"), + "Add a plate after the others and make it current, as Add Plate does. One undo step. " + "Reply: plate (the new plate's index), " + + plates_after + ".", + object_schema({}), json(), + [](const json&) { + AppActionRunResult added = MenuItems::plate_add(); + // Add Plate makes the plate it adds current. + if (added.level == AppActionRunResult::Level::Succeeded) { + json reply = plates_reply(); + reply["plate"] = ui_plater().get_partplate_list().get_curr_plate_index(); + added.reply = reply.dump(); + } + return added; + }), + L("Plate"), "toolbar_add_plate")); + catalog.add(reaching({"delete_plate"}, + own_action(menu_command("plate_delete", L("Delete Plate"), + "Delete a plate (plate, else the current one), as Delete Plate does. The objects on it " + "stay in the project, outside the plates, and the plates after it move down one. The " + "only plate is refused. One undo step. Reply: plate (the index it had), " + + plates_after + ".", + object_schema({{"plate", plate_prop}}), json(), plate_delete_command), + L("Plate"), "delete"))); + catalog.add(reaching({"duplicate_plate"}, + own_action(menu_command("plate_duplicate", L("Duplicate Plate"), + "Add a plate with a copy of each object on the plate (plate, else the current one), " + "placed on it as on that plate, as Duplicate Current Plate does. The new " + "plate comes last, and the current plate stays current. Refused when the project " + "holds as many plates as it can, and while slicing. One undo step. Reply: plate (the " + "plate copied), `new_plate` (the new plate's index), " + + plates_after + ".", + object_schema({{"plate", plate_prop}}), json(), plate_duplicate_command), + L("Plate"), "menu_copy"))); + // The name dialog's name, which every call but the action's gives. + NativeCommand rename = own_action(menu_command("plate_rename", L("Rename Plate"), + "Name a plate (plate, else the current one), as its name icon does: a plate other " + "than the current one is made current first. name \"\" leaves it unnamed. With no " + "arguments, as its Speed Dial action, the name dialog asks for the current plate's " + "name (`blocked_by_dialog`), and a cancelled dialog renames nothing, which the call " + "is told. The name is one undo step; the name the plate has already changes " + "nothing, the current plate included. Reply: plate and name.", + object_schema({{"plate", plate_prop}, + {"name", prop("string", "The plate's name, in place of " + "the name dialog.")}}, + {"name"}), + json(), plate_rename_command), + L("Plate"), "plate_name_edit"); + rename.input_schema = with_silent(std::move(rename.input_schema), person_forms(rename)); + catalog.add(reaching({"rename_plate", "select_plate"}, std::move(rename))); + catalog.add(reaching( + {"set_plate_locked"}, + menu_command("plate_lock", L("Toggle Plate Lock"), + "Lock or unlock a plate (plate, else the current one), as its lock icon does: locked true locks it and false " + "unlocks it; without locked it toggles, as its Speed Dial action does. An arrange of every plate leaves a " + "locked one as it is. One undo step, none when the plate is in that state already. Reply: plate, locked, and " + "changed (false when it was so already).", + object_schema({{"plate", plate_prop}, + {"locked", prop("boolean", "true locks the plate, false unlocks it. Default: the other state.")}}), + json::array({NativeCommands::action("plate_toggle_lock", L("Toggle Plate Lock"), L("Plate"), "lock_normal", + json::object(), "Lock or unlock the current plate.")}), + plate_lock_command))); + catalog.add(reaching( + {"select_plate"}, + menu_command("plate_select", L("Go to Plate"), + "Make a plate the current one, as a click on it does: plate; without it, the current plate stays current. " + "An index the project lacks is an error. Reply: plate.", + object_schema({{"plate", plate_prop}}), + json::array({NativeCommands::action("plate_goto", L("Go to Plate"), L("Plate"), "go_next_plate", {{"plate", 0}}, + "Make the first plate the current one.")}), + plate_select_command))); + + NativeCommand slice = reaching({"start_slice"}, mutate_tool( + "plate_slice", L("Slice"), + "Slice the current plate, all plates, or one plate by index, the way the toolbar's Slice button does, and wait for " + "the result (or reply with a job id when it takes longer than the reply budget). Each requested plate reports ok, " + "error, cancelled, empty or skipped; the whole operation is superseded when someone else started a slice or " + "edited the project while it ran. An ok plate has `time_s` (`silent_time_s` when the printer estimates it), " + "`filament_m` and `filament_g` including flush, `filament_cost`, layers, `max_z`, `filament_changes`, and filaments[i] for " + "slot i+1 with m, g and the grams of `model_g`, `support_g`, `flush_g` and `tower_g`. Other changes are refused until it " + "finishes; `job_cancel` stops it. The Preview tab shows the result, as after the Slice button; `preview: true`, alone " + "or with plates \"all\", is the call of Slice and Preview or Slice All Plates, whose pick starts the slice as a job " + "and shows its result as a notification.", + object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), \"all\", or a plate index."}}}, + {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Stop waiting after this long (default 1800): the call fails, and the slice goes on unless `job_cancel` stops it."}}}, + {"preview", prop("boolean", "Show the Preview tab, as every slice does: the argument of the Slice and " + "Preview and Slice All Plates actions.")}}), + [](const json& args, ToolContext& ctx) { + const json plates_arg = args.value("plates", json("current")); + if (plates_arg.is_string() && plates_arg != "all" && plates_arg != "current") + throw ToolFailure("plates is \"all\", \"current\" or a plate index"); + auto ticket = std::make_shared(); + // Held from before the wait below, so no call admitted meanwhile can change the project + // under the slice, and a cancel meanwhile finds the operation. + const uint64_t cancels_before = ctx.run_ui([&] { + ctx.begin_operation(); + return json(ui_plater().slice_cancel_seq()); + }).get(); + // A change made just before (settings_set, project_open) is validated by an update + // scheduled a moment later; a slice requested first would be refused on the old state. + poll_ui( + ctx, + [cancels_before]() -> json { + const Plater& plater = ui_plater(); + const bool pending = plater.is_background_process_update_scheduled(); + return pending && plater.slice_cancel_seq() == cancels_before ? json() : json(true); + }, + std::chrono::seconds(10), "the pending update of the slicing state"); + const bool cancelled = ctx.run_ui([&] { + Plater& plater = ui_plater(); + Ops::SliceArgs slice; + slice.all_plates = plates_arg.is_string() && plates_arg.get() == "all"; + if (plates_arg.is_number_integer()) + slice.plate = plates_arg.get(); + const Ops::Outcome> plates = Ops::slice_plates(slice); + if (!plates) + throw refused(plates.refusal()); + ticket->plates = plates.value(); + // A cancel that came while the update was pending stops the slice before it starts. + if (plater.slice_cancel_seq() != cancels_before) + return json(true); + ticket->state.started = std::chrono::steady_clock::now(); + const Ops::Outcome started = Ops::start_slice(slice); + if (!started) + throw refused(started.refusal()); + ticket->state.run_seq_before = started.value().run_seq_before; + ticket->state.revision_at_start = started.value().revision; + ticket->state.request_seq_mine = started.value().request_seq; + ticket->state.seen_running = started.value().slicing; + ticket->state.adopted_run = started.value().adopted_run; + return json(false); + }).get(); + if (cancelled) { + json plates = json::array(); + for (int index : ticket->plates) + plates.push_back({{"index", index}, {"outcome", to_string(PlateOutcome::Cancelled)}}); + return ToolResult::ok({{"status", "done"}, {"plates", std::move(plates)}}); + } + const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 1800)); + json result = poll_ui( + ctx, + [ticket]() -> json { + Plater& plater = ui_plater(); + SliceObservation obs; + obs.slicing_any = plater.is_slicing_any(); + obs.request_seq = plater.slice_request_seq(); + obs.interrupted = plater.slice_request_interrupted(ticket->state.request_seq_mine); + obs.current_revision = plater.project_revision(); + const uint64_t first = ticket->state.adopted_run != 0 ? ticket->state.adopted_run : ticket->state.run_seq_before + 1; + for (uint64_t seq = first; seq <= plater.slice_run_seq(); ++seq) + if (auto run = plater.slice_run(seq)) + obs.runs_since_start.push_back({run->seq, run->finished, run->cancelled, run->ok, run->error, + run->revision_at_finish, run->request_seq_at_finish, + run->request_seq_at_start, run->for_request, run->plate}); + ticket->state.seen_running = ticket->state.seen_running || obs.slicing_any || !obs.runs_since_start.empty(); + const TicketStatus status = slice_status(ticket->state, obs, std::chrono::steady_clock::now()); + if (status == TicketStatus::Pending) + return json(); + json out{{"status", status == TicketStatus::Done ? "done" : "superseded"}}; + PartPlateList& list = plater.get_partplate_list(); + std::vector observed; + for (int index : ticket->plates) + if (PartPlate* plate = list.get_plate(index)) + observed.push_back({index, plate->is_slice_result_valid(), !plate->has_printable_instances(), + plater.plate_validation_error(index)}); + const auto results = classify_plates(ticket->plates, observed, own_runs(ticket->state, obs)); + json plates = json::array(); + for (size_t i = 0; i < ticket->plates.size(); ++i) { + json p{{"index", ticket->plates[i]}, {"outcome", to_string(results[i].outcome)}}; + if (results[i].outcome == PlateOutcome::Ok) { + // The statistics are the plate's current result, so only while the + // project is as the operation sliced it and nobody sliced the plate since. + // They are read in this closure, which decides the outcome, since a later UI + // call would wait behind the preview's loading of the new result; the + // serializer's one pass over the moves is short next to that. + PartPlate* plate = list.get_plate(ticket->plates[i]); + const GCodeProcessorResult* gcode = plate != nullptr ? plate->get_slice_result() : nullptr; + if (gcode != nullptr && plate->is_slice_result_valid() && + plater.project_revision() == ticket->state.revision_at_start && + plate_result_is_own(ticket->plates[i], ticket->state, obs)) + p.update(plate_summary(json::parse(gcode_statistics_json(*gcode)), *gcode)); + else + p["note"] = "The plate changed after it was sliced; slice again for its statistics."; + } + if (!results[i].error.empty()) + p["error"] = results[i].error; + plates.push_back(std::move(p)); + } + out["plates"] = std::move(plates); + json notes = json::array(); + for (const NotificationSummary& n : plater.get_notification_manager()->summaries()) + if (n.level == "warning" || n.level == "error") + notes.push_back({{"level", n.level}, {"text", n.text}}); + if (!notes.empty()) + out["notifications"] = std::move(notes); + return out; + }, + timeout, "slicing to finish"); + return ToolResult::ok(result); + })); + slice.budget_ms = 45000; + slice.actions = json::array( + {NativeCommands::action("slice_and_preview", L("Slice and Preview"), L("Slice & Export"), "media_play", {{"preview", true}}, + "Slice the current plate and show the Preview tab; the call waits for the result, and a pick starts " + "the slice as a job."), + NativeCommands::action("slice_all", L("Slice All Plates"), L("Slice & Export"), "media_play", + {{"plates", "all"}, {"preview", true}}, + "Slice every plate and show the Preview tab; the call waits for the results, and a pick starts the " + "slice as a job.")}); + catalog.add(std::move(slice)); + + const json layer = {{"type", "integer"}, {"minimum", 1}, {"description", "1-based, as the Preview's layer slider numbers layers."}}; + const json z = {{"type", "number"}, {"minimum", 0}, {"description", "mm: the layer whose top is at or above it."}}; + catalog.add(mutate_tool( + "plate_set_custom_gcode", L("Set custom G-code at a layer"), + "Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview " + "layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the " + "plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects " + "it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding " + "where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not " + "undoable, as in the slider. A change invalidates the " + "plate's slice: slice again before exporting. Reply: the plate's codes as `plate_list`'s `layer_gcode` lists them, " + "each with z and layer.", + object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Default: the current plate."}}}, + {"add", array_prop(object_schema({{"layer", layer}, + {"z", z}, + {"type", enum_prop({"pause", "custom", "template", "change_filament"}, + "template runs the printer's `template_custom_gcode`.")}, + {"filament", {{"type", "integer"}, {"minimum", 1}, {"description", "`change_filament`: printed from this layer up."}}}, + {"gcode", prop("string", "custom: the G-code.")}}, + {"type"}), + "Codes to add, each with layer or z.")}, + {"remove", array_prop(object_schema({{"layer", layer}, {"z", z}}), "Codes to remove, by layer or z.")}, + {"clear", prop("boolean", "Remove every code on the plate first.")}}), + [](const json& args, ToolContext& ctx) { + // A setting changed just before is applied by an update scheduled a moment later, which may + // invalidate the plate. + poll_ui( + ctx, []() -> json { return ui_plater().is_background_process_update_scheduled() ? json() : json(true); }, + std::chrono::seconds(10), "the pending update of the slicing state"); + const int plate = ctx.run_ui([&] { return json(show_plate_layers(ui_plater(), args)); }).get(); + // A replay edits the same plate, whichever is current then. + json recorded = args; + recorded["plate"] = plate; + ctx.set_journal_args(std::move(recorded)); + // The Preview loads the plate's G-code at its first frame when it shows for the first time. + poll_ui( + ctx, + [plate]() -> json { + Plater& plater = ui_plater(); + return preview_shows_plate(plater, plate) && !plater.is_slicing_any() ? json(true) : json(); + }, + std::chrono::seconds(15), "the Preview to show plate " + std::to_string(plate) + "'s layers"); + CustomGCode::Info handed_over; + json out = ctx.run_ui([&] { return set_custom_gcode_at_layer(ui_plater(), plate, args, handed_over); }); + if (!out.is_null()) + return ToolResult::ok(out); + // The plater's handler writes the codes into the plate as the event arrives. + return ToolResult::ok(poll_ui( + ctx, + [&]() -> json { + Plater& plater = ui_plater(); + const Model& model = plater.model(); + const auto codes = model.plates_custom_gcodes.find(plate); + return codes != model.plates_custom_gcodes.end() && codes->second == handed_over ? layer_gcode_reply(plater, plate, true, args) : json(); + }, + std::chrono::seconds(5), "the layer slider's codes to reach the project")); + })); + + catalog.add(inspect_tool( + "plate_slice_stats", L("Get slice statistics"), + "What the Preview shows for a sliced plate. summary: `plate_slice`'s, plus prepare and travel time and travel " + "distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and " + "travel. layers: per layer (1-based, as `view_set`'s layer) Z, height, seconds and grams, paged; `layer_features` adds " + "each feature type's seconds. objects: grams per object instance, with its `object_list` index when its name is " + "unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, " + "and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file " + "opened for viewing reads the same.", + object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index; default the current plate."}}}, + {"include", array_prop({{"type", "string"}, {"enum", json::array({"features", "layers", "layer_features", "objects", "view"})}}, + "Parts besides the summary; default `[\"features\", \"view\"]`.")}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 1000}, {"description", "Layers per page (default 100)."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { + const std::set parts = args.contains("include") ? args["include"].get>() : + std::set{"features", "view"}; + return ToolResult::ok(ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + if (plater.printer_technology() != ptFFF) + throw ToolFailure("The Preview needs an FFF printer"); + // The background process may be rewriting a result whatever its valid flag says. + if (plater.is_slicing_any()) + throw ToolFailure("Slicing is in progress; app_wait {\"for\": \"idle\"} first"); + PartPlateList& plates = plater.get_partplate_list(); + const int current = plates.get_curr_plate_index(); + const int index = arg_int(args, "plate", current); + if (index >= plates.get_plate_count()) + throw ToolFailure(no_such_plate(index, plates.get_plate_count())); + GLCanvas3D* canvas = plater.get_preview_canvas3D(); + if (canvas == nullptr) + throw ToolFailure("The preview is not available"); + PartPlate* plate = plates.get_plate(index); + const GCodeProcessorResult* result = plate->get_slice_result(); + const bool shown = index == current && viewer_holds(canvas->get_gcode_viewer(), result); + // A G-code file opened for viewing fills the current plate's result, which the Preview + // shows, without marking the plate sliced. + const bool gcode_file = plater.only_gcode_mode() && shown; + const std::string name = "Plate " + std::to_string(index); + const std::string slice_it = "plate_slice {\"plates\": " + std::to_string(index) + "}"; + if (result == nullptr || !(plate->is_slice_result_valid() || gcode_file)) + throw ToolFailure(name + " has no up-to-date slice; " + slice_it + " first"); + // Of a project opened from a sliced 3MF, a plate the Preview has not shown keeps only the file's totals. + if (result->moves.empty()) + throw ToolFailure(name + " has no toolpaths, only the totals of a sliced 3MF; " + slice_it + " again for layer data"); + + const json statistics = json::parse(gcode_statistics_json(*result)); + const json& totals = statistics.at("summary"); + json summary = plate_summary(statistics, *result); + summary["prepare_time_s"] = std::lround(totals.at("prepare_time").get()); + summary["travel_time_s"] = std::lround(totals.at("travel_time").get()); + summary["travel_mm"] = std::lround(totals.at("travel_distance").get()); + json out{{"plate", index}, {"summary", std::move(summary)}}; + if (parts.count("features") > 0) + out["features"] = preview_features(statistics); + if (parts.count("layers") > 0 || parts.count("layer_features") > 0) + out["layers"] = page(preview_layers(statistics, parts.count("layer_features") > 0), args, 100); + if (parts.count("objects") > 0) { + std::vector names; + for (const ModelObject* object : plater.model().objects) + names.push_back(object->name); + out["objects"] = preview_objects(statistics, names); + } + if (parts.count("view") > 0) { + out["view"] = shown ? preview_view(*canvas) : json(); + if (index != current) + out["note"] = "The Preview shows plate " + std::to_string(current) + "; show plate " + std::to_string(index) + + " there (plate_select {\"plate\": " + std::to_string(index) + "}) to read its legend"; + else if (!shown) + out["note"] = "The Preview has not loaded this plate's toolpaths; show it with view_set {\"tab\": \"preview\"}"; + } + return out; + })); + })); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsPlugins.cpp b/src/slic3r/GUI/Mcp/Tools/PluginTools.cpp similarity index 99% rename from src/slic3r/GUI/Mcp/McpToolsPlugins.cpp rename to src/slic3r/GUI/Mcp/Tools/PluginTools.cpp index df1d8361a6..1d06517363 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPlugins.cpp +++ b/src/slic3r/GUI/Mcp/Tools/PluginTools.cpp @@ -1,9 +1,9 @@ -// The plugin commands: what the Plugins window lists and does (plugin_list, plugin_enable, plugin_uninstall, +// The place Plugins: what the Plugins window lists and does (plugin_list, plugin_enable, plugin_uninstall, // plugin_reload) on the operations of GUI/Operations/PluginOps.hpp, and the Plugins menu's items (plugin_install_local, // plugin_refresh). -#include "McpArguments.hpp" -#include "McpTools.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" @@ -20,7 +20,6 @@ #include #include -#include #include #include #include diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/Tools/PresetTools.cpp similarity index 67% rename from src/slic3r/GUI/Mcp/McpToolsConfig.cpp rename to src/slic3r/GUI/Mcp/Tools/PresetTools.cpp index f4d7b6d1bb..2f1bb25474 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/Tools/PresetTools.cpp @@ -1,73 +1,58 @@ -// preset_list, preset_select, preset_save, preset_delete, settings_list, settings_get, settings_set, -// plate_get_settings, plate_set_settings, project_get_settings, project_set_settings and -// plate_list: presets are selected through the same selectors a person uses, saved and deleted through the tab, and -// settings change through the Tab's own transaction (strict parsing, on_change callbacks, rollback on failure), or -// for the project's and the plates' own settings through the code of their sidebar controls and dialogs, so the UI -// and the project stay consistent. The preferences have commands of their own (McpToolsPreferences.cpp). The plate -// commands made from menu items act on the plate a call names, else on the -// current plate, through the plate operations (Operations/PlateOps.hpp); plate_add runs its menu item's function -// (NativeCommandMenuItems.hpp). +// The place Presets and settings: preset_list, preset_select, preset_save, preset_delete, settings_list, settings_get +// and settings_set. Presets are selected through the same selectors a person uses, saved and deleted through the +// tab, and settings change through the Tab's own transaction (strict parsing, on_change callbacks, rollback on +// failure), so the UI and the project stay consistent. The project's and the plates' own settings, and the +// filament list's flushing, are read and written by the code here too, through the code of their sidebar controls +// and dialogs; their commands are in ProjectTools.cpp, PlateTools.cpp and FilamentTools.cpp. Also the commands made +// from the presets' and the settings mode's menu items. -#include "slic3r/GUI/I18N.hpp" -#include "McpArguments.hpp" -#include "McpTargets.hpp" -#include "McpTools.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/CreatePresetsDialog.hpp" #include "slic3r/GUI/FilamentMapPanel.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_Factories.hpp" -#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" -#include "slic3r/GUI/IMSlider.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/MainFrame.hpp" -#include "slic3r/GUI/MixedFilamentDialog.hpp" #include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/ObjectDataViewModel.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/Operations/PresetOps.hpp" #include "slic3r/GUI/PartPlate.hpp" -#include "slic3r/GUI/PlateSettingsDialog.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/PresetComboBoxes.hpp" #include "slic3r/GUI/SavePresetDialog.hpp" #include "slic3r/GUI/SettingsIndex.hpp" #include "slic3r/GUI/Tab.hpp" #include "slic3r/GUI/WipeTowerDialog.hpp" -#include "slic3r/GUI/format.hpp" #include "libslic3r/AppConfig.hpp" -#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" -#include "libslic3r/ExtrusionEntity.hpp" -#include "libslic3r/FilamentMixer.hpp" #include "libslic3r/FlushVolCalc.hpp" -#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/libslic3r.h" #include "libslic3r/LocalesUtils.hpp" #include "libslic3r/Model.hpp" -#include "libslic3r/ParameterUtils.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" -#include "libslic3r/Utils.hpp" -#include "libslic3r/libslic3r.h" #include #include -#include #include #include #include #include -#include #include #include #include @@ -75,10 +60,8 @@ #include #include #include -#include #include #include -#include #include #include #include @@ -316,7 +299,8 @@ std::string filament_list_hint(const std::string& key) return {}; } -// Per filament slot, in config order, whether it is a mixed filament. UI thread. +} // namespace + std::vector mixed_slots() { const PresetBundle& bundle = *wxGetApp().preset_bundle; @@ -326,6 +310,8 @@ std::vector mixed_slots() return mixed; } +namespace { + // The types settings_get looks through when keys come without one: the process, filament and printer settings being // edited, since a key read for what it does rarely comes with the tab that holds it. const char* const kSearchTypes[]{"process", "filament", "printer"}; @@ -350,9 +336,8 @@ std::string type_of_key(const std::string& key) return std::find(project.begin(), project.end(), key) != project.end() ? "project" : ""; } -// Sets unknown_keys to the keys a read named that its settings, `within`, lack; type_of to where each of those is a -// setting elsewhere (type_of_key()), so the agent can ask there; and similar to the keys of `within` like each of the -// others, as settings_set's refusal gives them. UI thread. +} // namespace + void add_unknown_keys(json& out, const json& unknown, const std::vector& within) { if (unknown.empty()) @@ -373,9 +358,6 @@ void add_unknown_keys(json& out, const json& unknown, const std::vector project_offered(const std::string& key) { PresetBundle& bundle = *wxGetApp().preset_bundle; @@ -437,9 +416,6 @@ std::vector project_offered(const std::string& key) return out; } -// project_set_settings, with the project's keys, and filament_set_flushing, with the filament list's flushing -// (`flushing`). Every key is written by the code its control runs: the plate type selector, the Flushing volumes and -// Purge mode dialogs' OK, a wipe tower drag. Everything is checked before anything changes. ToolResult set_project_values(const json& values_in, ToolContext& ctx, bool flushing) { DynamicPrintConfig before; @@ -568,657 +544,7 @@ ToolResult set_project_values(const json& values_in, ToolContext& ctx, bool flus return ToolResult::ok(reply); } -ToolResult set_project_settings(const json& args, ToolContext& ctx) -{ - const json values_in = args.value("values", json::object()); - if (values_in.empty()) - throw ToolFailure("values must be a non-empty object {key: value}"); - return set_project_values(values_in, ctx, false); -} - -// What a slot's colour button does with the colour its picker gives: the slot's colour, then its -// EVT_FILAMENT_COLOR_CHANGED, which recalculates the flushing volumes where Auto flush after changing is on. UI thread. -void apply_slot_colour(std::size_t slot, const std::string& colour) -{ - auto& combos = ui_plater().sidebar().combos_filament(); - auto combo = std::find_if(combos.begin(), combos.end(), - [slot](PlaterPresetComboBox* c) { return c != nullptr && c->get_filament_idx() == int(slot); }); - if (combo == combos.end()) - throw ToolFailure("Filament slot " + std::to_string(slot + 1) + " has no colour button"); - (*combo)->sync_colour_config({colour}, false); - wxCommandEvent* evt = new wxCommandEvent(EVT_FILAMENT_COLOR_CHANGED); - evt->SetInt(int(slot)); - wxQueueEvent(&ui_plater(), evt); -} - -// filament_set_colour: one slot's colour, checked as check_filament_colours() checks a colour list. The reply reads it -// back once the change has settled. -ToolResult set_filament_colour(const json& args, ToolContext& ctx) -{ - const int slot = arg_int(args, "filament_slot", 1); - const std::string colour = arg_string(args, "colour"); - bool changed = false; - ctx.run_ui([&]() -> json { - ui_plater(); - const std::vector& current = - wxGetApp().preset_bundle->project_config.option("filament_colour")->values; - if (slot < 1 || std::size_t(slot) > current.size()) - throw ToolFailure("filament_slot must be 1.." + std::to_string(current.size())); - std::vector colours = current; - colours[std::size_t(slot) - 1] = colour; - colours = check_filament_colours(colours, current, mixed_slots()); - changed = colours[std::size_t(slot) - 1] != current[std::size_t(slot) - 1]; - if (changed) - apply_slot_colour(std::size_t(slot) - 1, colours[std::size_t(slot) - 1]); - return json(); - }); - settle(ctx); - return ToolResult::ok(ctx.run_ui([&]() -> json { - const std::vector& colours = - wxGetApp().preset_bundle->project_config.option("filament_colour")->values; - return {{"filament_slot", slot}, {"colour", colours[std::size_t(slot) - 1]}, {"changed", changed}}; - })); -} - -// filament_list: the filament list as the sidebar shows it, a row per slot in config order (the physical filaments, -// then the mixed ones), with the flushing its Flushing volumes and Purge mode buttons set. UI thread. -json filament_list() -{ - Sidebar& sidebar = ui_plater().sidebar(); - PresetBundle& bundle = *wxGetApp().preset_bundle; - const std::vector& colours = bundle.project_config.option("filament_colour")->values; - const auto* components = bundle.project_config.option("filament_mixed_components"); - const std::vector broken = sidebar.broken_mixed_filaments(); - json rows = json::array(); - for (std::size_t i = 0; i < colours.size(); ++i) { - const bool mixed = bundle.is_mixed_filament(i); - json row{{"filament_slot", i + 1}, {"mixed", mixed}, {"colour", colours[i]}}; - if (!mixed) { - const std::string name = i < bundle.filament_presets.size() ? bundle.filament_presets[i] : std::string(); - Preset* preset = bundle.filaments.find_preset(name); - std::string display; - row["preset"] = name; - row["type"] = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); - rows.push_back(std::move(row)); - continue; - } - // The components as stored, a deleted one as 0; the ratios and the gradient as the Edit Mixed Filament dialog - // reads them. - json parts = json::array(); - if (components != nullptr && i < components->size()) - for (const unsigned int component : parse_mixed_components(components->values[i])) - parts.push_back(component); - const MixedFilamentResult mix = sidebar.mixed_filament_result(i); - row["components"] = std::move(parts); - row["ratios"] = mix.ratios; - row["gradient"] = nullptr; - if (mix.gradient_enabled && mix.components.size() == 2) { - // Direction 0 starts with the first component's share high: it leads at the bottom (filament_mixed_gradient_range). - const bool first_at_bottom = mix.gradient_direction == 0; - row["gradient"] = {{"bottom", first_at_bottom ? mix.components[0] : mix.components[1]}, - {"top", first_at_bottom ? mix.components[1] : mix.components[0]}, - {"per_part", mix.per_part_gradient}, - {"curve", mix.gradient_curve.empty() ? "linear" : "custom"}}; - } - row["broken"] = std::find(broken.begin(), broken.end(), i) != broken.end(); - rows.push_back(std::move(row)); - } - const DynamicPrintConfig settings = project_settings(); - json out{{"filaments", std::move(rows)}, - {"flush_multiplier", settings.option("flush_multiplier")->values}, - {"flush_volumes_matrix", settings.option("flush_volumes_matrix")->values}, - {"prime_volume_mode", settings.opt_serialize("prime_volume_mode")}}; - if (std::vector offered = project_offered("prime_volume_mode"); !offered.empty()) - out["prime_volume_modes"] = std::move(offered); - return out; -} - -bool is_plate_setting(const std::string& key) -{ - const std::vector& keys = plate_setting_keys(); - return std::find(keys.begin(), keys.end(), key) != keys.end(); -} - -// The plate settings plate_list and an unnamed plate_get_settings show: the filament grouping only on a printer with -// several extruders, whose plates show the filament map icon (a plate keeps a mode of its own on any printer). UI thread. -std::vector listed_plate_keys() -{ - std::vector keys = plate_setting_keys(); - if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) - keys.erase(std::remove_if(keys.begin(), keys.end(), - [](const std::string& key) { return key == "filament_map_mode" || key == "filament_map"; }), - keys.end()); - return keys; -} - -// The plate the call's `plate` argument names, the current one without it. UI thread. -int scope_plate(const json& args) -{ - PartPlateList& plates = ui_plater().get_partplate_list(); - const int index = arg_int(args, "plate", plates.get_curr_plate_index()); - if (index < 0 || index >= plates.get_plate_count()) - throw ToolFailure(no_such_plate(index, plates.get_plate_count())); - return index; -} - -// How many filaments the filament grouping dialog groups: one per slot of the project. -int grouped_filaments() -{ - const auto* colours = ui_plater().config()->option("filament_colour"); - return colours != nullptr ? int(colours->size()) : 0; -} - -// The extruder of each filament as the plate's filament grouping dialog shows it: the plate's own map, else the -// project's, extruder 1 for a filament it lacks. With `volumes`, the nozzle volume type of each filament the same way, -// Standard for one it lacks. -std::vector shown_filament_map(const PartPlate& plate, bool volumes = false) -{ - const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; - std::vector map = volumes ? plate.get_real_filament_volume_maps(project) : plate.get_real_filament_maps(project); - map.resize(std::size_t(grouped_filaments()), volumes ? 0 : 1); - return map; -} - -// The filament_map_mode values the plate's filament grouping dialog offers: none on a printer with one extruder, whose -// plates show no filament map icon, and Auto For Match, which groups by the filaments a printer has loaded, once that -// printer is synced and has no filament track switch ready. UI thread. -std::vector offered_map_modes() -{ - if (wxGetApp().preset_bundle->get_printer_extruder_count() < 2) - return {}; - Plater& plater = ui_plater(); - std::vector modes{"Auto For Flush"}; - if (plater.get_machine_sync_status() && !plater.sidebar().is_fila_switch_ready()) - modes.push_back("Auto For Match"); - modes.push_back("Manual"); - return modes; -} - -// A plate's filament_map_mode as plate_set_settings takes it: an offered mode, or null, no mode of the plate's own, so -// that it follows the project's grouping (PartPlate::set_filament_map_mode() with fmmDefault; the plate's grouping -// dialog offers no page for it). UI thread. -FilamentMapMode filament_map_mode_value(const json& value) -{ - if (value.is_null()) - return fmmDefault; - const std::vector offered = offered_map_modes(); - if (!value.is_string() || std::find(offered.begin(), offered.end(), value.get()) == offered.end()) - throw ToolFailure("filament_map_mode is a mode the plate's filament grouping offers (meta.offered of plate_get_settings), " - "or null for the project's grouping" + - std::string(value == "Auto For Match" ? "; Auto For Match groups by the filaments a printer has " - "loaded, and is offered once that printer is synced" : - ""), - {{"offered", offered}}); - return FilamentMapMode(ConfigOptionEnum::get_enum_values().at(value.get())); -} - -// A plate setting in the form plate_set_settings takes: the plate's own value, null where it follows the -// project's plate type, the process, Auto or the project's filament grouping; or with `effective` what the plate -// prints with. -json plate_value(PartPlate& plate, const std::string& key, bool effective) -{ - if (key == "filament_map_mode") { - const FilamentMapMode mode = effective ? plate.get_real_filament_map_mode(wxGetApp().preset_bundle->project_config) : - plate.get_filament_map_mode(); - return mode == fmmDefault ? json() : json(ConfigOptionEnum(mode).serialize()); - } - if (key == "filament_map") { - const std::vector own = plate.get_filament_maps(); - return effective ? json(shown_filament_map(plate)) : own.empty() ? json() : json(own); - } - if (key == "curr_bed_type") { - const BedType type = plate.get_bed_type(effective); - return type == btDefault ? json() : json(ConfigOptionEnum(type).serialize()); - } - if (key == "print_sequence") { - const PrintSequence sequence = effective ? plate.get_real_print_seq() : plate.get_print_seq(); - return sequence == PrintSequence::ByDefault ? json() : json(ConfigOptionEnum(sequence).serialize()); - } - if (key == "spiral_mode") - return effective || plate.has_spiral_mode_config() ? json(plate.get_spiral_vase_mode()) : json(); - if (key == "first_layer_print_sequence") { - const std::vector order = plate.get_first_layer_print_sequence(); - return order.empty() ? json() : json(order); - } - const std::vector ranges = plate.get_other_layers_print_sequence(); - return ranges.empty() ? json() : layer_sequences_json(ranges); -} - -// Every listed setting of a plate (listed_plate_keys()): its own value, or with `effective` what it prints with. -json plate_values(PartPlate& plate, bool effective) -{ - json out = json::object(); - for (const std::string& key : listed_plate_keys()) - out[key] = plate_value(plate, key, effective); - return out; -} - -// plate_get_settings: every key, or those named, with the plate's own value and the one it prints with. UI thread. -json plate_settings(const json& args) -{ - const int index = scope_plate(args); - PartPlate& plate = *ui_plater().get_partplate_list().get_plate(index); - std::vector keys = listed_plate_keys(); - json unknown = json::array(); - if (args.contains("keys")) { - keys.clear(); - for (const json& k : args["keys"]) { - const std::string key = k.get(); - if (is_plate_setting(key)) - keys.push_back(key); - else - unknown.push_back(key); - } - } - json items = json::array(); - for (const std::string& key : keys) { - json item{{"key", key}, {"value", plate_value(plate, key, false)}, {"effective", plate_value(plate, key, true)}}; - if (arg_bool(args, "include_meta", true)) { - item["meta"] = option_meta(*print_config_def.get(key)); - if (key == "curr_bed_type") - item["meta"]["offered"] = project_offered(key); - if (key == "filament_map_mode") - item["meta"]["offered"] = offered_map_modes(); - } - items.push_back(std::move(item)); - } - json out = page(items, args, 100); - out["plate"] = index; - add_unknown_keys(out, unknown, listed_plate_keys()); - return out; -} - -// plate_set_settings. The Plate Settings dialog's values go through its OK (Plater::apply_plate_settings()) with the -// plate's other values as they are, after selecting the plate as its settings icon does; the filament grouping's go -// through the OK of the dialog the plate's filament map icon opens (Plater::open_filament_map_setting_dialog()), which -// takes no undo snapshot of its own. Everything is checked before anything changes, a key a plate's settings lack -// before the app is read, and the call is one undo step. -ToolResult set_plate_settings(const json& args, ToolContext& ctx) -{ - const json values_in = args.value("values", json::object()); - if (values_in.empty()) - throw ToolFailure("values must be a non-empty object {key: value}"); - int index = -1; - json reply = ctx.run_ui([&]() -> json { - for (auto it = values_in.begin(); it != values_in.end(); ++it) - if (!is_plate_setting(it.key())) - throw unknown_setting(it.key(), "plate", {{"keys", plate_setting_keys()}}); - Plater& plater = ui_plater(); - if (plater.printer_technology() != ptFFF || plater.only_gcode_mode()) - throw ToolFailure("Plates are a filament (FFF) feature"); - index = scope_plate(args); - PartPlateList& plates = plater.get_partplate_list(); - PartPlate& plate = *plates.get_plate(index); - const json before = plate_values(plate, false); - // The dialog's choices, starting from the plate's own. - const int own_spiral = plate.has_spiral_mode_config() ? (plate.get_spiral_vase_mode() ? 1 : 2) : 0; - BedType bed_type = plate.get_bed_type(); - PrintSequence sequence = plate.get_print_seq(); - int spiral = own_spiral; - std::vector first_layer = plate.get_first_layer_print_sequence(); - std::vector other_layers = plate.get_other_layers_print_sequence(); - const int slots = wxGetApp().filaments_cnt(); - // The filament grouping dialog's choices: its mode, and the map its Custom page sets. - const FilamentMapMode own_mode = plate.get_filament_map_mode(); - FilamentMapMode map_mode = own_mode; - std::optional> map; - const int extruders = wxGetApp().preset_bundle->get_printer_extruder_count(); - for (auto it = values_in.begin(); it != values_in.end(); ++it) { - const std::string& key = it.key(); - const json& value = it.value(); - if (key == "curr_bed_type") { - bed_type = btDefault; // "Same as Global Plate Type" - if (value.is_null()) - continue; - const std::vector offered = project_offered(key); - if (offered.empty()) - throw ToolFailure("curr_bed_type: this printer has a single plate type"); - if (!value.is_string() || std::find(offered.begin(), offered.end(), value.get()) == offered.end()) - throw ToolFailure("This printer does not offer curr_bed_type " + value.dump(), {{"offered", offered}}); - bed_type = BedType(ConfigOptionEnum::get_enum_values().at(value.get())); - } else if (key == "print_sequence") { - const auto& names = ConfigOptionEnum::get_enum_values(); - if (!value.is_null() && (!value.is_string() || names.count(value.get()) == 0)) - throw ToolFailure("print_sequence is \"by layer\", \"by object\" or null (the process's)"); - sequence = value.is_null() ? PrintSequence::ByDefault : PrintSequence(names.at(value.get())); - } else if (key == "spiral_mode") { - if (!value.is_null() && !value.is_boolean()) - throw ToolFailure("spiral_mode is true, false or null (the process's)"); - spiral = value.is_null() ? 0 : value.get() ? 1 : 2; - } else if (key == "first_layer_print_sequence" || key == "other_layers_print_sequence") { - // The dialog greys the custom orders out while a slot is a mixed filament, which prints a different - // physical filament from layer to layer. - if (!value.is_null() && wxGetApp().preset_bundle->num_mixed_filaments() > 0) - throw ToolFailure(key + " cannot be set while the project has mixed filaments (filament_list's mixed rows); " - "null sets Auto"); - if (key == "first_layer_print_sequence") - first_layer = value.is_null() ? std::vector() : filament_order(value, slots); - else - other_layers = value.is_null() ? std::vector() : layer_sequences(value, slots); - } else { - // The plate shows its filament map icon on a printer with several extruders alone. - if (extruders < 2) - throw ToolFailure(key + " groups the filaments onto the extruders of a printer that has several; this one has one"); - if (key == "filament_map_mode") { - map_mode = filament_map_mode_value(value); - } else { - if (!value.is_array() || - std::any_of(value.begin(), value.end(), [](const json& extruder) { return !extruder.is_number_integer(); })) - throw ToolFailure("filament_map is the extruder of each filament, 1-based, e.g. [1, 2, 2]"); - map = value.get>(); - } - } - } - if (map) { - const std::string mode = map_mode == fmmDefault ? std::string() : ConfigOptionEnum(map_mode).serialize(); - if (const std::string err = filament_map_error(mode, *map, grouped_filaments(), extruders); !err.empty()) - throw ToolFailure(err); - } - const bool settings = bed_type != plate.get_bed_type() || sequence != plate.get_print_seq() || - first_layer != plate.get_first_layer_print_sequence() || - other_layers != plate.get_other_layers_print_sequence() || spiral != own_spiral; - // The grouping dialog's OK: in the Manual mode the map and nozzle volume types its Custom page shows become the - // plate's own, and the slice is invalidated when the mode or what the plate prints with changes. - const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; - const std::vector old_maps = plate.get_real_filament_maps(project); - const std::vector old_volumes = plate.get_real_filament_volume_maps(project); - const std::vector new_maps = map ? *map : shown_filament_map(plate); - const std::vector new_volumes = shown_filament_map(plate, true); - const bool manual = map_mode == fmmManual; - const bool regrouped = map_mode != own_mode || old_maps != new_maps || old_volumes != new_volumes; - const bool own_map = manual && (plate.get_filament_maps() != new_maps || - plate.get_filament_volume_maps() != new_volumes); - const bool grouping_given = values_in.contains("filament_map_mode") || values_in.contains("filament_map"); - const bool grouping = grouping_given && (regrouped || own_map); - // The Custom page disables the dialog's OK while an extruder its map gives a filament the plate prints has no - // nozzle of the volume type that filament needs. - if (const std::optional shortage = manual && grouping_given ? - manual_map_nozzle_shortage(nozzle_inventory(*wxGetApp().preset_bundle), plate.get_extruders(true), new_maps, - new_volumes) : - std::nullopt) { - const std::string type = ConfigOptionEnum(shortage->volume_type).serialize(); - const char* side = shortage->extruder == 0 ? " (left)" : shortage->extruder == 1 ? " (right)" : ""; - throw ToolFailure("The manual grouping gives extruder " + std::to_string(shortage->extruder + 1) + side + - " a filament that prints with a " + type + " nozzle, and the extruder has no " + type + - " nozzle, so the filament grouping dialog does not take this map: give that filament another " - "extruder, or set the extruder's nozzles first", - {{"code", "no_nozzle_for_grouping"}, {"extruder", shortage->extruder + 1}, {"nozzle_volume_type", type}}); - } - if (settings || grouping) { - // The settings and filament map icons select their plate first; the dialogs work on the current plate. - if (index != plates.get_curr_plate_index()) - plater.select_plate(index); - Plater::SingleSnapshot single(&plater); - plater.take_snapshot("Plate Settings"); - if (settings) - plater.apply_plate_settings(index, bed_type, first_layer, other_layers, sequence, spiral); - if (grouping) { - if (map_mode != own_mode) - plate.set_filament_map_mode(map_mode); - if (manual) { - plate.set_filament_maps(new_maps); - plate.set_filament_volume_maps(new_volumes); - } - if (regrouped) { - plate.update_slice_result_valid_state(false); - plater.set_plater_dirty(true); - plater.update(); - } - } - } - const json after = plate_values(plate, false); - json applied = json::object(); - json effective = json::object(); - json changed = json::object(); - for (auto it = values_in.begin(); it != values_in.end(); ++it) { - applied[it.key()] = after.value(it.key(), json()); - effective[it.key()] = plate_value(plate, it.key(), true); - } - for (auto it = after.begin(); it != after.end(); ++it) - if (it.value() != before.value(it.key(), json())) - changed[it.key()] = it.value(); - return json{{"plate", index}, {"applied", applied}, {"changed", changed}, {"effective", effective}}; - }); - // A replay sets the same plate, whichever is current then. - if (!args.contains("plate")) { - json recorded = args; - recorded["plate"] = index; - ctx.set_journal_args(std::move(recorded)); - } - settle(ctx); - return ToolResult::ok(reply); -} - -// How many objects have an instance on plate `plate`; object_list lists them. -int objects_on_plate(const Model& model, PartPlateList& plates, int plate) -{ - int objects = 0; - for (std::size_t o = 0; o < model.objects.size(); ++o) { - const std::size_t instances = model.objects[o]->instances.size(); - std::size_t j = 0; - while (j < instances && instance_plate(plates, int(o), int(j)) != plate) - ++j; - objects += j < instances; - } - return objects; -} - -// plate_list: every plate's name, lock, settings as it prints them, what it sets itself, its objects, place on the bed, -// slice state, prime tower position and layer G-codes. UI thread. -json list_plates(const json& args) -{ - Plater& plater = ui_plater(); - PartPlateList& plates = plater.get_partplate_list(); - const Model& model = plater.model(); - const DynamicPrintConfig& project = wxGetApp().preset_bundle->project_config; - const auto* tower_x = project.option("wipe_tower_x"); - const auto* tower_y = project.option("wipe_tower_y"); - json items = json::array(); - for (int i = 0; i < plates.get_plate_count(); ++i) { - PartPlate& plate = *plates.get_plate(i); - json entry = plate_values(plate, true); - entry["index"] = i; - entry["name"] = plate.get_plate_name(); - entry["locked"] = plate.is_locked(); - entry["current"] = i == plates.get_curr_plate_index(); - json overrides = json::array(); - for (const std::string& key : listed_plate_keys()) - if (!plate_value(plate, key, false).is_null()) - overrides.push_back(key); - entry["overrides"] = std::move(overrides); - entry["objects"] = objects_on_plate(model, plates, i); - entry.update(plate_place(plate)); - entry["sliced"] = plate.is_slice_result_valid(); - if (tower_x != nullptr && tower_y != nullptr && !tower_x->empty() && !tower_y->empty()) - entry["wipe_tower"] = {tower_x->get_at(std::size_t(i)), tower_y->get_at(std::size_t(i))}; - // Layer numbers only from an up-to-date slice that no slice is rewriting. - const auto codes = model.plates_custom_gcodes.find(i); - std::vector layer_zs; - if (codes != model.plates_custom_gcodes.end() && !codes->second.gcodes.empty() && plate.is_slice_result_valid() && - !plater.is_slicing_any() && plate.get_slice_result() != nullptr) - layer_zs = gcode_layer_zs(*plate.get_slice_result()); - entry["layer_gcode"] = codes != model.plates_custom_gcodes.end() ? layer_gcode_json(codes->second, layer_zs) : json::array(); - items.push_back(std::move(entry)); - } - return page(items, args, 100); -} - -// ---- The plate commands made from menu items ---- - -// What a plate command made from menu items answers for a refusal: as information where its item told it so (no plates to -// edit, the only plate, no room for another, a slice running), else as an error. -AppActionRunResult plate_refused(const Ops::Refusal& refusal) -{ - const std::string code = refusal.code; - const bool info = refusal.kind == Ops::RefusalKind::Busy || code == "no_plates" || code == "last_plate" || - code == "too_many_plates"; - return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); -} - -// The plate a call's `plate` argument names; none without it, for the current plate. -std::optional named_plate(const json& args) -{ - return args.contains("plate") ? std::optional(arg_int(args, "plate", 0)) : std::nullopt; -} - -// The plates as a command that adds or removes one replies with them afterwards: each plate's index, name and how many -// objects stand on it, and the current plate. UI thread. -json plates_reply() -{ - Plater& plater = ui_plater(); - PartPlateList& plates = plater.get_partplate_list(); - json items = json::array(); - for (int i = 0; i < plates.get_plate_count(); ++i) - items.push_back( - {{"index", i}, {"name", plates.get_plate(i)->get_plate_name()}, {"objects", objects_on_plate(plater.model(), plates, i)}}); - return {{"plates", std::move(items)}, {"current", plates.get_curr_plate_index()}}; -} - -AppActionRunResult plate_delete_command(const json& args) -{ - const Ops::Outcome deleted = Ops::delete_plate({named_plate(args)}); - if (!deleted) - return plate_refused(deleted.refusal()); - json reply = plates_reply(); - reply["plate"] = deleted.value(); - return menu_reply(reply); -} - -AppActionRunResult plate_duplicate_command(const json& args) -{ - const Ops::Outcome made = Ops::duplicate_plate({named_plate(args)}); - if (!made) - return plate_refused(made.refusal()); - json reply = plates_reply(); - reply["plate"] = made.value().plate; - reply["new_plate"] = made.value().copy; - return menu_reply(reply); -} - -// plate_rename: a call with no arguments asks for the current plate's name in its name dialog, as the menu item does; any -// other gives it. -AppActionRunResult plate_rename_command(const json& args) -{ - Ops::RenamePlateArgs op; - op.plate = named_plate(args); - if (person_form(args)) { - if (std::optional refusal = Ops::plates_refusal()) - return plate_refused(*refusal); - PlateNameEditDialog dlg(wxGetApp().mainframe, wxID_ANY, _L("Edit Plate Name")); - dlg.set_plate_name(from_u8(ui_plater().get_partplate_list().get_curr_plate()->get_plate_name())); - // The person called it off, and knows nothing was renamed. - if (dlg.ShowModal() != wxID_YES) - return quiet_refusal(Ops::plate_not_renamed()); - op.name = into_u8(dlg.get_plate_name()); - } else { - op.name = arg_string(args, "name"); - } - const Ops::Outcome renamed = Ops::rename_plate(op); - if (!renamed) - return plate_refused(renamed.refusal()); - const PartPlate& plate = *ui_plater().get_partplate_list().get_plate(renamed.value()); - return menu_reply({{"plate", renamed.value()}, {"name", plate.get_plate_name()}}); -} - -AppActionRunResult plate_lock_command(const json& args) -{ - Ops::SetPlateLockedArgs op; - op.plate = named_plate(args); - if (args.contains("locked")) - op.locked = arg_bool(args, "locked", true); - const Ops::Outcome locked = Ops::set_plate_locked(op); - if (!locked) - return plate_refused(locked.refusal()); - return menu_reply({{"plate", locked.value().plate}, {"locked", locked.value().locked}, {"changed", locked.value().changed}}); -} - -// plate_select: Ops::select_plate() also serves the commands that select a plate on the way, so the check of the menu items, -// that the project has plates to select, is made here. -AppActionRunResult plate_select_command(const json& args) -{ - if (std::optional refusal = Ops::plates_refusal()) - return plate_refused(*refusal); - Ops::SelectPlateArgs op; - op.plate = arg_int(args, "plate", ui_plater().get_partplate_list().get_curr_plate_index()); - if (const Ops::Outcome selected = Ops::select_plate(op); !selected) - return plate_refused(selected.refusal()); - return menu_reply({{"plate", op.plate}}); -} - -// ---- The filament slot commands made from menu items, and Sync Presets ---- - -// What a filament slot command answers for a refusal: as information where its menu item told it so (no slots to change, no -// + and - buttons for the printer, no room for another slot, the only slot), else as an error. -AppActionRunResult filament_refused(const Ops::Refusal& refusal) -{ - const std::string code = refusal.code; - const bool info = code == "filaments_unavailable" || code == "one_filament_per_extruder" || code == "too_many_filaments" || - code == "last_filament_slot"; - return NativeCommands::refused(refusal, info ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Error); -} - -// What a filament slot command that ran shows a person, `message`, and replies to a call: `reply` with how many slots -// the project has afterwards. -AppActionRunResult filament_reply(const wxString& message, json reply) -{ - reply["filament_slots"] = wxGetApp().preset_bundle->filament_presets.size(); - AppActionRunResult result{AppActionRunResult::Level::Succeeded, message}; - result.reply = reply.dump(); - return result; -} - -AppActionRunResult filament_add_command(const json&) -{ - const Ops::Outcome added = Ops::add_filament_slot(); - if (!added) - return filament_refused(added.refusal()); - // TRN %1% is a filament slot number. - return filament_reply(format_wxstr(_L("Added filament slot %1%."), added.value()), {{"filament_slot", added.value()}}); -} - -AppActionRunResult filament_delete_command(const json& args) -{ - Ops::DeleteFilamentArgs op; - if (args.contains("filament_slot")) - op.filament_slot = arg_int(args, "filament_slot", 1); - if (args.contains("merge_into")) - op.merge_into = arg_int(args, "merge_into", 1); - if (args.contains("break_mix")) - op.break_mix = arg_bool(args, "break_mix", false); - const Ops::Outcome deleted = Ops::delete_filament_slot(op); - if (!deleted) - return filament_refused(deleted.refusal()); - json reply{{"filament_slot", deleted.value().filament_slot}}; - if (deleted.value().merged_into) - reply["merged_into"] = *deleted.value().merged_into; - if (!deleted.value().broken_mixed.empty()) - reply["broken_mixed"] = deleted.value().broken_mixed; - // TRN %1% is a filament slot number. - return filament_reply(format_wxstr(_L("Deleted filament slot %1%."), deleted.value().filament_slot), std::move(reply)); -} - -// filament_sync_ams: with no arguments, as its Speed Dial action, the sync dialog's run, which asks and warns; with -// mode, the sync with that choice of the dialog, which opens nothing. Reply: each slot's preset and colour afterwards. -AppActionRunResult sync_ams_command(const json& args) -{ - if (!args.contains("mode")) - return MenuItems::sync_ams(); - const Ops::AmsSyncMode mode = arg_string(args, "mode") == "map" ? Ops::AmsSyncMode::Map : Ops::AmsSyncMode::Overwrite; - const Ops::Outcome synced = Ops::sync_filaments_from_ams(mode); - if (!synced) - return NativeCommands::refused(synced.refusal(), AppActionRunResult::Level::Error); - json slots = json::array(); - for (std::size_t slot = 0; slot < synced.value().presets.size(); ++slot) { - json item{{"filament_slot", slot + 1}, {"preset", synced.value().presets[slot]}}; - if (slot < synced.value().colours.size()) - item["colour"] = synced.value().colours[slot]; - slots.push_back(std::move(item)); - } - json reply{{"mode", arg_string(args, "mode")}, {"filaments", std::move(slots)}}; - if (!synced.value().unknowns.empty()) - reply["mapped_to_generic"] = synced.value().unknowns; - return menu_reply(reply); -} +namespace { // preset_sync: signed out, a pick says to sign in, as its menu item did, and a call is refused. AppActionRunResult preset_sync_command(const json&) @@ -2286,42 +1612,6 @@ std::vector check_flush_matrix(std::vector matrix, std::size_t s return matrix; } -json plate_place(PartPlate& plate) -{ - // The plate's shape on the bed, moved to where the plate list places the plate; the extended box holds the grabber - // in front of it too. - const BoundingBoxf3& box = plate.get_bounding_box(); - const auto mm = [](double v) { return std::round(v * 1000.) / 1000. + 0.; }; - return {{"origin", {mm(box.min.x()), mm(box.min.y())}}, {"size", {mm(box.size().x()), mm(box.size().y())}}}; -} - -const std::vector& plate_setting_keys() -{ - static const std::vector keys{"curr_bed_type", - "print_sequence", - "spiral_mode", - "first_layer_print_sequence", - "other_layers_print_sequence", - "filament_map_mode", - "filament_map"}; - return keys; -} - -std::string filament_map_error(const std::string& mode, const std::vector& map, int filaments, int extruders) -{ - if (mode != "Manual") - return "filament_map is a plate's own grouping, which filament_map_mode \"Manual\" takes: the automatic modes group the " - "filaments when the plate slices, and null follows the project's grouping"; - if (int(map.size()) != filaments) - return "filament_map gives one extruder per filament: " + std::to_string(filaments) + " filaments, " + - std::to_string(map.size()) + " given"; - for (const int extruder : map) - if (extruder < 1 || extruder > extruders) - return "filament_map names extruder " + std::to_string(extruder) + "; this printer has extruders 1 to " + - std::to_string(extruders); - return {}; -} - json filter_preset_items(json items, const json& args, const std::function& fits) { const bool include_incompatible = arg_bool(args, "include_incompatible", false); @@ -2398,115 +1688,6 @@ std::string nozzle_diameter_variant(const std::vector& diameters, const return {}; } -std::vector filament_order(const json& order, int slots) -{ - std::vector out; - if (order.is_array()) - for (const json& slot : order) - out.push_back(slot.is_number_integer() ? slot.get() : 0); - std::vector sorted = out; - std::sort(sorted.begin(), sorted.end()); - std::vector every(std::size_t(std::max(slots, 0))); - std::iota(every.begin(), every.end(), 1); - if (sorted != every) - throw ToolFailure("A filament order lists every filament slot 1.." + std::to_string(slots) + " once, e.g. [2, 1]; got " + - order.dump()); - return out; -} - -std::vector layer_sequences(const json& ranges, int slots) -{ - // The dialog's "End" of a range: up to the last layer. - constexpr int last_layer = INT_MAX - 1; - if (!ranges.is_array() || ranges.empty()) - throw ToolFailure("other_layers_print_sequence is [{from, to, order}, ...] or null for Auto"); - std::vector out; - for (const json& range : ranges) { - const bool shaped = range.is_object() && range.contains("from") && range["from"].is_number_integer() && range.contains("order") && - (!range.contains("to") || range["to"].is_number_integer()) && range.size() == (range.contains("to") ? 3u : 2u); - if (!shaped) - throw ToolFailure("A range is {\"from\": layer, \"to\": layer, \"order\": [slots]}, to optional (the last layer); got " + range.dump()); - const int from = range["from"].get(); - const int to = range.value("to", last_layer); - if (from < 2) - throw ToolFailure("Ranges start at layer 2 or later; the first layer's order is first_layer_print_sequence"); - if (to < from) - throw ToolFailure("Range " + range.dump() + " ends before it starts"); - out.push_back({{from, std::min(to, last_layer)}, filament_order(range["order"], slots)}); - } - std::sort(out.begin(), out.end(), [](const LayerPrintSequence& a, const LayerPrintSequence& b) { return a.first < b.first; }); - for (std::size_t i = 1; i < out.size(); ++i) - if (out[i].first.first <= out[i - 1].first.second) - throw ToolFailure("Layer ranges overlap: one " + - (out[i - 1].first.second == last_layer ? std::string("runs to the last layer") : - "ends at layer " + std::to_string(out[i - 1].first.second)) + - ", the next starts at layer " + std::to_string(out[i].first.first)); - return out; -} - -json layer_sequences_json(const std::vector& ranges) -{ - json out = json::array(); - for (const LayerPrintSequence& range : ranges) { - json item{{"from", range.first.first}, {"order", range.second}}; - // The dialog's "End" is INT_MAX - 1, the plate tab's default INT_MAX. - if (range.first.second < INT_MAX - 1) - item["to"] = range.first.second; - out.push_back(std::move(item)); - } - return out; -} - -std::vector gcode_layer_zs(const GCodeProcessorResult& result) -{ - // GCodeViewer::load() and libvgcode::Layers::update(): layers numbered consecutively over the moves - // there are, each labelled with its last extrusion's height, or a belt print's with its print Z. - const bool belt = result.belt_tilt_angle > 0.f; - std::vector zs; - unsigned int layer = std::numeric_limits::max(); - for (std::size_t i = 1; i < result.moves.size(); ++i) { - const GCodeProcessorResult::MoveVertex& move = result.moves[i]; - if (move.layer_id != layer) { - layer = move.layer_id; - zs.push_back(belt ? double(move.print_z) : 0.); - } - if (!belt && move.type == EMoveType::Extrude && move.extrusion_role != erCustom) - zs.back() = double(move.position.z()); - } - return zs; -} - -json layer_gcode_json(const CustomGCode::Info& codes, const std::vector& layer_zs) -{ - std::vector items = codes.gcodes; - std::stable_sort(items.begin(), items.end()); - json out = json::array(); - for (const CustomGCode::Item& item : items) { - json code{{"z", std::round(item.print_z * 1000.) / 1000.}}; - // IMSlider::get_tick_from_value(z, true): the first layer whose top is at or above the height. - const auto layer = std::lower_bound(layer_zs.begin(), layer_zs.end(), item.print_z - epsilon()); - if (layer != layer_zs.end()) - code["layer"] = int(layer - layer_zs.begin()) + 1; - const bool change = item.type == CustomGCode::ToolChange || item.type == CustomGCode::ColorChange; - switch (item.type) { - case CustomGCode::PausePrint: code["type"] = "pause"; break; - case CustomGCode::Custom: code["type"] = "custom"; break; - case CustomGCode::Template: code["type"] = "template"; break; - case CustomGCode::ToolChange: code["type"] = "change_filament"; break; - case CustomGCode::ColorChange: code["type"] = "color_change"; break; - default: code["type"] = "unknown"; break; - } - if (change && item.extruder > 0) - code["filament"] = item.extruder; - if (change && !item.color.empty()) - code["color"] = item.color; - if (item.type == CustomGCode::Custom && !item.extra.empty()) - code["gcode"] = item.extra; - out.push_back(std::move(code)); - } - return out; -} - json changed_settings(const DynamicPrintConfig& before, const DynamicPrintConfig& after) { json changed = json::object(); @@ -2867,9 +2048,10 @@ std::string settings_request_error(const json& args, bool writes) return {}; } -void register_config_tools(CommandCatalog& catalog) +json read_project_settings(const json& args) { return read_target(args, project_target()); } + +void register_preset_tools(CommandCatalog& catalog) { - const json plate_prop = {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index; default: the current plate."}}; // The settings tools' type and target, as the Process panel's Global and Objects rows choose them. const json type_prop = enum_prop({"printer", "process", "filament"}, "Which settings: the printer, process or filament " "preset being edited."); @@ -3420,164 +2602,6 @@ void register_config_tools(CommandCatalog& catalog) return ToolResult::ok(result); }))); - catalog.add(inspect_tool( - "plate_get_settings", L("Read a plate's settings"), - "Read a plate's own settings, as the Plate Settings dialog sets them: `curr_bed_type`, `print_sequence`, `spiral_mode`, " - "`first_layer_print_sequence` and `other_layers_print_sequence`; and as its filament grouping sets them on a printer " - "with several extruders: `filament_map_mode` and `filament_map` (the extruder of each filament, 1-based). Each with " - "value (the plate's own, null where it follows the global setting or Auto), effective (what the plate prints with) " - "and meta (meta.offered lists the plate types or grouping modes this printer has). All of them, or those named in " - "keys. Reply: plate, items; `unknown_keys` for the keys a plate does not have, and similar the plate keys like them.", - object_schema({{"plate", plate_prop}, - {"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, - {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), - [](const json& args, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([&] { - ui_plater(); - return plate_settings(args); - })); - })); - - catalog.add(mutate_tool( - "plate_set_settings", L("Change a plate's settings"), - "Change a plate's own settings, which it selects and writes as the Plate Settings dialog's OK does: `curr_bed_type`, " - "`print_sequence` (\"by layer\", \"by object\"), `spiral_mode` (true asks for confirmation), `first_layer_print_sequence` " - "(every slot once, e.g. `[2, 1]`) and `other_layers_print_sequence` ([`{from: layer >= 2, to, order}`], to omitted for " - "the last layer); and as the OK of its filament grouping does, with several extruders: `filament_map_mode` (an " - "offered mode) and, with \"Manual\", `filament_map` (one extruder per filament, e.g. `[1, 2, 2]`; on a printer whose " - "extruder holds several nozzles, refused as the dialog refuses it where an extruder it uses has no nozzle of the " - "volume type its filaments print with). null returns a value to the global setting or Auto. Values are checked " - "before anything changes, and the call is one undo step. Reply: plate, applied, changed, and effective for the " - "settings the plate prints with.", - object_schema({{"plate", plate_prop}, - {"values", {{"type", "object"}, {"description", "{key: value}"}}}}, - {"values"}), - [](const json& args, ToolContext& ctx) { return set_plate_settings(args, ctx); })); - - catalog.add(inspect_tool( - "project_get_settings", L("Read the project's settings"), - "Read the project's own settings for its plates: the plate type (`curr_bed_type`), the prime tower position per plate " - "(`wipe_tower_x`, `wipe_tower_y`) and, with several extruders, the filament grouping (`filament_map_mode`, `filament_map`); " - "all of them, or those named in keys. The filament list's colours, mixed filaments and flushing are `filament_list`'s. " - "Each item has its value and meta; meta.offered lists the choices this printer has, and `meta.read_only` marks what is " - "set elsewhere.", - object_schema({{"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, - {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), - [](const json& args, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([&] { - ui_plater(); - return read_target(args, project_target()); - })); - })); - - catalog.add(mutate_tool( - "project_set_settings", L("Change the project's settings"), - "Change the project's own settings as their controls write them: `curr_bed_type`, as the plate type selector, and " - "wipe_tower_x/y (mm from the plate's origin, one per plate), as a prime tower's drag. The filament list's colours " - "and flushing are set with `filament_set_colour` and `filament_set_flushing`. Values are checked before anything " - "changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower " - "that did not fit.", - object_schema({{"values", {{"type", "object"}, {"description", "`{key: value}`, or `{key: {index, value}}` for one entry"}}}}, - {"values"}), - [](const json& args, ToolContext& ctx) { return set_project_settings(args, ctx); })); - - catalog.add(inspect_tool( - "plate_list", L("List plates"), - "Plates with name, locked, current, objects (how many are on it; `object_list` lists them), and the settings they print with: `curr_bed_type`, " - "`print_sequence`, `spiral_mode`, `first_layer_print_sequence` and `other_layers_print_sequence` (null: Auto), with several " - "extruders `filament_map_mode` and `filament_map`; overrides " - "lists those the plate sets itself (`plate_set_settings`). Also origin and size, the plate's place on the bed in " - "mm: the `[x, y]` of its front left corner and its `[width, depth]`, in the bed coordinates object positions are " - "given in, so that origin plus half the size is its middle; sliced (an up-to-date slice), `wipe_tower` `[x, y]` " - "and `layer_gcode`: the plate's pauses, custom G-code, templates and filament changes, each `{z, layer, type, " - "filament, color, gcode}`; layer is the Preview slider's number, given while the plate's slice is up to date.", - object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}}, - {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_plates(args); })); })); - - // The plate commands made from menu items: each acts on the plate the call names, else on the current plate, as its item - // does, and its reply names the plate. A command named as its item is that item's action, in the Speed Dial's section - // `section`. - const auto own_action = [](NativeCommand command, std::string section, std::string icon) { - command.has_own_action = true; - command.action_group = std::move(section); - command.icon = std::move(icon); - return command; - }; - const std::string plates_after = "plates (each plate afterwards: index, name and objects, how many stand on it) and current " - "(the current plate)"; - catalog.add(own_action(menu_command("plate_add", L("Add Plate"), - "Add a plate after the others and make it current, as Add Plate does. One undo step. " - "Reply: plate (the new plate's index), " + - plates_after + ".", - object_schema({}), json(), - [](const json&) { - AppActionRunResult added = MenuItems::plate_add(); - // Add Plate makes the plate it adds current. - if (added.level == AppActionRunResult::Level::Succeeded) { - json reply = plates_reply(); - reply["plate"] = ui_plater().get_partplate_list().get_curr_plate_index(); - added.reply = reply.dump(); - } - return added; - }), - L("Plate"), "toolbar_add_plate")); - catalog.add(reaching({"delete_plate"}, - own_action(menu_command("plate_delete", L("Delete Plate"), - "Delete a plate (plate, else the current one), as Delete Plate does. The objects on it " - "stay in the project, outside the plates, and the plates after it move down one. The " - "only plate is refused. One undo step. Reply: plate (the index it had), " + - plates_after + ".", - object_schema({{"plate", plate_prop}}), json(), plate_delete_command), - L("Plate"), "delete"))); - catalog.add(reaching({"duplicate_plate"}, - own_action(menu_command("plate_duplicate", L("Duplicate Plate"), - "Add a plate with a copy of each object on the plate (plate, else the current one), " - "placed on it as on that plate, as Duplicate Current Plate does. The new " - "plate comes last, and the current plate stays current. Refused when the project " - "holds as many plates as it can, and while slicing. One undo step. Reply: plate (the " - "plate copied), `new_plate` (the new plate's index), " + - plates_after + ".", - object_schema({{"plate", plate_prop}}), json(), plate_duplicate_command), - L("Plate"), "menu_copy"))); - // The name dialog's name, which every call but the action's gives. - NativeCommand rename = own_action(menu_command("plate_rename", L("Rename Plate"), - "Name a plate (plate, else the current one), as its name icon does: a plate other " - "than the current one is made current first. name \"\" leaves it unnamed. With no " - "arguments, as its Speed Dial action, the name dialog asks for the current plate's " - "name (`blocked_by_dialog`), and a cancelled dialog renames nothing, which the call " - "is told. The name is one undo step; the name the plate has already changes " - "nothing, the current plate included. Reply: plate and name.", - object_schema({{"plate", plate_prop}, - {"name", prop("string", "The plate's name, in place of " - "the name dialog.")}}, - {"name"}), - json(), plate_rename_command), - L("Plate"), "plate_name_edit"); - rename.input_schema = with_silent(std::move(rename.input_schema), person_forms(rename)); - catalog.add(reaching({"rename_plate", "select_plate"}, std::move(rename))); - catalog.add(reaching( - {"set_plate_locked"}, - menu_command("plate_lock", L("Toggle Plate Lock"), - "Lock or unlock a plate (plate, else the current one), as its lock icon does: locked true locks it and false " - "unlocks it; without locked it toggles, as its Speed Dial action does. An arrange of every plate leaves a " - "locked one as it is. One undo step, none when the plate is in that state already. Reply: plate, locked, and " - "changed (false when it was so already).", - object_schema({{"plate", plate_prop}, - {"locked", prop("boolean", "true locks the plate, false unlocks it. Default: the other state.")}}), - json::array({NativeCommands::action("plate_toggle_lock", L("Toggle Plate Lock"), L("Plate"), "lock_normal", - json::object(), "Lock or unlock the current plate.")}), - plate_lock_command))); - catalog.add(reaching( - {"select_plate"}, - menu_command("plate_select", L("Go to Plate"), - "Make a plate the current one, as a click on it does: plate; without it, the current plate stays current. " - "An index the project lacks is an error. Reply: plate.", - object_schema({{"plate", plate_prop}}), - json::array({NativeCommands::action("plate_goto", L("Go to Plate"), L("Plate"), "go_next_plate", {{"plate", 0}}, - "Make the first plate the current one.")}), - plate_select_command))); - // ---- The presets and settings commands made from menu items ---- using NativeCommands::action; const std::string preset_file = "a preset .json, a .zip of them, an .orca_printer, .orca_filament or .orca_bundle, or a .gcode"; @@ -3657,211 +2681,6 @@ void register_config_tools(CommandCatalog& catalog) // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. developer_mode.listed = false; catalog.add(std::move(developer_mode)); - - // ---- The filament slot and printer commands made from menu items ---- - // The + and - buttons above the filament list and a slot's Delete menu item, each named as the button or menu item is, in the Speed - // Dial's section Filament. - const std::string slot_buttons = "Refused for a printer that has one filament per extruder, which shows no + and - buttons."; - catalog.add(inspect_tool( - "filament_list", L("List the filaments"), - "Read the filament list as the sidebar shows it. filaments has a row per slot in config order, the physical " - "filaments first, then the mixed ones: `filament_slot` (1-based), mixed, colour (#RRGGBB) and, for a physical " - "filament, preset and type; for a mixed filament, components (the physical slots it mixes, 1-based, 0 for one " - "deleted), ratios (whole percentages, as `filament_add_mixed` takes them), gradient (null, or `{bottom, top: the " - "components that lead at the bottom and at the top, per_part, curve: linear or custom}`) and broken (a component " - "deleted or of another filament type: the sidebar marks it, slicing an object on it is refused, and " - "`filament_edit_mixed` repairs it). Then the flushing the list's Flushing volumes and Purge mode buttons set: " - "`flush_multiplier` (one per nozzle), `flush_volumes_matrix` (per nozzle, slots x slots from row to column in config " - "order over every slot, before the multiplier: the dialog shows each entry multiplied by its nozzle's multiplier, " - "and the G-code purges that product) and `prime_volume_mode`, with `prime_volume_modes` where the printer offers a " - "choice. The printer keeps all of it across new projects and restarts; a saved project keeps its own.", - object_schema({}), - [](const json&, ToolContext& ctx) { - return ToolResult::ok(ctx.run_ui([] { - ui_plater(); - return filament_list(); - })); - })); - catalog.add(reaching({"add_filament_slot"}, - own_action(menu_command("filament_add", L("Add Filament Slot"), - "Add a filament slot, as the + button above the filament list does. It takes the next " - "colour and the last slot's preset (change them with `filament_set_colour` and " - "`preset_select` `filament_slot`). It goes after the physical slots: mixed " - "filaments move up by one, and objects on them follow. " + - slot_buttons + " Reply: `filament_slot` (the new slot) and `filament_slots` (how many the " - "project has).", - object_schema({}), json(), filament_add_command), - L("Filament"), "add_filament"))); - catalog.add(reaching( - {"delete_filament_slot"}, - own_action(menu_command("filament_delete", L("Delete Filament Slot"), - "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; " - "with `merge_into`, as its Merge with item does, the objects on it taking that slot. The slots after " - "it move down by one. A mixed filament (`filament_list`'s mixed rows) is deleted as the mixed " - "filament list deletes it, and not merged. A physical filament that a mixed filament mixes is " - "deleted as the sidebar deletes it: the mix is broken (`broken_mixed`) until `filament_edit_mixed` " - "names its filaments again. A merge into a mixed filament that mixes the slot asks first, as Merge " - "with does, and replies `blocked_by_dialog`, unless `break_mix` answers: `true` merges, `false` refuses " - "(`mixed_uses_slot`). Refused: the only physical slot, and a mixed filament while one physical " - "slot is left, where the sidebar hides the mixed filaments (`filament_add` first). " + - slot_buttons + " Not in the undo history. Reply: `filament_slot` (the slot deleted), `merged_into` " - "(the slot its objects went to, as numbered afterwards), `filament_slots`, and " - "`broken_mixed` (the mixed filaments broken afterwards, as numbered then) where " - "there are any.", - object_schema({{"filament_slot", {{"type", "integer"}, - {"minimum", 1}, - {"description", "The 1-based filament slot. Default: the last " - "physical slot, as the - button."}}}, - {"merge_into", {{"type", "integer"}, - {"minimum", 1}, - {"description", "The 1-based slot the objects on it go to, as Merge " - "with does. Default: they take the first filament."}}}, - {"break_mix", prop("boolean", "The answer to Merge with's question about a merge into " - "a mixed filament that mixes the slot: `true` merges, " - "`false` merges nothing. Default: the question opens.")}}), - json(), filament_delete_command), - L("Filament"), "delete_filament"))); - - // The Add and Edit Mixed Filament dialogs' controls, for an agent that drives a dialog to set a gradient. - const std::string mixed_dialog = - "replies `blocked_by_dialog`. Its controls are named `filament_1` to `filament_3` (the components), gradient, " - "`gradient_direction` (item 0 puts the first filament at the bottom, item 1 the second) and `per_part_gradient`, for " - "`widget_set_value` with within the dialog's title; the gradient shows for a mix of two filaments only, and its curve " - "is drawn, changed only by dragging it (`mouse_gesture`). Its OK makes what it shows; Cancel changes nothing."; - const auto mix_props = [](const char* components) { - return std::vector{ - {"components", array_prop({{"type", "integer"}, {"minimum", 1}}, components)}, - {"ratios", array_prop({{"type", "integer"}, {"exclusiveMinimum", 0}}, - "Each component's share in percent, in the order of components, adding up to 100.")}}; - }; - const auto mix_args = [](const json& args, std::vector& components, std::vector& ratios) { - for (const json& component : args.value("components", json::array())) - components.push_back(component.get()); - for (const json& ratio : args.value("ratios", json::array())) - ratios.push_back(ratio.get()); - }; - const std::vector add_props = mix_props("The physical filament slots to mix, 1-based, two or more, each once, of " - "filaments of one type. Omitted with ratios: the dialog opens."); - NativeCommand mixed = reaching( - {"add_mixed_filament"}, - mutate_tool( - "filament_add_mixed", L("Add Mixed Filament"), - "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as " - "the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots " - "(1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to " - "100. It goes after every other slot. A mix the project has already is not added again: the reply names its " - "slot. With neither components nor ratios it opens the Add Mixed Filament dialog, as the sidebar's button does, " - "and " + mixed_dialog + " Not in the undo history. Reply: `filament_slot` (1-based, where one was added or " - "found) and added (false for a mix the project had, or a dialog cancelled).", - object_schema({add_props[0], add_props[1]}), - [mix_args](const json& args, ToolContext& ctx) { - Ops::AddMixedFilamentArgs op; - mix_args(args, op.components, op.ratios); - json reply = ctx.run_ui([&] { - ui_plater(); - const Ops::Outcome mixed = Ops::add_mixed_filament(op); - if (!mixed) - throw refused(mixed.refusal()); - json out{{"added", mixed.value().added}}; - if (mixed.value().filament_slot > 0) - out["filament_slot"] = mixed.value().filament_slot; - return out; - }); - settle(ctx); - return ToolResult::ok(reply); - })); - mixed.examples = json::parse(R"json([ - {"title": "Mix the first two filaments half and half", "calls": [ - {"tool": "filament_add_mixed", "args": {"components": [1, 2], "ratios": [50, 50]}}]}, - {"title": "Mix three filaments, the third the most", "calls": [ - {"tool": "filament_add_mixed", "args": {"components": [1, 2, 3], "ratios": [25, 25, 50]}}]}])json"); - catalog.add(std::move(mixed)); - - const std::vector edit_props = mix_props("The physical filament slots it mixes from now on, as `filament_add_mixed` " - "takes them. Omitted with ratios: the dialog opens."); - NativeCommand edit_mixed = reaching( - {"edit_mixed_filament"}, - mutate_tool( - "filament_edit_mixed", L("Edit Mixed Filament"), - "Change a mixed filament (`filament_list`'s mixed rows) as the Edit Mixed Filament dialog's OK does: components " - "and ratios as `filament_add_mixed` takes them. The slot keeps its number and the objects on it, and its colour " - "becomes the blend; a gradient stays for a mix of two filaments and goes for more, as the dialog shows none for " - "them. An edit that names its filaments again repairs a broken mix. With `filament_slot` alone it opens the Edit " - "Mixed Filament dialog on the mix, as a click on its swatch does, and " + mixed_dialog + - " Not in the undo history. Reply: `filament_slot` and changed.", - object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The mixed filament's 1-based slot."}}}, - edit_props[0], edit_props[1]}, - {"filament_slot"}), - [mix_args](const json& args, ToolContext& ctx) { - Ops::EditMixedFilamentArgs op; - op.filament_slot = arg_int(args, "filament_slot", 1); - mix_args(args, op.components, op.ratios); - json reply = ctx.run_ui([&] { - ui_plater(); - const Ops::Outcome edited = Ops::edit_mixed_filament(op); - if (!edited) - throw refused(edited.refusal()); - return json{{"filament_slot", edited.value().filament_slot}, {"changed", edited.value().changed}}; - }); - settle(ctx); - return ToolResult::ok(reply); - })); - edit_mixed.examples = json::parse(R"json([ - {"title": "Make the mixed filament in slot 3 mostly its first filament", "calls": [ - {"tool": "filament_edit_mixed", "args": {"filament_slot": 3, "components": [1, 2], "ratios": [75, 25]}}]}])json"); - catalog.add(std::move(edit_mixed)); - - catalog.add(mutate_tool( - "filament_set_colour", L("Set a filament's colour"), - "Set a physical filament slot's colour, as its colour button's picker does: colour is #RRGGBB. Where Auto flush " - "after changing is on, the flushing volumes are recalculated, so set `flush_volumes_matrix` (`filament_set_flushing`) " - "after the colours. A mixed filament's colour is its components' blend and is not set. Reply: `filament_slot`, " - "colour (as stored, upper case) and changed.", - object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The 1-based filament slot."}}}, - {"colour", prop("string", "#RRGGBB.")}}, - {"filament_slot", "colour"}), - [](const json& args, ToolContext& ctx) { return set_filament_colour(args, ctx); })); - - catalog.add(mutate_tool( - "filament_set_flushing", L("Set the flushing"), - "Change the flushing the filament list's Flushing volumes and Purge mode buttons set, as their dialogs' OK does, " - "any of: `flush_multiplier` (one per nozzle, or one value for all, within the Flushing volumes dialog's range), " - "`flush_volumes_matrix` (per nozzle, slots x slots from row to column in config order over every slot, before the " - "multiplier; whole, or one entry as `{index, value}`; a mixed filament's entries, which are never flushed, must be " - "given as they are) and `prime_volume_mode` (one of `filament_list`'s `prime_volume_modes`). A colour change " - "(`filament_set_colour`) can recalculate the matrix, so set it after the colours. Values are checked before " - "anything changes. Reply: applied and changed.", - object_schema({{"flush_multiplier", {{"type", {"number", "array"}}, {"description", "One value, or one per nozzle."}}}, - {"flush_volumes_matrix", {{"type", {"array", "object"}}, {"description", "The whole matrix, or `{index, value}`."}}}, - {"prime_volume_mode", prop("string", "The purge mode, e.g. \"Default\".")}}), - [](const json& args, ToolContext& ctx) { - json values = json::object(); - for (const char* key : {"flush_multiplier", "flush_volumes_matrix", "prime_volume_mode"}) - if (args.contains(key)) - values[key] = args[key]; - if (values.empty()) - throw ToolFailure("Give flush_multiplier, flush_volumes_matrix or prime_volume_mode"); - return set_project_values(values, ctx, true); - })); - - const std::string ams = "Synchronize the filament list from the connected printer's AMS."; - NativeCommand sync_ams = reaching( - {"sync_filaments_from_ams"}, - menu_command("filament_sync_ams", L("Synchronize Filament List from AMS"), - ams + " With mode, as the sync dialog's Synchronize now does with that choice, without the dialog: map maps " - "each of the project's filaments to a slot, as the dialog's Mapping first does, which takes a project " - "with objects; overwrite replaces the filament list with the slots' filaments. Called with no arguments, " - "as its Speed Dial action, it opens the sync dialog where the project has objects (`blocked_by_dialog`), and " - "a warning where it cannot sync. With no printer connected, no AMS or no filament it is refused, saying so. " - "Not in the undo history. Reply: mode, filaments (each slot's preset and colour afterwards) and " - "`mapped_to_generic` (slots whose filament is unknown, mapped to a generic preset).", - object_schema({{"mode", enum_prop({"map", "overwrite"}, "The sync dialog's choice: map or overwrite.")}}), - json::array({action("sync_ams", L("Synchronize Filament List from AMS"), L("Printer"), "ams_fila_sync", json::object(), - ams)}), - sync_ams_command)); - // It reads the connected printer's AMS. - sync_ams.open_world = true; - catalog.add(std::move(sync_ams)); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsInstall.cpp b/src/slic3r/GUI/Mcp/Tools/PrinterTools.cpp similarity index 51% rename from src/slic3r/GUI/Mcp/McpToolsInstall.cpp rename to src/slic3r/GUI/Mcp/Tools/PrinterTools.cpp index a21548e017..52ce810dcb 100644 --- a/src/slic3r/GUI/Mcp/McpToolsInstall.cpp +++ b/src/slic3r/GUI/Mcp/Tools/PrinterTools.cpp @@ -1,15 +1,20 @@ -// printer_list_models, printer_install and printer_uninstall: what the Printer Selection dialog lists and its Confirm -// installs; filament_install and filament_uninstall: what the System Filaments dialog's Confirm installs. On the -// operations of GUI/Operations/InstallOps.hpp. +// The place Printers and prints. printer_list_models, printer_install and printer_uninstall: what the Printer +// Selection dialog lists and its Confirm installs, on the operations of GUI/Operations/InstallOps.hpp. The printing +// commands: print_start and printer_send open the dialog the Print button's Print and Send open for the selected +// printer, and printer_test_host asks the printer's print host whether it answers, as the Test button of its +// connection dialog does. What is printed or sent is left to the dialog, which a client answers with the dialog +// tools. printer_status reads what the Device tab shows of the printer it is connected to, and print_pause, +// print_resume and print_stop send that printer the tab's job commands. -#include "McpTools.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Operations/InstallOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PresetOps.hpp" +#include "slic3r/GUI/Operations/PrinterOps.hpp" #include @@ -17,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -115,58 +121,88 @@ CommandFn change_printers(bool install) }; } -// What the filament commands reply when an operation refuses: the names a refusal carries under the key that says -// what they are. -ToolFailure filament_refused(const Ops::Refusal& refusal) +json temperature(const Ops::Temperature& t) { - const std::string code = refusal.code; - if (code == "no_such_filament" || code == "no_filament_vendor") - return refused(refusal, "preset_list {type: \"filament\", include_uninstalled: true} lists the system filaments.", "similar"); - if (code == "fits_no_printer") - return refused(refusal, "Name one of its presets.", "presets"); - if (code == "no_matching_filament") - return refused(refusal, "", "filament_types"); - if (code == "filament_in_use") - return refused(refusal, "Select another filament for the slot first (preset_select with filament_slot).", "presets"); - return refused(refusal); + return {{"current", t.current ? json(*t.current) : json()}, {"target", t.target ? json(*t.target) : json()}}; } -// filament_install's and filament_uninstall's function: the names, or the vendor and filament type, a call gives. -CommandFn change_filaments(bool install) +// print_pause, print_resume or print_stop: `command` sent to the connected printer. +NativeCommand job_command(const char* name, const char* title, Ops::JobCommand command, const std::string& description, + const char* examples, bool destructive) { - return [install](const json& args, ToolContext& ctx) { - Ops::InstallFilamentsArgs op; - if (const auto names = args.find("names"); names != args.end()) - for (const json& name : *names) - op.names.push_back(name.get()); - op.vendor = arg_string(args, "vendor"); - op.filament_type = arg_string(args, "filament_type"); - if (op.names.empty() && op.vendor.empty() && op.filament_type.empty()) - throw ToolFailure("Give names, or vendor and filament_type"); - if (!op.names.empty() && (args.contains("vendor") || args.contains("filament_type"))) - throw ToolFailure("Give names, or vendor and filament_type, not both"); - if (op.names.empty() && (op.vendor.empty() || op.filament_type.empty())) - throw ToolFailure("vendor and filament_type go together"); - json reply = ctx.run_ui([&] { - ui_plater(); - const Ops::Outcome done = install ? Ops::install_filaments(op) : Ops::uninstall_filaments(op); - if (!done) - throw filament_refused(done.refusal()); - json out{{install ? "installed" : "uninstalled", done.value().changed}}; - if (!done.value().unchanged.empty()) - out[install ? "installed_already" : "not_installed"] = done.value().unchanged; - if (!done.value().defaults_installed.empty()) - out["filaments_installed"] = done.value().defaults_installed; - return out; - }); - settle(ctx); - return ToolResult::ok(reply); - }; + NativeCommand job = mutate_tool( + name, title, + description + " The printer's new state arrives when it reports: read it with `printer_status`. Reply: printer (its " + "name), state (the state it was in) and sent. A replay sends the command again.", + object_schema({}), + [command](const json&, ToolContext& ctx) { + json reply = ctx.run_ui([command] { + const Ops::Outcome sent = Ops::send_job_command(Ops::connected_printer(), command); + if (!sent) + throw refused(sent.refusal()); + return json{{"printer", sent.value().printer}, {"state", sent.value().state}, {"sent", true}}; + }); + return ToolResult::ok(std::move(reply)); + }, + destructive); + // It sends the printer a command. + job.open_world = true; + job.examples = json::parse(examples); + return reaching({"send_job_command"}, std::move(job)); +} + +json plates_prop(const char* all) +{ + return {{"type", {"string", "integer"}}, + {"description", std::string("\"current\" (default), a plate index, which is selected first, or \"all\" for ") + all + + ", where the Print button offers it."}}; } } // namespace -void register_install_tools(CommandCatalog& catalog) +json printer_status_reply(const std::optional& status) +{ + if (!status) + return {{"connected", false}}; + json nozzles = json::array(); + for (const Ops::Temperature& nozzle : status->nozzles) + nozzles.push_back(temperature(nozzle)); + return {{"connected", true}, + {"name", status->name}, + {"model", status->model.empty() ? json() : json(status->model)}, + {"printer_type", status->printer_type}, + {"online", status->online}, + {"state", status->state}, + {"stage", status->stage}, + {"percent", status->percent}, + {"remaining_seconds", status->remaining_seconds}, + {"layer", status->layer}, + {"total_layers", status->total_layers}, + {"file", status->file}, + {"error_code", status->error_code}, + {"temperatures", + {{"nozzles", std::move(nozzles)}, {"bed", temperature(status->bed)}, {"chamber", temperature(status->chamber)}}}}; +} + +std::string read_print_plates(const json& args, std::optional& plate, bool& all) +{ + plate.reset(); + all = false; + if (!args.contains("plates")) + return {}; + const json& plates = args.at("plates"); + if (plates.is_number_integer()) { + plate = plates.get(); + return {}; + } + if (plates.is_string() && plates.get() == "all") + all = true; + else if (!plates.is_string() || plates.get() != "current") + return "plates is \"current\", \"all\" or a plate index"; + return {}; +} + +void register_printer_tools(CommandCatalog& catalog) { const json models_prop = { {"type", "array"}, @@ -288,50 +324,122 @@ void register_install_tools(CommandCatalog& catalog) {"tool": "printer_uninstall", "args": {"models": [{"vendor": "Goofoo", "model": "Goofoo Velo+"}]}}]}])json"); catalog.add(std::move(uninstall)); - const json names_prop = {{"type", "array"}, - {"minItems", 1}, - {"items", {{"type", "string"}}}, - {"description", "System filaments: a preset's name, or the short name the filament selector " - "shows (\"Bambu PLA Basic\"), which stands for its preset of every installed " - "printer it fits."}}; - const std::string kept = "The app keeps an installed printer's default filaments installed while no other installed filament " - "fits it: where the call leaves one so, they are installed again and listed under " - "`filaments_installed`, as the next start would. The other filaments, and the presets' unsaved " - "changes, are kept, and the selectors are refreshed. Not in the undo history."; - NativeCommand install_filaments = reaching( - {"install_filaments"}, - mutate_tool("filament_install", L("Install system filaments"), - "Install system filaments, for good, as ticking them in the System Filaments dialog and pressing Confirm " - "does: the filament selectors offer them. Name them by names, or with vendor and `filament_type` every " - "filament of that vendor and type that an installed printer fits. `preset_list {type: \"filament\", " - "include_uninstalled: true}` lists the system filaments, those not installed with `installed: false`. A name " - "no filament has is refused with the closest names. " + - kept + " Reply: installed (the presets installed), `installed_already`, `filaments_installed`.", - object_schema({{"names", names_prop}, - {"vendor", prop("string", "With `filament_type`, in place of names: a filament maker (\"Bambu " - "Lab\", \"Generic\"), in any case.")}, - {"filament_type", prop("string", "With vendor: a filament type (\"PLA\"), in any case.")}}), - change_filaments(true))); - install_filaments.examples = json::parse(R"json([ - {"title": "Install a filament by the name the selector shows", "calls": [ - {"tool": "preset_list", "args": {"type": "filament", "include_uninstalled": true, "query": "PETG HF"}}, - {"tool": "filament_install", "args": {"names": ["Bambu PETG HF"]}}]}, - {"title": "Install every filament of a vendor and type", "calls": [ - {"tool": "filament_install", "args": {"vendor": "Generic", "filament_type": "PETG"}}]}])json"); - catalog.add(std::move(install_filaments)); + NativeCommand print = mutate_tool( + "print_start", L("Print plate"), + "Open the dialog the Print button's Print plate opens for the selected printer, for the current plate or the plate " + "plates names, or with plates \"all\" Print all's. For a printer on the Bambu network or with printer agents it is the " + "Print dialog, which leaves the printer, bed levelling, flow calibration, timelapse, the AMS mapping and the button " + "that prints to it; for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...) it is the host's Send " + "G-code to printer host dialog, with Upload and Upload and Print. As the button does, it first applies the slicing " + "result, and it is refused (`not_sliced`) where the button would be disabled, as for a plate not sliced: slice with " + "`plate_slice` first. The call replies `blocked_by_dialog` while the dialog is open: read and set its fields with " + "`widget_list` and `widget_set_value`, and press its buttons with `dialog_answer`. Nothing prints until its button is " + "pressed. Refused: `all_plates_not_offered` for plates \"all\" where the button offers no Print all, `no_print_host` for " + "a printer with no print host address.", + object_schema({{"plates", plates_prop("Print all")}}), [](const json& args, ToolContext& ctx) { + Ops::OpenPrintDialogArgs op; + if (const std::string err = read_print_plates(args, op.plate, op.all); !err.empty()) + throw ToolFailure(err); + ctx.run_ui([&] { + if (const Ops::Outcome opened = Ops::open_print_dialog(op); !opened) + throw refused(opened.refusal()); + return json(); + }); + settle(ctx); + return ToolResult::ok(); + }); + // Its dialog prints on a printer. + print.open_world = true; + print.examples = json::parse(R"json([ + {"title": "Open the Print dialog for the current plate", "calls": [{"tool": "print_start", "args": {}}]}, + {"title": "Print the second plate after slicing it", "calls": [ + {"tool": "plate_slice", "args": {"plates": 1}}, {"tool": "print_start", "args": {"plates": 1}}]}])json"); + catalog.add(reaching({"open_print_dialog"}, std::move(print))); - NativeCommand uninstall_filaments = reaching( - {"uninstall_filaments"}, - mutate_tool("filament_uninstall", L("Uninstall system filaments"), - "Uninstall system filaments, for good, as unticking them in the System Filaments dialog and pressing " - "Confirm does: the filament selectors no longer offer them. names as `filament_install` takes them. A " - "filament a slot of the project uses is refused, naming the slot. " + - kept + " Reply: uninstalled (the presets uninstalled), `not_installed`, `filaments_installed`.", - object_schema({{"names", names_prop}}, {"names"}), change_filaments(false))); - uninstall_filaments.examples = json::parse(R"json([ - {"title": "Uninstall a filament", "calls": [ - {"tool": "filament_uninstall", "args": {"names": ["Bambu PETG HF"]}}]}])json"); - catalog.add(std::move(uninstall_filaments)); + const std::string send = + "Open the dialog the Print button's Send opens for the selected printer, for the current plate or the plate plates " + "names. For a printer on the Bambu network or with printer agents it is the dialog that sends the sliced plate to the " + "printer's storage (with plates \"all\", Send all's), which leaves the printer, the file name, the storage and the " + "button that sends to it, and is refused (`not_sliced`) for a plate not sliced. For a printer with a print host " + "(OctoPrint, Moonraker, PrusaLink, Duet...) it is the Send G-code to printer host dialog: set the file name with " + "`widget_set_value` and press Upload or Upload and Print with `dialog_answer`; the plate is sliced if needed, then " + "uploaded in the background: `app_state.uploads` shows the row's state, and a failed upload also opens an error " + "dialog. The call replies `blocked_by_dialog` while the dialog is open. A replay sends again. Refused: " + "`all_plates_not_offered` for plates \"all\" where the button offers no Send all, `no_print_host` for a printer with no " + "print host address."; + const json send_action = NativeCommands::action("send_gcode", L("Send G-code to printer host"), L("Slice & Export"), "printer", + json::object(), send); + NativeCommand printer_send = reaching({"open_print_dialog"}, + menu_command("printer_send", L("Send G-code to printer host"), send, + object_schema({{"plates", plates_prop("Send all")}}), json::array({send_action}), + [](const json& args) { return MenuItems::send_gcode(args); })); + // It uploads to the printer's print host, or sends to the printer. + printer_send.open_world = true; + catalog.add(std::move(printer_send)); + + NativeCommand test_host = mutate_tool( + "printer_test_host", L("Test the print host"), + "Ask the selected printer's print host whether it answers, as the Test button of the printer's connection dialog " + "does, with its connection settings as they stand. Reply: ok, whether the host answered, and message, the button's " + "message in the app's language; branch on ok. A cloud host that wants a login is a failed test with the host's " + "message: logging in stays in the printer's connection dialog. The window does not redraw while the host is asked. " + "Refused: `no_print_host` for a printer with no print host address, `host_cannot_be_tested` for a kind of host that has " + "no test.", + object_schema({}), [](const json&, ToolContext& ctx) { + json reply = ctx.run_ui([] { + const Ops::Outcome tested = Ops::test_print_host(); + if (!tested) + throw refused(tested.refusal()); + return json{{"ok", tested.value().ok}, {"message", tested.value().message}}; + }); + return ToolResult::ok(std::move(reply)); + }); + // It asks the host over the network. + test_host.open_world = true; + test_host.examples = json::parse(R"json([ + {"title": "Check the print host after setting its address", "calls": [ + {"tool": "settings_set", "args": {"type": "printer", "values": {"host_type": "octoprint", "print_host": "192.168.1.20"}}}, + {"tool": "printer_test_host", "args": {}}]}])json"); + catalog.add(reaching({"test_print_host"}, std::move(test_host))); + + NativeCommand status = inspect_tool( + "printer_status", L("Printer status"), + "Read what the Device tab shows of the printer it is connected to, without sending it anything. Reply: connected; " + "with a printer, name, model (null where the tab would say Unknown), `printer_type` (the model's id), online, state " + "(IDLE, PREPARE, RUNNING, PAUSE, FINISH, FAILED...), stage (a number), percent, `remaining_seconds`, layer, " + "`total_layers`, file (the job's name), `error_code`, and temperatures: nozzles (one `{current, target}` each), bed and " + "chamber, null where the tab shows none. With no printer connected the reply is `{\"connected\": false}`, which is no " + "error. The values are what the printer last reported.", + object_schema({}), [](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([] { return printer_status_reply(Ops::printer_status(Ops::connected_printer())); })); + }); + status.examples = json::parse(R"json([ + {"title": "Read the connected printer's state and temperatures", "calls": [{"tool": "printer_status", "args": {}}]}])json"); + catalog.add(std::move(status)); + + catalog.add(job_command( + "print_pause", L("Pause the print"), Ops::JobCommand::Pause, + "Pause the print running on the printer the Device tab is connected to, as the tab's Pause button does. Refused: " + "`no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is RUNNING.", + R"json([{"title": "Pause the print once printer_status reads RUNNING", "calls": [ + {"tool": "printer_status", "args": {}}, {"tool": "print_pause", "args": {}}]}])json", + false)); + catalog.add(job_command( + "print_resume", L("Resume the print"), Ops::JobCommand::Resume, + "Resume the paused print on the printer the Device tab is connected to, as the tab's Resume button does. Refused: " + "`no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is PAUSE, and " + "`resume_at_printer`, in the app's own sentence, for a job (such as laser processing) that resumes only at the printer.", + R"json([{"title": "Resume the print once printer_status reads PAUSE", "calls": [ + {"tool": "printer_status", "args": {}}, {"tool": "print_resume", "args": {}}]}])json", + false)); + catalog.add(job_command( + "print_stop", L("Stop the print"), Ops::JobCommand::Stop, + "Stop the print on the printer the Device tab is connected to, as the tab's Stop button does, but without its " + "question \"Are you sure you want to stop this print?\": it asks nothing, and a stopped print cannot be resumed. " + "Refused: `no_printer_connected` with no printer connected, `printer_state`, naming the state, unless it is RUNNING, " + "PAUSE, PREPARE or SLICING.", + R"json([{"title": "Stop the print", "calls": [{"tool": "print_stop", "args": {}}]}])json", + true)); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp b/src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp new file mode 100644 index 0000000000..1dce0a581b --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp @@ -0,0 +1,589 @@ +// The place The project: project_new, project_open, project_import, project_save and project_export, the project's +// files in and out without file dialogs, and called as their menu items' actions, with them; and +// project_get_settings and project_set_settings, the project's own settings, which the settings code of +// PresetTools.cpp reads and writes. + +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandMenuItems.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/Operations/ExportOps.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/ProjectOps.hpp" +#include "slic3r/GUI/Operations/RunStatus.hpp" +#include "slic3r/GUI/PartPlate.hpp" +#include "slic3r/GUI/Plater.hpp" + +#include "libslic3r/Model.hpp" + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; +namespace fs = boost::filesystem; + +namespace { + +bool has_extension(const fs::path& p, std::initializer_list exts) +{ + const std::string name = path_to_utf8(p.filename()); + for (const char* e : exts) + if (boost::algorithm::iends_with(name, e)) + return true; + return false; +} + +} // namespace + +json objects_summary(Plater& plater) +{ + json names = json::array(); + for (const ModelObject* o : plater.model().objects) + names.push_back(o->name); + return {{"objects", plater.model().objects.size()}, {"names", std::move(names)}, {"plates", plater.get_partplate_list().get_plate_count()}}; +} + +namespace { + +json project_json(const Ops::ProjectSummary& project) +{ + return {{"objects", project.object_names.size()}, {"names", project.object_names}, {"plates", project.plates}}; +} + +// The answer about the project's unsaved changes that a command replacing the project gives: discard them, else refuse. +Ops::UnsavedChanges unsaved_changes_answer(bool discard) { return discard ? Ops::UnsavedChanges::Discard : Ops::UnsavedChanges::Refuse; } + +// What a command that replaces the project adds to the refusal of unsaved changes. +constexpr const char* kUnsavedChangesHint = "project_save first, or pass discard_changes: true."; + +} // namespace + +void require_project_discardable(bool discard) +{ + if (const std::optional refusal = Ops::unsaved_changes_refusal(unsaved_changes_answer(discard))) + throw refused(*refusal, kUnsavedChangesHint); +} + +ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket) +{ + json done = poll_ui( + ctx, + [&ticket]() -> json { + ui_plater(); + std::string error; + const Ops::ExportStatus status = Ops::gcode_export_state(ticket, &error); + if (status == Ops::ExportStatus::Pending) + return json(); + json out{{"export", Ops::to_string(status)}, {"path", ticket.path}}; + if (!error.empty()) + out["error"] = error; + return out; + }, + std::chrono::minutes(10), "the export to finish"); + const std::string status = done["export"]; + if (status == "ok") + return ToolResult::ok(done); + if (status == "superseded") { + done["note"] = "The project changed while exporting; the file reflects the project as it was when the export started."; + return ToolResult::ok(done); + } + return ToolResult::error("The export ended " + status, done); +} + +namespace { + +// project_export's format for a path given without one, from its extension. +std::string format_of(const std::string& path) +{ + static const std::pair formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"}, + {".stl", "stl"}, {".drc", "drc"}, {".obj", "toolpaths_obj"}}; + for (const auto& [ext, format] : formats) + if (boost::algorithm::iends_with(path, ext)) + return format; + throw ToolFailure("Give format (gcode, sliced_3mf, 3mf, stl, drc or toolpaths_obj), or a path ending in .gcode, .gcode.3mf, " + ".3mf, .stl, .drc or .obj"); +} + +} // namespace + +void register_project_tools(CommandCatalog& catalog) +{ + NativeCommand open = reaching({"open_project"}, mutate_tool( + "project_open", L("Open a project"), + "Open a project (.3mf) by absolute path, without a file dialog, replacing the current project, with the settings it " + "was saved with whatever the Preferences' Load behavior says; when the current project has unsaved changes that " + "fails, changing nothing, unless `discard_changes`. A G-code file replaces the project too, to show its toolpaths: " + "with unsaved changes the app asks first (`blocked_by_dialog`), whatever `discard_changes` says. `project_import` adds " + "models, or a project's objects alone, to the current project. Called with no arguments it is Load Project: the " + "Open dialog asks for the file (`blocked_by_dialog`), after asking about the unsaved changes. Reply: opened (project " + "or gcode), and objects, names and plates for a project, path for a G-code.", + object_schema({{"path", prop("string", "Absolute path of a .3mf project, or of a G-code file (.gcode, .bgcode).")}, + {"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a project " + "replaces it.")}}, + {"path"}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + std::string err; + const auto path = resolve_input_path(arg_string(args, "path"), err); + if (!path) + throw ToolFailure(err); + const bool gcode = has_extension(*path, {".gcode", ".bgcode"}); + if (!gcode && !has_extension(*path, {".3mf"})) + throw ToolFailure("project_open opens a .3mf project or a G-code file; project_import adds models to the project"); + // A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes. + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); + json out = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + if (gcode) { + plater.load_gcode(from_path(*path)); + return {{"opened", "gcode"}, {"path", path_to_utf8(*path)}}; + } + Ops::OpenProjectArgs open; + open.path = *path; + open.unsaved = unsaved_changes_answer(discard); + const Ops::Outcome opened = Ops::open_project(open); + if (!opened) + throw refused(opened.refusal(), kUnsavedChangesHint); + json o = project_json(opened.value()); + o["opened"] = "project"; + return o; + }); + settle(ctx); + return ToolResult::ok(out); + })); + open.actions = json::array({NativeCommands::action("load_project", L("Load Project"), L("Commands"), "menu_open", json::object(), + "Open a project through the Open dialog (it asks first if the current project " + "has unsaved changes); project_open with a path opens that file without a " + "dialog.")}); + catalog.add(NativeCommands::with_person_form(std::move(open), [](const json&) { return MenuItems::load_project(); })); + + NativeCommand import_ = reaching({"import_models"}, mutate_tool( + "project_import", L("Import models"), + "Add the models of files (STL, 3MF, STEP, OBJ, AMF, SVG...) to the current project by absolute path, without a file " + "dialog, as one undo step; a .3mf adds its objects only, not its settings (`project_open` opens it as a project). A " + ".zip archive gives the model files it holds (STL, OBJ, AMF, 3MF, STEP; a .3mf its objects only, as above), as Import " + "ZIP Archive does: those entries names, by their paths in the archive, else all of them, in place of its file list; " + "an entry the archive lacks is refused with the names it has, before anything is imported. Importing can open a " + "dialog (STEP mesh options, for instance); the reply is then `blocked_by_dialog`. Called with no arguments it is " + "Import 3MF/STL/STEP/SVG/OBJ/AMF, and with `archive: true` alone Import ZIP Archive: a file dialog asks for the files, " + "or for the archive and then which of its files to import (`blocked_by_dialog`). Reply: opened (models), added (how " + "many objects), archives (each archive's path and the entries taken) and the project's objects, names and plates.", + object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths of model files, or of a .zip archive of them.")}, + {"entries", {{"type", "array"}, + {"items", {{"type", "string"}}}, + {"minItems", 1}, + {"description", "The files to take from the one .zip archive among paths, by their paths " + "in it (\"parts/cube.stl\"). Default: every model file it holds."}}}, + {"archive", prop("boolean", "true, alone: ask for a ZIP archive in a file dialog and import the models " + "it holds, as Import ZIP Archive does.")}}, + {"paths"}), + [](const json& args, ToolContext& ctx) { + if (arg_bool(args, "archive", false)) + throw ToolFailure("archive asks for the archive in a file dialog, so it goes alone; paths imports files without one"); + if (args.contains("entries")) { + const json& given = args["paths"]; + const auto zips = std::count_if(given.begin(), given.end(), [](const json& p) { + return boost::algorithm::iends_with(p.get(), ".zip"); + }); + if (zips == 0) + throw ToolFailure("entries names files of a .zip archive: give the archive in paths"); + if (zips > 1) + throw ToolFailure("entries names the files of one archive: give one .zip in paths"); + } + std::vector paths; + for (const json& p : args["paths"]) { + std::string err; + auto resolved = resolve_input_path(p.get(), err); + if (!resolved) + throw ToolFailure(err); + if (has_extension(*resolved, {".gcode", ".bgcode"})) + throw ToolFailure(p.get() + " is a G-code file, which project_open opens to show its toolpaths"); + paths.push_back(*resolved); + } + if (paths.empty()) + throw ToolFailure("paths is empty"); + json out = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + Ops::ImportModelsArgs models; + models.paths = paths; + if (args.contains("entries")) + models.entries = args["entries"].get>(); + const Ops::Outcome imported = Ops::import_models(models); + if (!imported) { + const bool nothing = std::string(imported.refusal().code) == "nothing_loaded"; + throw refused(imported.refusal(), nothing ? "See app_log for the reason." : "", "entries"); + } + json o = objects_summary(plater); + o["opened"] = "models"; + o["added"] = imported.value().added; + if (!imported.value().archives.empty()) { + json archives = json::array(); + for (const Ops::ImportedArchive& archive : imported.value().archives) + archives.push_back({{"path", path_to_utf8(archive.path)}, {"entries", archive.entries}}); + o["archives"] = std::move(archives); + } + return o; + }); + settle(ctx); + return ToolResult::ok(out); + })); + import_.actions = json::array( + {NativeCommands::action("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", json::object(), + "Import models (3MF/STL/STEP/SVG/OBJ/AMF) through a file dialog, as one undo step; a project " + "file's settings are not loaded (project_open opens a project). project_import with paths adds " + "files' geometry without a dialog."), + NativeCommands::action("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", {{"archive", true}}, + "Import models from a ZIP archive (opens a file dialog).")}); + catalog.add(NativeCommands::with_person_form(std::move(import_), [](const json& action_args) { + return action_args.value("archive", false) ? MenuItems::import_zip_archive() : MenuItems::import_file(); + })); + + // New Project's menu item is its action: with no arguments it asks as the item does. + NativeCommand project_new = reaching({"new_project"}, mutate_tool( + "project_new", L("New Project"), + "Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes " + "if there are any: the reply is then `blocked_by_dialog`, and `dialog_answer` answers it. With arguments, or `silent: " + "true`, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless " + "`discard_changes`. The presets' unsaved changes carry over to the new project unless `preset_changes` is \"discard\", as " + "New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved " + "changes, discarded and modified list per preset the keys dropped and the keys still unsaved. With no arguments " + "the reply is ran and level, also once a prompt is answered, whatever the answer: Cancel keeps the project.", + object_schema({{"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail; for the " + "presets', see `preset_changes`.")}, + {"preset_changes", enum_prop({"keep", "discard"}, "The presets' unsaved changes, not the project's: keep " + "them for the new project (default) or drop them.")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage()); + const bool discard_presets = arg_string(args, "preset_changes", "keep") == "discard"; + json out = ctx.run_ui([&] { + ui_plater(); + const json before = unsaved_changes(); + Ops::NewProjectArgs fresh; + fresh.unsaved = unsaved_changes_answer(discard); + fresh.discard_preset_changes = discard_presets; + const Ops::Outcome started = Ops::new_project(fresh); + if (!started) + throw refused(started.refusal(), kUnsavedChangesHint); + json o = project_json(started.value()); + o.update(unsaved_changes_outcome(before)); + return o; + }); + settle(ctx); + return ToolResult::ok(out); + })); + project_new.actions = json::array({NativeCommands::action("new_project", L("New Project"), L("Commands"), "menu_open", json::object(), + "Runs project_new with no arguments, as New Project does: a new, empty " + "project, after asking about the unsaved changes if there are any.")}); + catalog.add(NativeCommands::with_person_form(std::move(project_new), [](const json&) { + if (Plater* plater = wxGetApp().plater()) + plater->new_project(); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + })); + + // Save Project's and Save Project As's menu items are its actions: with no arguments, or with save_as alone, it saves as + // the item does. + NativeCommand save = reaching({"save_project_as"}, mutate_tool( + "project_save", L("Save Project"), + "Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, " + "level), or, when it has none, through a file dialog (`blocked_by_dialog`; a native picker needs `dialog_auto_answer` " + "registered first); with `save_as: true` alone, as Save Project As does, always through the file dialog. With path, " + "it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name " + "ending in .gcode.3mf is refused (`project_export` writes that). Either way the save can still open a dialog " + "(`blocked_by_dialog`): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file " + "cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, " + "fails with `project_not_saved`, and a file already there stays as it was.", + object_schema({{"path", prop("string", "Absolute .3mf path.")}, + {"overwrite", prop("boolean", "Replace an existing file.")}, + {"save_as", prop("boolean", "true, alone: ask for the file in the save dialog, as Save Project As does. With " + "path it adds nothing: path is the new file.")}}, + {"path"}), + [](const json& args, ToolContext& ctx) { + std::string err; + auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); + if (!path) + throw ToolFailure(err); + ctx.run_ui([&] { + ui_plater(); + Ops::SaveProjectAsArgs save; + save.path = *path; + if (const Ops::Outcome saved = Ops::save_project_as(save); !saved) + throw refused(saved.refusal(), std::string(saved.refusal().code) == "sliced_file_name" ? + "That is project_export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." : + "See app_log."); + return json(); + }); + settle(ctx); + return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}}); + })); + save.actions = json::array( + {NativeCommands::action("save_project", L("Save Project"), L("Commands"), "menu_save", json::object(), + "Runs project_save with no arguments, as Save Project does: to the project's file, or through a " + "file dialog when it has none."), + NativeCommands::action("save_project_as", L("Save Project As"), L("Commands"), "menu_save", {{"save_as", true}}, + "Save the project as a .3mf file through the save dialog. project_save with a path saves there " + "without a dialog; a name ending in .gcode.3mf is refused (project_export {format: \"sliced_3mf\"} " + "writes that).")}); + save = NativeCommands::with_person_form(std::move(save), [](const json& action_args) { + if (action_args.value("save_as", false)) + return MenuItems::save_project_as(); + if (Plater* plater = wxGetApp().plater()) + return NativeCommands::project_save_result(plater->save_project(false)); + return AppActionRunResult{AppActionRunResult::Level::Succeeded}; + }); + // Every call but the two actions' requires path, and a call with path skips the file dialog: silent has nothing to add. + save.input_schema["properties"]["silent"]["description"] = + "Goes with path, which every call but {} and `{save_as: true}` requires, and adds nothing to it: a call with path skips " + "the file dialog already."; + catalog.add(save); + + NativeCommand export_ = reaching( + {"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "export_toolpaths_obj"}, + with_target_ids(mutate_tool( + "project_export", L("Export"), + "Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the " + "background, and the call returns once it is). `sliced_3mf`: the sliced plate, or all plates, as .gcode.3mf (slice " + "first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl and drc " + "(Draco): the objects as one file, or with `per_object` each in a file of its own, named after it, into the folder " + "path names; every object of every plate, or those objects names. `toolpaths_obj`: the toolpaths the Preview shows, " + "as an OBJ, refused while it shows none (slice the plate and show the Preview first). Without format, the path's " + "extension (.gcode, .gcode.3mf, .3mf, .stl, .drc, .obj) says which. Called with exactly the arguments of one of the " + "File > Export menu items (format alone, `sliced_3mf` with plates \"all\", stl or drc with `per_object`), it asks for the file " + "or folder in the dialog that item opens (`blocked_by_dialog`). A file per object of a project with no objects, and the " + "toolpaths while the Preview shows none, are refused in either form. Reply: path and bytes; for gcode, path and " + "export (ok, or superseded with a note when the project changed while it was written); for `per_object`, path and " + "files (each file written); for stl and drc, objects (those written).", + with_targets(object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl", "drc", "toolpaths_obj"}, + "What to write; default from the path's extension.")}, + {"path", prop("string", "Absolute output path: the file, or with `per_object` an existing folder.")}, + {"plates", {{"type", {"string", "integer"}}, + {"description", "\"current\" (default), a plate index, which is selected first and is " + "the plate gcode and `sliced_3mf` write, or \"all\" (`sliced_3mf` only)."}}}, + {"per_object", prop("boolean", "stl and drc: a file per object, into a folder. Default false.")}, + {"overwrite", prop("boolean", "Replace an existing file.")}}, + {"path"}), + kObjects, false), + [](const json& args, ToolContext& ctx) { + const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path")); + const bool per_object = arg_bool(args, "per_object", false); + const bool meshes = format == "stl" || format == "drc"; + if (per_object && !meshes) + throw ToolFailure("per_object goes with format stl or drc"); + if (per_object && (args.contains("plates") || args.contains("overwrite"))) + throw ToolFailure("per_object writes every object into the folder path names: plates and overwrite go with one file"); + if (format == "toolpaths_obj" && args.contains("plates")) + throw ToolFailure("toolpaths_obj writes the toolpaths the Preview shows: plates goes with the other formats"); + const json plate = args.value("plates", json("current")); + const bool all = plate.is_string() && plate.get() == "all"; + if (plate.is_string() && !all && plate.get() != "current") + throw ToolFailure("plates is \"all\", \"current\" or a plate index"); + if (all && format != "sliced_3mf") + throw ToolFailure("plates \"all\" applies to sliced_3mf only"); + std::string err; + const auto path = per_object ? resolve_output_dir(arg_string(args, "path"), err) : + resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); + if (!path) + throw ToolFailure(err); + std::optional ticket; + json written = json::object(); // what the reply adds for stl and drc + ctx.run_ui([&]() -> json { + // A G-code export finishes in the background: held from before it starts. + if (format == "gcode") + ctx.begin_operation(); + Plater& plater = ui_plater(); + const std::optional index = plate.is_number_integer() ? std::optional(plate.get()) : std::nullopt; + // The export's own refusals of the object indices given come before the target check, which + // refuses an index the project lacks without no_such_object's code. + std::vector indices; + if (args.contains("object") && args.at("object").is_number_integer()) + indices.push_back(args.at("object").get()); + for (const json& entry : args.value("objects", json::array())) + if (entry.is_number_integer()) + indices.push_back(entry.get()); + if (const std::optional refusal = Ops::export_objects_refusal(format, indices, per_object, plater.model())) + throw refused(*refusal); + // The objects named, by index or id; none named: every object. + Targets named; + if (names_targets(args)) { + const Ops::Outcome found = resolve_targets(plater.model(), nullptr, args, kObjects, false); + if (!found) + throw refused(found.refusal()); + named = found.value(); + } + if (const std::optional refusal = + Ops::export_objects_refusal(format, named.objects, per_object, plater.model())) + throw refused(*refusal); + if (meshes) { + Ops::ExportStlArgs mesh; + mesh.path = *path; + mesh.plate = index; + mesh.objects = named.objects; + mesh.per_object = per_object; + mesh.draco = format == "drc"; + const Ops::Outcome> files = Ops::export_stl(mesh); + if (!files) + throw refused(files.refusal(), std::string(files.refusal().code) == "file_not_written" ? "See app_log." : ""); + Targets exported = named; + if (exported.objects.empty()) + for (int o = 0; o < int(plater.model().objects.size()); ++o) + exported.objects.push_back(o); + written = targets_reply(plater.model(), exported); + if (per_object) { + written["files"] = json::array(); + for (const fs::path& file : files.value()) + written["files"].push_back(path_to_utf8(file)); + } + return json(); + } + if (format == "toolpaths_obj") { + if (const Ops::Outcome drawn = Ops::export_toolpaths_obj({*path}); !drawn) + throw refused(drawn.refusal(), std::string(drawn.refusal().code) == "no_toolpaths" ? + "plate_slice {preview: true} slices the plate and shows it." : + "See app_log."); + return json(); + } + if (format == "gcode") { + Ops::ExportGcodeArgs gcode; + gcode.path = *path; + gcode.plate = index; + const Ops::Outcome started = Ops::start_gcode_export(gcode); + if (!started) { + const std::string code = started.refusal().code; + throw refused(started.refusal(), code == "slicing_in_progress" ? "app_wait {for:\"idle\"} waits for it." : + code == "export_not_started" ? "Check app_state.notifications." : + ""); + } + ticket = started.value(); + return json(); + } + Ops::ExportSlicedArgs sliced; + sliced.path = *path; + sliced.all_plates = all; + sliced.plate = index; + Ops::ExportFileArgs file; + file.path = *path; + file.plate = index; + const Ops::Outcome done = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) : Ops::export_model_3mf(file); + if (!done) + throw refused(done.refusal(), std::string(done.refusal().code) == "file_not_written" ? "See app_log." : ""); + return json(); + }); + if (ticket) + return await_gcode_export(ctx, *ticket); + settle(ctx); + json reply{{"path", path_to_utf8(*path)}}; + if (!per_object) + reply["bytes"] = fs::file_size(*path); + reply.update(written); + return ToolResult::ok(reply); + }))); + // The File > Export menu items, each with the dialog it asks for the file or folder in. + export_.actions = json::array({ + NativeCommands::action("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", {{"format", "gcode"}}, + "Export the current plate's G-code through the export dialog, in the background. project_export " + "with a path exports the sliced plate there without a dialog, and the call returns when the file " + "is written; a plate that is not sliced is refused (slice first)."), + NativeCommands::action("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", {{"format", "sliced_3mf"}}, + "Export the current plate's sliced file (.gcode.3mf) through a file dialog; project_export with a " + "path writes there without one."), + NativeCommands::action("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", + {{"format", "sliced_3mf"}, {"plates", "all"}}, + "Export every plate's sliced file into one .gcode.3mf through a file dialog; project_export with a " + "path writes there without one."), + NativeCommands::action("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", {{"format", "3mf"}}, + "Export the model as a .3mf without slicing data, through a file dialog; project_export with a path " + "writes there without one."), + NativeCommands::action("export_stl", L("Export STL"), L("Slice & Export"), "save", {{"format", "stl"}}, + "Export all objects as one STL through a file dialog; project_export with a path writes there " + "without one."), + NativeCommands::action("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", + {{"format", "stl"}, {"per_object", true}}, + "Export each object as its own STL into the folder a dialog asks for; project_export with a folder " + "as path writes there without one."), + NativeCommands::action("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", {{"format", "drc"}}, + "Export all objects as one Draco (.drc) file."), + NativeCommands::action("export_drc_multi", L("Export All Objects as DRCs"), L("Export"), "save", + {{"format", "drc"}, {"per_object", true}}, + "Export each object as its own Draco (.drc) file."), + NativeCommands::action("export_toolpaths_obj", L("Export Toolpaths as OBJ"), L("Export"), "custom-gcode_gcode", + {{"format", "toolpaths_obj"}}, "Export the sliced toolpaths as an OBJ."), + }); + catalog.add(NativeCommands::with_person_form(std::move(export_), [](const json& action_args) { + const std::string format = action_args.at("format"); + const bool per_object = action_args.value("per_object", false); + if (format == "gcode") + return MenuItems::export_gcode(); + if (format == "sliced_3mf") + return MenuItems::export_sliced_file(action_args.value("plates", std::string()) == "all"); + if (format == "3mf") + return MenuItems::export_3mf(); + if (format == "stl") + return per_object ? MenuItems::export_stl_multi() : MenuItems::export_stl(); + if (format == "drc") + return per_object ? MenuItems::export_drc_multi() : MenuItems::export_drc_single(); + return MenuItems::export_toolpaths_obj(); + })); + + catalog.add(inspect_tool( + "project_get_settings", L("Read the project's settings"), + "Read the project's own settings for its plates: the plate type (`curr_bed_type`), the prime tower position per plate " + "(`wipe_tower_x`, `wipe_tower_y`) and, with several extruders, the filament grouping (`filament_map_mode`, `filament_map`); " + "all of them, or those named in keys. The filament list's colours, mixed filaments and flushing are `filament_list`'s. " + "Each item has its value and meta; meta.offered lists the choices this printer has, and `meta.read_only` marks what is " + "set elsewhere.", + object_schema({{"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), + [](const json& args, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); + return read_project_settings(args); + })); + })); + + catalog.add(mutate_tool( + "project_set_settings", L("Change the project's settings"), + "Change the project's own settings as their controls write them: `curr_bed_type`, as the plate type selector, and " + "wipe_tower_x/y (mm from the plate's origin, one per plate), as a prime tower's drag. The filament list's colours " + "and flushing are set with `filament_set_colour` and `filament_set_flushing`. Values are checked before anything " + "changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower " + "that did not fit.", + object_schema({{"values", {{"type", "object"}, {"description", "`{key: value}`, or `{key: {index, value}}` for one entry"}}}}, + {"values"}), + [](const json& args, ToolContext& ctx) { + const json values = args.value("values", json::object()); + if (values.empty()) + throw ToolFailure("values must be a non-empty object {key: value}"); + return set_project_values(values, ctx, false); + })); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp b/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp new file mode 100644 index 0000000000..fac53c3da3 --- /dev/null +++ b/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp @@ -0,0 +1,1313 @@ +// The place Recordings, replays and scripts. window_screenshot, what the agent looks at, and window_save_screenshot, +// the person's Take Screenshot. recording_start, recording_stop and recording_encode: a video of what OrcaSlicer +// shows, optionally captioned with the current tool call and its pointer highlighted, and its encode to MP4. +// replay_run and replay_export: deterministic replays of tool calls, and turning a session into one. script_run, +// script_list_api and script_describe_api: Python scripts against orca.host, the plugin API, and the orca package's +// reference, read one module or class at a time. + +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/McpPersonRun.hpp" +#include "slic3r/GUI/Mcp/McpRecorder.hpp" +#include "slic3r/GUI/Mcp/McpReplay.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/RecordingSettings.hpp" +#include "slic3r/GUI/Mcp/ScreenCapture.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/Mcp/VideoEncode.hpp" +#include "slic3r/GUI/CommandCatalog.hpp" +#include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommandMenuItems.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/plugin/host/PluginHostTools.hpp" +#include "slic3r/plugin/PluginAuditManager.hpp" +#include "slic3r/plugin/PythonInterpreter.hpp" +#include "slic3r/plugin/PythonScriptRunner.hpp" +#include "slic3r/plugin/PythonSession.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; +namespace fs = boost::filesystem; +namespace py = pybind11; + +namespace { + +std::string base64(const std::string& bytes) +{ + namespace b64 = boost::beast::detail::base64; + std::string out(b64::encoded_size(bytes.size()), '\0'); + out.resize(b64::encode(out.data(), bytes.data(), bytes.size())); + return out; +} + +std::string read_file(const fs::path& path) +{ + boost::nowide::ifstream in(path_to_utf8(path).c_str(), std::ios::binary); + if (!in) + throw ToolFailure("Cannot read " + path_to_utf8(path)); + std::ostringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +void write_file(const fs::path& path, const std::string& text) +{ + boost::nowide::ofstream out(path_to_utf8(path).c_str(), std::ios::binary | std::ios::trunc); + out << text; + if (!out) + throw ToolFailure("Cannot write " + path_to_utf8(path)); +} + +std::string timestamp() +{ + const std::time_t t = std::time(nullptr); + char buf[32]; + std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", std::localtime(&t)); + return buf; +} + +// An invalid replay is a tool error flagged `invalid`, which --run turns into exit code 2. +ToolResult invalid(const std::string& message) { return ToolResult::error("Invalid replay: " + message, {{"invalid", true}}); } + +} // namespace + +json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx, const ReplayRunOptions& options) +{ + boost::system::error_code ec; + fs::create_directories(sctx.out_dir, ec); + if (ec) + throw ToolFailure("Cannot create " + path_to_utf8(sctx.out_dir) + ": " + ec.message()); + + const std::string job = ctx.job_id(); + runtime.begin_run_scope(job); + struct ScopeEnd + { + AutomationRuntime& runtime; + std::string job; + bool recording_waited = false; // the run below waited for the replay's recording already + ~ScopeEnd() { runtime.end_run_scope(job, !recording_waited); } + } scope_end{runtime, job}; + + const auto stopped = [&ctx] { return ctx.cancelled(); }; + + ReplayHost host; + host.call = [&ctx](const std::string& tool, const json& a) { return ctx.call_child(tool, a); }; + host.wait_job = [&runtime, &stopped](const std::string& id, int timeout_s) { + return runtime.jobs().wait(id, std::chrono::seconds(timeout_s), stopped); + }; + host.cancelled = stopped; + host.step_started = options.step_started; + host.step_finished = options.step_finished; + host.open_dialogs = [&runtime] { return runtime.ui().open_dialogs(); }; + + json result = run_replay(replay, sctx, host, options.only_step); + // A recording the replay started ends with it, its file closed before the result is written; one still + // being written after the wait is named, since an encode of it would fail. + std::optional unfinished = runtime.recorder().end_owned_by(job, "run_ended", true); + scope_end.recording_waited = true; + if (unfinished) + result["unfinished_recording"] = *unfinished; + result["out_dir"] = path_to_utf8(sctx.out_dir); + if (options.write_result) { + const fs::path file = sctx.out_dir / "result.json"; + write_file(file, result.dump(2)); + result["result_file"] = path_to_utf8(file); + } + return result; +} + +namespace { + +// A run's orca.host.tools calls, as child calls of the script_run job, so each has its tool's guards, +// admission and undo, and a cancel of the run reaches them. +class RunBridge final : public ToolBridge +{ +public: + explicit RunBridge(ToolContext& ctx) : m_ctx(ctx) {} + json call(const std::string& tool, const json& args) override + { + ToolResult r = m_ctx.call_child(tool, args); + if (r.is_error) + throw ToolCallError(r.message, r.data); + return r.data; + } + +private: + ToolContext& m_ctx; +}; + +// The Run Script panel's session's orca.host.tools calls: child calls under a lineage node of the session's job, so a +// stop cancels every call in flight, inline ones (app_wait) included, without stopping the session, and the next work's +// calls run under a fresh node. +class SessionBridge final : public ToolBridge +{ +public: + SessionBridge(AutomationRuntime& runtime, const std::string& session_job) + : m_runtime(runtime), m_node(runtime.jobs(), "script_run", session_job) + {} + json call(const std::string& tool, const json& args) override + { + ToolResult r = m_runtime.core().call_child_named(tool, args, m_node.id()); + if (r.is_error) + throw ToolCallError(r.message, r.data); + return r.data; + } + // A stop or time-out, from the session's watcher: the node's calls are cancelled, and its operations, as the + // job_cancel cancels them. + void stop_calls() + { + const std::string node = m_node.id(); + m_stopped = true; + m_runtime.jobs().request_stop(node); + // Found again on the UI thread: the runtime may be gone by the time the closure runs. + m_runtime.post_ui([node] { + if (AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->cancel_operations_of(node); + }); + } + // As a work starts: after a stop its calls get a node no stop was asked for. + void renew_after_stop() + { + if (m_stopped.exchange(false)) + m_node.renew(); + } + +private: + AutomationRuntime& m_runtime; + LineageNode m_node; + std::atomic m_stopped{false}; +}; + +// python_api_reference()'s walk over the orca package. +constexpr const char* kReferenceSource = R"PY( + +import inspect, re, types + +# A signature line pybind11 starts a docstring with: "name(...) -> T", numbered after "Overloaded function.", +# and without a name for a property's getter. + +_SIGNATURE = re.compile(r"^(?:\d+\. )?(\w*)\(.*\)(?: -> .+)?$") + +_SELF = re.compile(r"\bself: [\w.]+") +# The types of a module's constants, such as orca.host.ui.PD_CAN_ABORT. + +_CONSTANTS = (bool, int, float, str) + +def _split(names, doc): + """The signature lines of a docstring whose function is called one of names, and the rest of it.""" + signatures, text = [], [] + for line in (doc or "").splitlines(): + stripped = line.strip() + match = _SIGNATURE.match(stripped) + if match and match.group(1) in names: + signatures.append(_SELF.sub("self", re.sub(r"^\d+\. ", "", stripped))) + elif stripped != "Overloaded function.": + text.append(line) + # An overloaded function's first line, name(*args, **kwargs), stands for the numbered overloads after it. + if len(signatures) > 1: + signatures = [s for s in signatures if not s.endswith("(*args, **kwargs)")] + return signatures, "\n".join(text).strip() + +def _entry(name, obj, kind): + short = name.rsplit(".", 1)[-1] + if kind == "class": + # A class's own docstring, not one inherited from a base, then what its constructors say of their + # arguments; the constructors' signatures are the class's. + init = vars(obj).get("__init__") + signatures, made = _split(("__init__",), init.__doc__ if init is not None else None) + signatures = [short + s[len("__init__"):].replace("(self, ", "(").replace("(self)", "()").replace(" -> None", "") + for s in signatures] + doc = inspect.cleandoc(obj.__doc__ or "") + if made and made != doc: + doc = (doc + "\n\n" + made).strip() + return {"name": name, "kind": kind, "signature": " | ".join(signatures) or short, "doc": doc} + if kind == "property": + getter = obj.fget.__doc__ if obj.fget is not None else "" + returns = re.match(r"^\w*\(.*\) -> (.+)$", (getter or "").strip().split("\n")[0]) + _, doc = _split((short, ""), inspect.getdoc(obj)) + return {"name": name, "kind": kind, "signature": short + (": " + returns.group(1) if returns else ""), "doc": doc} + signatures, doc = _split((short, ""), inspect.getdoc(obj)) + if not signatures: + try: + signatures = [short + str(inspect.signature(obj))] + except (TypeError, ValueError): + signatures = [short] + return {"name": name, "kind": kind, "signature": " | ".join(signatures), "doc": doc} + +def reference(package): + out, seen, constants = [], set(), [] + def walk(module, prefix): + if id(module) in seen: + return + seen.add(id(module)) + out.append(_entry(prefix.rstrip("."), module, "module")) + for name, value in sorted(vars(module).items()): + if name.startswith("_"): + continue + full = prefix + name + if isinstance(value, types.ModuleType): + if value.__name__.startswith(package.__name__): + walk(value, full + ".") + elif inspect.isclass(value): + out.append(_entry(full, value, "class")) + # An enum lists its values in its docstring; name and value are every enum's. + values = getattr(value, "__members__", None) + for member, attr in sorted(vars(value).items()): + if member.startswith("_") or (values is not None and (member in values or member in ("name", "value"))): + continue + # A class holds a static method as a staticmethod object, whose documentation is the + # staticmethod type's; pybind11 documented the function inside it. + if isinstance(attr, (staticmethod, classmethod)): + attr = attr.__func__ + kind = "property" if isinstance(attr, property) else "method" if callable(attr) else None + if kind: + out.append(_entry(full + "." + member, attr, kind)) + elif callable(value): + out.append(_entry(full, value, "function")) + elif isinstance(value, _CONSTANTS): + constants.append(len(out)) + out.append({"name": full, "kind": "constant", "signature": name + " = " + repr(value), "doc": ""}) + elif type(value).__module__.startswith(package.__name__) and not hasattr(type(value), "__members__"): + # An instance the package offers by name, such as orca.host.preset.process; enum values + # exported into a module are their enum's. + kind_of = type(value) + out.append({"name": full, "kind": "attribute", "signature": name + ": " + kind_of.__module__ + "." + kind_of.__name__, + "doc": inspect.cleandoc(kind_of.__doc__ or "")}) + walk(package, package.__name__ + ".") + # A constant has no docstring of its own: the documentation of what takes it says what it means. + for i in constants: + word = re.compile(r"\b" + re.escape(out[i]["name"].rsplit(".", 1)[-1]) + r"\b") + users = [e["name"] for e in out if e["kind"] != "constant" and word.search(e["doc"])] + if users: + out[i]["doc"] = "See " + ", ".join(users) + "." + return out +)PY"; + +} // namespace + +json python_api_reference() +{ + py::gil_scoped_acquire gil; + try { + py::dict scope; + py::exec(kReferenceSource, scope); + json entries = json::array(); + for (const auto item : scope["reference"](py::module_::import("orca")).cast()) { + json entry = json::object(); + for (const auto field : item.cast()) + entry[field.first.cast()] = field.second.cast(); + entries.push_back(std::move(entry)); + } + return entries; + } catch (py::error_already_set& e) { + throw ToolFailure(std::string("Cannot read the Python API: ") + e.what()); + } +} + +json python_api_children(const json& reference, const std::string& within) +{ + const auto is_scope = [&within](const json& e) { + return e["name"] == within && (e["kind"] == "module" || e["kind"] == "class"); + }; + if (std::none_of(reference.begin(), reference.end(), is_scope)) { + json modules = json::array(); + std::string names; + for (const json& e : reference) + if (e["kind"] == "module") { + modules.push_back(e["name"]); + names += (names.empty() ? "" : ", ") + e["name"].get(); + } + throw ToolFailure(within + " is no module or class of the orca package; its modules are " + names, + {{"code", "invalid_argument"}, {"modules", std::move(modules)}}); + } + // An entry is directly inside `within` when its name is `within`, a dot and one more part. + const std::string prefix = within + '.'; + json items = json::array(); + for (const json& e : reference) { + const std::string& name = e["name"].get_ref(); + if (boost::algorithm::starts_with(name, prefix) && name.find('.', prefix.size()) == std::string::npos) + items.push_back({{"name", name}, {"kind", e["kind"]}, {"signature", e["signature"]}, + {"summary", first_sentence(e["doc"].get())}}); + } + return items; +} + +json python_api_entry(const json& reference, const std::string& name) +{ + std::vector> scored; // {distance, index}, the reference's order among equals + for (std::size_t i = 0; i < reference.size(); ++i) { + const std::string& candidate = reference[i]["name"].get_ref(); + if (candidate == name) + return reference[i]; + scored.emplace_back(edit_distance(name, candidate), i); + } + std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + json closest = json::array(); + std::string names; + for (std::size_t i = 0; i < scored.size() && closest.size() < 3; ++i) { + closest.push_back(reference[scored[i].second]["name"]); + names += (names.empty() ? "" : ", ") + closest.back().get(); + } + throw ToolFailure("No entry " + name + " in the orca package; the closest are " + names, + {{"code", "invalid_argument"}, {"did_you_mean", std::move(closest)}}); +} + +bool python_has_numpy() +{ + py::gil_scoped_acquire gil; + try { + return !py::module_::import("importlib.util").attr("find_spec")("numpy").is_none(); + } catch (py::error_already_set&) { + return false; + } +} + +ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename) +{ + const std::string job = ctx.job_id(); + // The session waits for the person between works: `app_wait {for: "idle"}` counts only the calls it makes. + runtime.jobs().set_idle(job); + // What its calls leave behind is the session's, as a run's is; its rules act only while a work runs. + runtime.begin_run_scope(job); + runtime.set_run_scope_paused(job, true); + struct ScopeEnd + { + AutomationRuntime& runtime; + std::string job; + ~ScopeEnd() { runtime.end_run_scope(job); } + } scope_end{runtime, job}; + + SessionBridge bridge(runtime, job); + ScopedToolBridge bound(bridge); + PythonSessionRequest request; + request.identity = kScriptIdentityPerson; + request.filename = filename; + request.cancelled = [&ctx] { return ctx.cancelled(); }; + request.stop_calls = [&bridge] { bridge.stop_calls(); }; + request.work_started = [&runtime, &bridge, job] { + bridge.renew_after_stop(); + runtime.set_run_scope_paused(job, false); + }; + request.work_ended = [&runtime, job] { + runtime.set_run_scope_paused(job, true); + runtime.release_run_presses(job); + }; + host_python_session(request, session); + return ToolResult::ok({{"status", "ended"}}); +} + +std::shared_ptr start_python_session(AutomationRuntime& runtime, std::shared_ptr session, + const boost::filesystem::path& file, PersonRun::Events events) +{ + const NativeCommand* script_run = NativeCommands::instance().find("script_run"); + if (script_run == nullptr || runtime.stopping() || !session) + return nullptr; + auto run = std::make_shared(runtime, std::move(events)); + auto hosted = std::make_shared>(false); + auto filename = file.empty() ? std::string("") : path_to_utf8(file); + // script_run's properties, outside the session journal, as a person's run. + NativeCommand def = *script_run; + def.journal = false; + def.run = [&runtime, run, session, hosted, filename](const json&, ToolContext& ctx) { + run->set_job(ctx.job_id()); + hosted->store(true); + // A handler that refuses never hosts the session: it ends here all the same. + struct Ended + { + PythonSession& session; + ~Ended() + { + if (!session.ended()) + session.host_returned(); + } + } ended{*session}; + return run_python_session_job(runtime, ctx, *session, filename); + }; + + FollowedCall call; + call.command = std::move(def); + call.origin = {{"source", "run_script"}}; + call.person = true; + call.ended = [&runtime, run, session, hosted](const std::optional& r) { + run->mark_ended(); + // Refused before its handler ran: the session was never hosted. + if (r && !hosted->load()) + session->host_returned(); + if (!r || runtime.stopping() || !r->is_error) + return; + run->post_finished(json{{"error", r->message}}, json()); + }; + call.stop = [run] { run->stop(); }; + if (!runtime.follow(std::move(call))) + return nullptr; + return run; +} + +namespace { + +// The recording tools only read the app, so they run behind dialogs and during operations, but each +// is a job: ownership is read from the job's ancestry, and an encode outlives the reply budget. +NativeCommand record_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) +{ + NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler)); + d.description = std::move(description); + d.listed = true; + d.guard = GuardClass::Inspect; + d.journal = true; + return d; +} + +json int_prop(int minimum, int maximum, const std::string& description) +{ + return {{"type", "integer"}, {"minimum", minimum}, {"maximum", maximum}, {"description", description}}; +} + +std::string read_text(const fs::path& path) +{ + boost::nowide::ifstream in(path_to_utf8(path).c_str(), std::ios::binary); + std::ostringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +void remove_quietly(const fs::path& path) +{ + boost::system::error_code ec; + fs::remove(path, ec); +} + +int process_id() +{ +#ifdef _WIN32 + return _getpid(); +#else + return int(getpid()); +#endif +} + +std::vector encode_preset_keys() +{ + std::vector keys; + for (const EncodePreset& p : encode_presets()) + keys.emplace_back(p.key); + return keys; +} + +} // namespace + +ToolResult start_encode(AutomationRuntime& runtime, const json& args, const std::string& stop_job) +{ + const NativeCommand* encode = NativeCommands::instance().find("recording_encode"); + if (encode == nullptr || runtime.stopping()) + return ToolResult::error("OrcaSlicer is shutting down"); + NativeCommand def = *encode; + def.journal = false; + def.budget_ms = 0; // the envelope at once; the result comes from app_wait + return runtime.core().call(def, args, {{"source", "agent"}, {"under", stop_job}}); +} + +void register_recording_tools(CommandCatalog& catalog) +{ + NativeCommand screenshot = inspect_tool( + "window_screenshot", L("Take a screenshot"), + "Capture what OrcaSlicer shows and return it as an image, downscaled to `max_dim` on the long edge (default 1280), " + "plus the full-size PNG written to `save_path` (or the session's output folder). `target: \"main\"` (the main " + "window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the " + "Design tab its view), " + "\"dialog\" (the topmost modal dialog), or a ref: a window's from `window_list` (one that is not modal, say), or a " + "widget's from `widget_list`, cropped to that widget (a page element's ref captures its whole web view). The result " + "says when parts may differ from the " + "screen (approximate). Point the view first with `view_set`.", + object_schema({{"target", {{"type", json::array({"string", "object"})}, + {"description", "main (default), canvas, dialog, or a widget's ref or locator from `widget_list`."}}}, + {"max_dim", {{"type", "integer"}, {"minimum", 256}, {"maximum", 2000}, {"description", "Long edge of the returned image."}}}, + {"save_path", prop("string", "Absolute .png path for the full-size image.")}, + {"overwrite", prop("boolean", "Replace an existing `save_path`.")}, + {"include_image", prop("boolean", "Return the image itself (default true); false returns only the path.")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + const json target_arg = args.value("target", json("main")); + const std::string target = target_arg.is_string() ? target_arg.get() : std::string(); + json locator; + fs::path path; + if (args.contains("save_path")) { + std::string err; + auto p = resolve_output_path(arg_string(args, "save_path"), arg_bool(args, "overwrite", false), err); + if (!p) + throw ToolFailure(err); + path = *p; + } else { + path = timestamped_path(output_dir(), "screenshot", ".png"); + } + const int max_dim = std::clamp(arg_int(args, "max_dim", 1280), 256, 2000); + json info; + wxImage full; + if (target != "main" && target != "canvas" && target != "dialog") + // Scrolled into view first, and painted before the capture below runs. + ctx.run_ui([&] { + UiTarget t = runtime.inspector().resolve(target_arg); + runtime.inspector().reveal(t); + return json(); + }); + // A canvas that comes back blank has not drawn yet; it does within moments. + bool blank = false; + for (int attempt = 0;; ++attempt) { + ctx.run_ui([&] { + std::string err; + std::optional cap; + if (target == "canvas") { + ui_plater(); // refuses while OrcaSlicer starts or closes + GLCanvas3D* canvas = shown_canvas(); + if (canvas == nullptr) + throw ToolFailure("No 3D view is shown; switch to one with view_set tab"); + cap = capture_canvas(*canvas, err); + } else if (target == "dialog") { + wxDialog* top = runtime.modals().top(); + if (top == nullptr) + throw ToolFailure(no_modal_dialog(runtime.modals())); + cap = capture_window(*top, err); + } else if (target != "main") { + // A widget: its top-level window, cropped to the widget unless it is that window. + const UiTarget t = runtime.inspector().resolve(target_arg); + locator = runtime.inspector().locator_for(t); + // A page element is captured as its web view. + wxWindow* w = t.window.get(); + if ((t.kind != UiTarget::Kind::Window && t.kind != UiTarget::Kind::WebElement) || w == nullptr) + throw ToolFailure("target must be main, canvas, dialog or the ref of a widget"); + if (t.kind == UiTarget::Kind::WebElement) { + // A replay captures the same web view, by its own locator: a page element's + // has none the window_screenshot's target takes. + UiTarget view; + view.kind = UiTarget::Kind::Window; + view.window = w; + view.locator = {{"class", "webview"}}; + if (const std::string within = within_of(w); !within.empty()) + view.locator["within"] = within; + locator = runtime.inspector().locator_for(view); + } + if (t.page >= 0) { + // A tab: its page, which only the selected tab shows. + auto* book = dynamic_cast(w); + if (book == nullptr || t.page >= int(book->GetPageCount())) + throw ToolFailure("The tab is gone; call widget_list again"); + if (book->GetSelection() != t.page) + throw ToolFailure("The tab's page is not shown; click the tab (widget_click) first"); + w = book->GetPage(size_t(t.page)); + } + if (GLCanvas3D* canvas = runtime.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { + cap = capture_canvas(*canvas, err); + } else { + wxWindow* top = wxGetTopLevelParent(w); + // A popup is a native window of its own, which its window's capture draws in. + if (dynamic_cast(top) != nullptr) + throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and widget_list " + "{target: \"popup\"} lists it"); + auto* tlw = dynamic_cast(top); + if (tlw == nullptr) + throw ToolFailure("The widget has no window"); + tlw->Update(); + cap = capture_window(*tlw, err); + if (cap && w != tlw) { + // The capture is in physical pixels, like client_offset_in(). + const wxPoint at = client_offset_in(*w, *tlw); + const double scale = tlw->GetContentScaleFactor(); + const wxSize size(int(std::lround(w->GetSize().x * scale)), int(std::lround(w->GetSize().y * scale))); + const wxRect r = wxRect(at, size).Intersect(wxRect(cap->image.GetSize())); + if (r.IsEmpty()) + throw ToolFailure("The widget is outside its window's visible area"); + cap->image = cap->image.GetSubImage(r); + } + } + } else { + wxTopLevelWindow* frame = wxGetApp().mainframe; + if (frame == nullptr) + throw ToolFailure("The main window is not up yet"); + cap = capture_window(*frame, err); + } + if (!cap) + throw ToolFailure(err); + full = cap->image; + info = {{"source", target.empty() ? json(target_arg) : json(target)}, {"width", full.GetWidth()}, {"height", full.GetHeight()}}; + if (cap->approximate) + info["approximate"] = true; + if (!cap->note.empty()) + info["note"] = cap->note; + blank = cap->blank_canvas; + return json(); + }); + if (!blank || attempt >= 10 || ctx.cancelled()) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + } + if (blank) { + const std::string undrawn = undrawn_window(ctx); + info["approximate"] = true; + info["note"] = info.value("note", std::string()) + (info.contains("note") ? "; " : "") + "the 3D view came back blank" + + (undrawn.empty() ? ", as if not drawn yet" : ": " + undrawn); + } + if (target_arg.is_string() && !locator.is_null()) { + // A replay needs the locator; refs mean nothing in another session. + json recorded = args; + recorded["target"] = locator; + ctx.set_journal_args(std::move(recorded)); + } + // Encoding and scaling run off the UI thread. + if (!full.SaveFile(from_path(path), wxBITMAP_TYPE_PNG)) + throw ToolFailure("Could not write " + path_to_utf8(path)); + info["path"] = path_to_utf8(path); + ToolResult out = ToolResult::ok(info); + if (arg_bool(args, "include_image", true)) { + const wxSize size = fit_within(full.GetSize(), max_dim); + const wxImage scaled = size == full.GetSize() ? full : full.Scale(size.x, size.y, wxIMAGE_QUALITY_HIGH); + out.data["image_width"] = size.x; + out.data["image_height"] = size.y; + out.content.push_back({{"type", "image"}, {"mimeType", "image/png"}, {"data", base64(encode_png(scaled))}}); + } + return out; + }); + screenshot.journal = true; // a replay takes the same screenshots + catalog.add(screenshot); + + const std::string saved = "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless " + "they chose another) and show the person a notification naming it; the reply has its path. Agents use " + "the window_screenshot tool, which returns the image."; + NativeCommand save_screenshot = menu_command("window_save_screenshot", L("Take Screenshot"), saved, object_schema({}), + json::array({NativeCommands::action("take_screenshot", L("Take Screenshot"), + L("Commands"), "screenshot", json::object(), saved)}), + [](const json&) { return MenuItems::take_screenshot(); }); + // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. + save_screenshot.listed = false; + catalog.add(std::move(save_screenshot)); + + NativeCommand run = mutate_tool( + "replay_run", L("Run a replay"), + std::string("Replay a list of tool calls in order and report each step: `{\"orca_replay_version\": \"") + + REPLAY_VERSION + + "\", name, vars, steps: [{tool, args, expect, optional, await, save_as, timeout_s}]}`, JSON with comments. " + "Strings may use `${replay_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and `${jobs.NAME}`. A step that " + "returns a job is awaited unless `await: false`, which stores the job under `save_as` so later steps can answer " + "the dialog it opened. `expect` maps a JSON pointer into the step's result to matchers (`eq` `ne` `gt` `ge` `lt` " + "`le` `contains` `regex` `exists` `empty`); the first failed step or expectation stops the run unless the step is " + "`optional`. Writes `result.json` to `out_dir` (default: a new folder `replay-` in " + "`orca_action_replay` in the temp folder, or in the `--outputdir` folder of a `--run` launch). Reply: `passed`, " + "`steps`, `failed_step`, `out_dir` and `result_file`. `dialog_auto_answer` rules a replay registers end with it. " + "`replay_export` turns this session into one.", + object_schema({{"path", prop("string", "Absolute path of a replay file.")}, + {"replay", {{"type", json::array({"object", "string"})}, + {"description", "The replay itself, as an object or as its JSON text, instead of `path`."}}}, + {"out_dir", prop("string", "Absolute directory for result.json and screenshots; created if missing.")}, + {"vars", {{"type", "object"}, {"description", "Values that override the replay's vars."}}}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + const bool has_path = args.contains("path"), has_replay = args.contains("replay"); + if (has_path == has_replay) + return invalid("give exactly one of path and replay"); + + std::optional replay; + ReplayContext sctx; + std::string err; + if (has_path) { + const auto path = resolve_input_path(arg_string(args, "path"), err); + if (!path) + return invalid(err); + std::string text; + try { + text = read_file(*path); + } catch (const ToolFailure& f) { + return invalid(f.what()); + } + replay = parse_replay(text, err); + sctx.replay_dir = path->parent_path(); + } else + replay = parse_replay(inline_replay_text(args["replay"]), err); + if (!replay) + return invalid(err); + for (const ReplayStep& step : replay->steps) + if (NativeCommands::instance().lookup(step.tool) == nullptr) + return invalid("unknown tool " + step.tool); + if (args.contains("vars")) + for (const auto& [key, value] : args["vars"].items()) + replay->vars[key] = value; + + sctx.out_dir = args.contains("out_dir") ? path_from_utf8(arg_string(args, "out_dir")) : replay_output_dir(); + if (!sctx.out_dir.is_absolute()) + return invalid("out_dir must be an absolute path"); + if (!has_path) + sctx.replay_dir = sctx.out_dir; + json result = run_replay_job(runtime, ctx, *replay, sctx, ReplayRunOptions{}); + return ToolResult::ok(std::move(result)); + }); + // Its steps call any tool, script_run included. + run.open_world = true; + catalog.add(run); + + NativeCommand exp = inspect_tool( + "replay_export", L("Export this session as a replay"), + "Turn the calls this session made into a replay that `replay_run` runs: mutating calls, `app_wait`, `window_screenshot` and the " + "recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and `window_screenshot` " + "and recording paths moved under `${out_dir}`. " + "Calls that failed, at once or as a job later, are left out (a `script_run` that raised or timed out replied, so it " + "stays); so is a call whose job is still running (unless it " + "waits on a dialog), which `left_out_running` lists as `{tool, job}`. " + "Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.", + object_schema({{"name", prop("string", "Replay name.")}, + {"path", prop("string", "Absolute .json path to write.")}, + {"overwrite", prop("boolean", "Replace an existing file.")}, + {"clear", prop("boolean", "Forget the calls recorded so far once exported.")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + if (!ctx.caller_plugin().empty()) + throw ToolFailure("replay_export exports the agent's session, which a plugin's calls are not part of"); + json running; + json replay = runtime.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running); + json out{{"steps", replay["steps"].size()}}; + if (!running.empty()) + out["left_out_running"] = std::move(running); + if (args.contains("path")) { + std::string err; + const auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err); + if (!path) + throw ToolFailure(err); + write_file(*path, replay.dump(2)); + out["path"] = path_to_utf8(*path); + } + if (arg_bool(args, "clear", false)) + runtime.journal().clear(); + out["replay"] = std::move(replay); + return ToolResult::ok(std::move(out)); + }); + exp.read_only = false; + // clear empties the journal, so a second call exports less. + exp.idempotent = false; + catalog.add(exp); + + NativeCommand script = mutate_tool( + "script_run", L("Run a Python script"), + "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against `orca.host`, the whole plugin " + "API (`script_list_api` lists it): read objects, meshes and settings, compute, use `orca.host.ui` and the preset " + "API, and call these same tools, with their guards and undo, through `orca.host.tools.call`(name, args). Mesh and " + "matrix arrays need numpy, which " + "`script_list_api` says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " + "thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon " + "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " + "to a JSON value to return it; print() output comes back as output. Reply: `{status: finished | raised | cancelled | " + "timed_out, result, output, traceback?, message?}`; a script that raised changed what it changed before. The code's " + "own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a " + "file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises " + "PermissionError, unless a person has let Python scripts run unrestricted in Preferences " + "(`app_state.python.scripts_unrestricted`), when the threads and pool tasks it starts call the tools too while " + "the run lasts; the tools it calls work as they do for you. Recorded " + "by `replay_export` as one step with its code, which a replay runs again against the project as it is then.", + object_schema({{"code", prop("string", "Python source, run as a module body.")}, + {"args", {{"type", "object"}, {"description", "Bound to the name `args` in the code."}}}, + {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 3600}, + {"description", "The run is stopped as `timed_out` after this many seconds (default 300)."}}}, + {"filename", prop("string", "The name tracebacks show for the code (default ). An existing file's " + "path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports " + "from its folder and its PEP 723 dependencies; any other name only names it. " + "What runs is still `code`: pass the file's text there.")}}, + {"code"}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + // A plugin's script is the plugin's own code: its identity and grants. + const std::string& plugin = ctx.caller_plugin(); + const std::string identity = !plugin.empty() ? plugin : + runtime.jobs().person_in(ctx.lineage()) ? kScriptIdentityPerson : + kScriptIdentityAgent; + + // A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON + // script does: it all ends with the run. + const std::string job = ctx.job_id(); + // A run may wait for a person in its window: `app_wait {for: "idle"}` counts only the calls it makes. + runtime.jobs().set_idle(job); + runtime.begin_run_scope(job); + struct ScopeEnd + { + AutomationRuntime& runtime; + std::string job; + ~ScopeEnd() { runtime.end_run_scope(job); } + } scope_end{runtime, job}; + + RunBridge bridge(ctx); + ScopedToolBridge bound(bridge); + PythonRunRequest request; + request.code = arg_string(args, "code"); + request.args = args.value("args", json::object()); + request.identity = identity; + request.filename = arg_string(args, "filename", ""); + // 0, below the schema's minimum, is passed only in process, by the Run Script dialog, whose Stop ends a run: + // every external path validates the arguments. It means no time limit. + request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300)); + request.cancelled = [&ctx] { return ctx.cancelled(); }; + // A stop or time-out cancels the run's tool calls in flight too, so one that waits returns at once. + request.stop_calls = [&runtime, job] { runtime.jobs().request_stop(job); }; + const PythonRunOutcome out = run_python_code(request); + if (out.status == "unavailable") + throw ToolFailure(out.message); + + json data{{"status", out.status}, {"result", out.result}, {"output", out.output}}; + if (!out.traceback.empty()) + data["traceback"] = out.traceback; + if (!out.message.empty()) + data["message"] = out.message; + // A run that did not finish is reported, not failed, as replay_run reports a failed step: the + // journal keeps it, and a replay of it fails again (D7). + return ToolResult::ok(std::move(data)); + }); + // job_cancel {job} stops a run: its code is interrupted at its next bytecode. + script.cancellable = true; + // A script reaches outside the app: files, programs and the network. + script.open_world = true; + catalog.add(script); + + // Both read the package as Python runs it now, holding its runtime for the read as script_run does. + const auto while_python_runs = [](const auto& read) { + if (!PythonInterpreter::instance().is_initialized()) + throw ToolFailure("Python is not available in this OrcaSlicer"); + PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); + if (!lease) + throw ToolFailure("Python is shutting down"); + return read(); + }; + catalog.add(inspect_tool( + "script_list_api", L("List the Python API"), + "List `orca`, the Python API of `script_run` scripts and plugins, in the running build, one module or class at a time: " + "`orca.host` (the project's model and meshes, presets and their editors, slicing data, `orca.host.ui` windows and " + "dialogs, `orca.host.tools` calling these tools) and the classes, events and pages plugins build on. It lists what is " + "directly inside `within`, a module or a class (default `orca`): each entry's `name`, `kind`, `signature` (a " + "class's constructors) and the first sentence of its documentation. A module or class it lists is listed with " + "`within` set " + "to its name, and `script_describe_api {name}` gives an entry's whole documentation. Page with `offset`. `numpy` says " + "whether numpy is installed, which mesh and matrix arrays need.", + object_schema({{"within", {{"type", "string"}, {"default", kPythonApiRoot}, + {"description", "A module's or class's dotted name, e.g. \"orca.host\" or " + "\"orca.host.TriangleMesh\"."}}}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [while_python_runs](const json& args, ToolContext&) { + return ToolResult::ok(while_python_runs([&args] { + json out = page(python_api_children(python_api_reference(), arg_string(args, "within", kPythonApiRoot)), args, 20); + out["numpy"] = python_has_numpy(); + return out; + })); + })); + catalog.add(inspect_tool( + "script_describe_api", L("Describe a Python API entry"), + "Read one entry of `orca`, the Python API of `script_run` scripts and plugins, by its dotted name as `script_list_api` " + "lists it (`orca.host.TriangleMesh.face_normals`): its `kind`, its `signature` (a class's constructors) and its whole " + "documentation. A name no entry has is refused with the closest names.", + object_schema({{"name", prop("string", "An entry's dotted name, as `script_list_api` lists it.")}}, {"name"}), + [while_python_runs](const json& args, ToolContext&) { + return ToolResult::ok( + while_python_runs([&args] { return python_api_entry(python_api_reference(), arg_string(args, "name")); })); + })); + + // The Run Script panel's menu item, which has no argument form. + const std::string panel = "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents " + "run Python with the script_run tool instead."; + NativeCommand toggle_panel = menu_command("script_toggle_panel", L("Run Script"), panel, object_schema({}), + json::array({NativeCommands::action("toggle_run_script_panel", L("Run Script"), + L("Commands"), "media_play", json::object(), panel)}), + [](const json&) { return MenuItems::toggle_run_script_panel(); }); + // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. + toggle_panel.listed = false; + catalog.add(std::move(toggle_panel)); + + // The Speed Dial's Start Recording is its action: with no arguments it opens the action's dialog. + NativeCommand start = record_tool( + "recording_start", L("Start Recording"), + "Record a video of OrcaSlicer until `recording_stop`: MJPEG frames with their real timestamps in a Matroska (.mkv) " + "file. Captions show the tool call acting on the app at the bottom (secret setting values never show); pointer " + "highlights the pointer, its clicks rippling. Capture takes at most about a third of the UI thread, so the frame " + "rate drops where capturing is slow. One recording at a time: a replay's or script's ends with it, a client's when " + "the server is turned off. With encode, the `recording_stop` that reports it also writes an MP4 beside it and " + "deletes the .mkv unless `keep_raw_video_file`; `recording_encode` encodes any recording later. With no arguments it " + "opens the Start Recording dialog (`blocked_by_dialog`), whose controls are named after their settings for " + "`widget_set_value`; its \"Start recording\" starts the person's recording, which neither a replay's or script's end " + "nor the server turning off ends, and the dialog remembers the settings. `silent: true` starts one at once with the " + "defaults.", + object_schema({{"target", enum_prop({"main", "canvas"}, "main (default): the main window and its dialogs; canvas: the 3D view shown.")}, + {"fps", int_prop(1, 30, "Frames per second at most (default 10).")}, + {"max_dim", int_prop(320, 3840, "Long edge of the video in pixels (default 1920).")}, + {"jpeg_quality", int_prop(30, 95, "JPEG quality of the frames (default 80).")}, + {"max_seconds", int_prop(1, 3600, "The recording ends on its own after this long (default 3600).")}, + {"captions", prop("boolean", "Caption the tool call acting on the app (default false).")}, + {"pointer", prop("boolean", "Highlight the pointer and show its clicks (default false).")}, + {"encode", prop("boolean", "Encode it to an MP4 once stopped; needs an ffmpeg (default false).")}, + {"encode_preset", enum_prop(encode_preset_keys(), "With encode: the settings the fields below change " + "(default balanced: h265, crf 28, medium, main).")}, + {"codec", enum_prop({"h265", "h264"}, "With encode: the codec (default the preset's).")}, + {"crf", int_prop(0, 51, "With encode: constant rate factor, lower is better and larger (default the preset's).")}, + {"speed", enum_prop(encoder_speeds(), "With encode: slower makes a smaller file (default the preset's).")}, + {"profile", enum_prop({"high", "main", "baseline", "main10"}, + "With encode: h264 high, main or baseline; h265 main or main10 (default the preset's, else " + "the codec's first).")}, + {"keep_raw_video_file", prop("boolean", "With encode: keep the .mkv beside the MP4 (default false).")}, + {"save_path", prop("string", "Absolute .mkv path; default the session's output folder.")}, + {"overwrite", prop("boolean", "Replace an existing `save_path`, and with encode its MP4.")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + RecordingOptions o; + o.target = arg_string(args, "target", "main"); + o.fps = arg_int(args, "fps", 10); + o.max_dim = arg_int(args, "max_dim", 1920); + o.quality = arg_int(args, "jpeg_quality", 80); + o.max_seconds = arg_int(args, "max_seconds", 3600); + o.captions = arg_bool(args, "captions", false); + o.pointer = arg_bool(args, "pointer", false); + // The encode with the Start Recording dialog's defaults, the Balanced preset. + RecordingSettings settings; + if (const std::string err = apply_recording_overrides(settings, args); !err.empty()) + throw ToolFailure(err); + if (std::string err; settings.encode && !find_ffmpeg(err)) + throw ToolFailure("Cannot encode: " + err); + if (args.contains("save_path")) { + const std::string path = arg_string(args, "save_path"); + if (!boost::algorithm::iends_with(path, ".mkv")) + throw ToolFailure("save_path must end with .mkv: the recording is Matroska"); + std::string err; + auto p = resolve_output_path(path, arg_bool(args, "overwrite", false), err); + if (!p) + throw ToolFailure(err); + o.path = *p; + } else { + o.path = timestamped_path(output_dir(), "recording", ".mkv", {".mp4"}); + } + if (settings.encode) { + o.encode = encode_arguments(settings, path_to_utf8(o.path)); + if (arg_bool(args, "overwrite", false)) + o.encode["overwrite"] = true; + } + // Like auto-answer rules: a run's recording ends with the run, a client's with the endpoint. + const std::vector ancestry = runtime.jobs().ancestry(ctx.job_id()); + o.owner = runtime.run_owner(ancestry); + // A call of a run that has ended (its scope gone before this ran): not a client's call. + if (o.owner.empty() && runtime.recorder().owner_ended_in(ancestry)) + throw ToolFailure("The replay or script that started the recording has ended"); + // Reserved here, off the UI thread: comparing paths may touch the disk. start() keeps the + // reservation for the recording or releases it. + const std::shared_ptr& files = runtime.recorder().files(); + const uint64_t owner = files->new_owner(); + if (const std::string why = files->reserve(owner, {{o.path, RecordingFiles::Use::Recording}}); !why.empty()) + throw ToolFailure("Cannot record there: " + why); + bool handed_over = false; + struct Release + { + RecordingFiles& files; + uint64_t owner; + const bool& handed_over; + ~Release() + { + if (!handed_over) + files.release(owner); + } + } release{*files, owner, handed_over}; + json out = ctx.run_ui([&] { + ui_plater(); // refuses while OrcaSlicer starts or closes + // On the UI thread, as close_client_scope() runs: a client's start queued while the endpoint + // closed must not begin a recording nothing would end. + if (o.owner.empty() && !runtime.client_scope_open()) + throw ToolFailure("The MCP server was turned off; the recording was not started"); + handed_over = true; // start() owns the reservation from here, success or not + return runtime.recorder().start(o, owner); + }); + if (settings.encode) + out["encode"] = {{"codec", settings.codec}, + {"crf", settings.crf}, + {"speed", settings.speed}, + {"profile", settings.profile}, + {"keep_raw_video_file", settings.keep_raw_video_file}}; + // The limit it runs under, which a call that leaves it out did not choose. + out["max_seconds"] = o.max_seconds; + // The path used, so a replay records into its own output folder under the same name and its + // encode finds it there. + json recorded = args; + recorded["save_path"] = out["path"]; + ctx.set_journal_args(std::move(recorded)); + return ToolResult::ok(out); + }); + start.actions = json::array({NativeCommands::action("start_recording", L("Start Recording"), L("Commands"), "recording_start", + json::object(), + "Runs recording_start with no arguments, as Start Recording does: the Start " + "Recording dialog, whose Start recording starts the person's recording, " + "which neither the end of a replay or script nor the server turning off ends.")}); + catalog.add(NativeCommands::with_person_form(std::move(start), [](const json&) { return NativeCommands::start_person_recording(); })); + + // The Speed Dial's Stop Recording is its action: with no arguments it stops as the action does. + NativeCommand stop = record_tool("recording_stop", L("Stop Recording"), + "Stop the running recording. Call it with `silent: true` for the report: it waits for the file and " + "returns it with its seconds, frames captured and " + "written, frames dropped when encoding fell behind, failed when they could not be encoded, or " + "skipped when the window could not be captured, " + "the size, the mean UI-thread time a capture took (`capture_ms`), and why it ended. A recording that ended on its own (`max_seconds`, the replay or script that started it ended, a " + "write error) is reported once by the next `recording_stop`. For a recording started with encode, it then " + "starts the MP4 encode and returns it under encode: a job, whose `app_wait {for: \"job\"}` returns " + "`recording_encode`'s result, whose `raw_video_file_deleted` says whether the .mkv was deleted. " + "Called with no arguments, it stops " + "the recording as Stop Recording does, whoever started it: without waiting for its " + "file, it shows the person a notification naming it and replies with its path; the next " + "`recording_stop` with `silent: true` reports it as ended `stopped_in_app`.", + object_schema({}), [](const json&, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + // The last state too, even if the timer has not ticked since the last call. Without the + // UI thread (a native dialog holds it), the recording ends with its last frame. + try { + ctx.run_ui([&] { + runtime.recorder().capture_now(); + return json(); + }); + } catch (const ToolFailure&) { + } + json encode; + json report = runtime.recorder().stop_and_report(std::chrono::seconds(60), encode); + if (report.is_null()) + throw ToolFailure("No recording is running"); + if (!encode.is_null()) { + const ToolResult r = start_encode(runtime, encode, ctx.job_id()); + report["encode"] = r.is_error ? json{{"error", r.message}} : r.data; + } + return ToolResult::ok(report); + }); + stop.actions = json::array({NativeCommands::action("stop_recording", L("Stop Recording"), L("Commands"), "recording_stop", + json::object(), + "Runs recording_stop with no arguments, as Stop Recording does: it stops the " + "recording, whoever started it, and shows the person a notification naming its " + "file.")}); + // The person's stop opens nothing: like the silent one, it stops a recording behind a dialog. + stop = NativeCommands::with_person_form(std::move(stop), [](const json&) { return NativeCommands::stop_recording_in_app(); }, + /*person_form_behind_dialogs=*/true); + // It has no other argument, and neither form asks: silent picks the form that waits and reports. + stop.input_schema["properties"]["silent"]["description"] = + "true waits for the file and returns the report, and the encode job when the recording has one; a call with no " + "arguments stops as Stop Recording does."; + catalog.add(stop); + + NativeCommand encode = record_tool( + "recording_encode", L("Encode a recording"), + "Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it " + "needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names " + "one, and writes beside it unless `save_path` says where. A long encode returns a job: `app_wait` waits for it, or `job_cancel {job}` " + "stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless `keep_raw_video_file`; " + "any other .mkv is kept. `raw_video_file_deleted` in the reply says which.", + object_schema({{"path", prop("string", "Absolute .mkv of a finished recording; default this session's last.")}, + {"save_path", prop("string", "Absolute .mp4 path; default the recording's, with .mp4.")}, + {"overwrite", prop("boolean", "Replace an existing `save_path`.")}, + {"codec", enum_prop({"h265", "h264"}, "Default h265.")}, + {"crf", int_prop(0, 51, "Constant rate factor, lower is better and larger (default 28 for h265, 23 for h264).")}, + {"speed", enum_prop(encoder_speeds(), "The encoder's preset: slower makes a smaller file of the same quality (default medium).")}, + {"profile", enum_prop({"high", "main", "baseline", "main10"}, + "h264: high, main or baseline; h265: main, or main10 for 10 bits per sample. Default the " + "encoder's (high, main).")}, + {"keep_raw_video_file", prop("boolean", "Keep the .mkv beside the MP4 (default false: a recording this " + "session made is deleted once the MP4 is written).")}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + const std::shared_ptr& files = runtime.recorder().files(); + std::string err; + fs::path source; + if (args.contains("path")) { + auto p = resolve_input_path(arg_string(args, "path"), err); + if (!p) + throw ToolFailure(err); + source = *p; + } else if (auto last = files->last_finished()) { + source = *last; + } else { + throw ToolFailure("No recording of this session has finished; give path"); + } + if (!boost::algorithm::iends_with(path_to_utf8(source), ".mkv")) + throw ToolFailure("path must be a .mkv recording"); + if (boost::system::error_code ec; !fs::is_regular_file(source, ec)) + throw ToolFailure("No such recording: " + path_to_utf8(source)); + + const bool overwrite = arg_bool(args, "overwrite", false); + fs::path dest; + if (args.contains("save_path")) { + auto p = resolve_output_path(arg_string(args, "save_path"), overwrite, err); + if (!p) + throw ToolFailure(err); + dest = *p; + } else { + dest = source; + dest.replace_extension(".mp4"); + if (boost::system::error_code ec; fs::exists(dest, ec) && !overwrite) + throw ToolFailure(path_to_utf8(dest) + " exists; set overwrite or give save_path"); + } + if (RecordingFiles::same_file(source, dest)) + throw ToolFailure("save_path is the recording itself"); + // The .mkv goes once the MP4 is written unless it is to be kept, and only a recording this session made: + // any other .mkv is the person's own file, so it stays. + const bool keep_asked = arg_bool(args, "keep_raw_video_file", false); + const bool ours = files->is_finished(source); + const bool remove = !keep_asked && ours; + + const std::string codec = arg_string(args, "codec", "h265"); + const std::string encoder = encoder_for(codec); + const int crf = arg_int(args, "crf", codec == "h265" ? 28 : 23); + const std::string profile = arg_string(args, "profile", ""); + if (const std::vector profiles = codec_profiles(codec); + !profile.empty() && std::find(profiles.begin(), profiles.end(), profile) == profiles.end()) + throw ToolFailure(codec + " has no " + profile + " profile"); + const auto ffmpeg = find_ffmpeg(err); + if (!ffmpeg) + throw ToolFailure(err); + + const uint64_t owner = files->new_owner(); + if (const std::string why = files->reserve(owner, {{source, remove ? RecordingFiles::Use::ExclusiveSource : RecordingFiles::Use::Source}, + {dest, RecordingFiles::Use::Destination}}); + !why.empty()) + throw ToolFailure("Cannot encode now: " + why); + // Every file this call makes is its own, so failing or a cancel removes only those. + const std::string tag = "." + std::to_string(process_id()) + "-" + std::to_string(owner); + const fs::path part = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".part").native()); + const fs::path log = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".log").native()); + const fs::path probe = dest.parent_path() / (dest.filename().native() + path_from_utf8(tag + ".probe").native()); + struct Cleanup + { + RecordingFiles& files; + uint64_t owner; + std::vector paths; + bool release = true; + ~Cleanup() + { + for (const fs::path& p : paths) + remove_quietly(p); + if (release) + files.release(owner); + } + } cleanup{*files, owner, {part, log, probe}}; + const auto cancelled = [&ctx] { return ctx.cancelled(); }; + + // What this ffmpeg is: the options that keep the timing depend on its version, and the encoder + // must be built in. + auto listing = [&](const char* what) { + const ProcessOutcome r = run_process(*ffmpeg, {"-hide_banner", what}, probe, {}, cancelled, std::chrono::seconds(20)); + if (ctx.cancelled()) + throw ToolFailure("The encode was cancelled"); + if (!r.started || r.timed_out || r.exit_code != 0) + throw ToolFailure("Cannot run " + path_to_utf8(*ffmpeg) + " " + what); + return read_text(probe); + }; + const FfmpegVersion version = parse_ffmpeg_version(listing("-version")); + if (parse_encoders(listing("-encoders")).count(encoder) == 0) + throw ToolFailure(path_to_utf8(*ffmpeg) + " has no " + encoder + + " encoder. Install an ffmpeg built with it (Homebrew, winget Gyan.FFmpeg, Debian/Ubuntu ffmpeg) or " + "point ORCA_FFMPEG at one"); + + EncodeSpec spec; + spec.input = path_to_utf8(source); + spec.output = path_to_utf8(part); + spec.codec = codec; + spec.crf = crf; + spec.speed = arg_string(args, "speed", "medium"); + spec.profile = profile; + ProcessOutcome run; + // A build whose version is unknown may refuse the current spelling of the timing options: the next. + const std::vector timings = timing_candidates(version); + for (std::size_t i = 0; i < timings.size(); ++i) { + spec.timing = timings[i]; + run = run_process(*ffmpeg, encode_args(spec), {}, log, cancelled, std::chrono::hours(4)); + const bool refused = run.started && run.gone && !run.cancelled && !run.timed_out && run.exit_code != 0 && + refused_timing_option(file_tail(log, 6)); + if (!refused || i + 1 == timings.size()) + break; + } + if (!run.gone) { + // It may still read the source and write its files: they are left for it, and the source and + // destination stay reserved for the session, so no later encode deletes or writes them under it. + cleanup.paths = {probe}; + cleanup.release = false; + throw ToolFailure("ffmpeg did not exit after it was stopped; " + path_to_utf8(part) + " and " + path_to_utf8(log) + + " are left, and " + path_to_utf8(source) + " stays in use until OrcaSlicer restarts"); + } + if (run.cancelled) + throw ToolFailure("The encode was cancelled"); + if (!run.started) + throw ToolFailure("Cannot run " + path_to_utf8(*ffmpeg)); + if (run.timed_out || run.exit_code != 0) { + const std::string tail = file_tail(log, 6); + throw ToolFailure(run.timed_out ? "ffmpeg did not finish within 4 hours" : + "ffmpeg failed" + (tail.empty() ? std::string() : ":\n" + tail)); + } + const double seconds = mp4_duration(part).value_or(0.); + + boost::system::error_code ec; + if (!overwrite && fs::exists(dest, ec)) + throw ToolFailure(path_to_utf8(dest) + " appeared while encoding; set overwrite to replace it"); + fs::rename(part, dest, ec); // replaces an existing file on every platform + if (ec) + throw ToolFailure("Cannot write " + path_to_utf8(dest) + ": " + ec.message()); + if (remove && fs::remove(source, ec)) + files->forget(source); + const uintmax_t size = fs::file_size(dest, ec); + json out{{"path", path_to_utf8(dest)}, + {"source", path_to_utf8(source)}, + {"codec", codec}, + {"encoder", encoder}, + {"seconds", std::round(seconds * 10.) / 10.}, + {"size_bytes", ec ? 0 : size}}; + out["raw_video_file_deleted"] = remove && !fs::exists(source, ec); + if (!keep_asked && !ours) + out["note"] = "The .mkv was kept: an encode deletes only a recording this session made"; + return ToolResult::ok(out); + }); + encode.cancellable = true; + catalog.add(encode); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/Tools/ToolsCommon.cpp similarity index 90% rename from src/slic3r/GUI/Mcp/McpToolsCommon.cpp rename to src/slic3r/GUI/Mcp/Tools/ToolsCommon.cpp index 58267cbebc..a1a39e1154 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/Tools/ToolsCommon.cpp @@ -1,27 +1,34 @@ -#include "McpTools.hpp" +// The helpers every place's commands are built with (McpTools.hpp): the schema helpers, the command makers, the +// handler helpers and the id arguments. -#include "McpArguments.hpp" -#include "McpTargets.hpp" - -#include "libslic3r/Model.hpp" - -#include "UiInspector.hpp" +#include "slic3r/GUI/Mcp/McpArguments.hpp" +#include "slic3r/GUI/Mcp/McpTargets.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" -#include "slic3r/GUI/NativeCommands.hpp" -#include "slic3r/GUI/Operations/Outcome.hpp" -#include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/Operations/ObjectOps.hpp" +#include "slic3r/GUI/Operations/Outcome.hpp" +#include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/Plater.hpp" -#include +#include "libslic3r/Model.hpp" +#include "libslic3r/Slicing.hpp" + #include +#include +#include #include #include +#include + #include #include #include @@ -30,7 +37,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -133,6 +142,7 @@ bool canvas_being_mapped() } #ifdef __WXGTK__ + // The main window's frame clock, or null while the window is hidden or minimized, so not meant to be // drawn. UI thread. GdkFrameClock* main_frame_clock() @@ -353,4 +363,36 @@ void check_expected_ids(const ModelObject& object, const ModelVolume* volume, co {{"id", instance->id().id}}); } +std::string mm(double z) +{ + std::ostringstream out; + out << z; + return out.str(); +} + +double rounded(double value, double scale) { return std::round(value * scale) / scale; } + +void journal_with_locator(ToolContext& ctx, const json& args, const json& locator) +{ + json recorded = args; + if (recorded.contains("target") && recorded["target"].is_string() && !locator.is_null()) + recorded["target"] = locator; + ctx.set_journal_args(std::move(recorded)); +} + +NativeCommand recover_input_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler) +{ + NativeCommand d = mutate_tool(std::move(name), std::move(title), std::move(description), std::move(schema), std::move(handler)); + d.guard = GuardClass::Recover; + return d; +} + +NativeCommand own_action(NativeCommand command, std::string section, std::string icon) +{ + command.has_own_action = true; + command.action_group = std::move(section); + command.icon = std::move(icon); + return command; +} + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/Tools/ViewTools.cpp similarity index 72% rename from src/slic3r/GUI/Mcp/McpToolsView.cpp rename to src/slic3r/GUI/Mcp/Tools/ViewTools.cpp index 527f12fe63..c5ff585516 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/Tools/ViewTools.cpp @@ -1,63 +1,62 @@ -// window_screenshot, plate_slice_stats and view_set: what the agent looks at and reads off the Preview, and -// pointing the view before looking; and the window commands made from menu items, window_open and -// window_save_screenshot. +// The place View and windows: view_set, pointing the view before looking: the main tab, the 3D view and its camera, +// the Preview's colour scheme, legend and layers, and the display switches; window_list and window_set, the app's +// windows listed, sized, moved and raised; and the window commands made from menu items, window_open and +// view_toggle_activity_panel. -#include "libvgcode/include/ColorRange.hpp" -#include "slic3r/GUI/I18N.hpp" -#include "libvgcode/include/Types.hpp" -#include "libvgcode/include/Viewer.hpp" -#include "McpPaths.hpp" -#include "AutomationRuntime.hpp" -#include "McpTools.hpp" -#include "ModalTracker.hpp" -#include "ScreenCapture.hpp" -#include "UiInspector.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpEndpoint.hpp" +#include "slic3r/GUI/Mcp/McpRecorder.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/PythonScriptsDialog.hpp" +#include "slic3r/GUI/Mcp/ScreenCapture.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/Mcp/WebPages.hpp" +#include "slic3r/GUI/Mcp/WindowControl.hpp" +#include "slic3r/GUI/Mcp/WindowNames.hpp" #include "slic3r/GUI/ActionRegistry.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GCodeViewer.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/Notebook.hpp" +#include "slic3r/GUI/NotificationManager.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PlateOps.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" -#ifdef SLIC3R_CAD -#include "McpToolsCad.hpp" -#include "slic3r/GUI/CAD/DesignCanvas.hpp" -#include "slic3r/GUI/CAD/DesignPanel.hpp" -#endif #include "libslic3r/AppConfig.hpp" -#include "libslic3r/Config.hpp" #include "libslic3r/ExtrusionEntity.hpp" -#include "libslic3r/GCode/GCodeProcessor.hpp" -#include "libslic3r/GCode/GCodeStatistics.hpp" #include "libslic3r/Geometry.hpp" -#include "libslic3r/Model.hpp" #include "libslic3r/Point.hpp" +#include "libvgcode/include/Types.hpp" +#include "libvgcode/include/Viewer.hpp" -#include -#include -#include - -#include +#include +#include #include +#include +#include #include #include -#include -#include #include +#include #include +#include + #include #include #include @@ -65,29 +64,29 @@ #include #include #include -#include +#include +#include #include -#include #include -#include #include #include +#ifdef SLIC3R_CAD +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#endif + +#if defined(__WXGTK__) +#include "slic3r/GUI/LinuxDisplayBackend.hpp" +#endif + namespace Slic3r { namespace GUI { namespace Mcp { using nlohmann::json; -namespace fs = boost::filesystem; namespace { -std::string base64(const std::string& bytes) -{ - namespace b64 = boost::beast::detail::base64; - std::string out(b64::encoded_size(bytes.size()), '\0'); - out.resize(b64::encode(out.data(), bytes.data(), bytes.size())); - return out; -} - // The ids of the main window's notebook pages, in the notebook's order. std::vector notebook_pages(const Notebook& notebook) { @@ -97,49 +96,6 @@ std::vector notebook_pages(const Notebook& notebook) return pages; } -// Rounded for a reply, which reads like the legend rather than the raw floats. -double rounded(double value, double scale) { return std::round(value * scale) / scale; } - -// The view types the legend shows a colour range for; the logarithmic layer time repeats the linear one. -constexpr libvgcode::EViewType range_view_types[] = { - libvgcode::EViewType::Height, libvgcode::EViewType::Width, - libvgcode::EViewType::Speed, libvgcode::EViewType::ActualSpeed, - libvgcode::EViewType::Acceleration, libvgcode::EViewType::Jerk, - libvgcode::EViewType::VolumetricFlowRate, libvgcode::EViewType::ActualVolumetricFlowRate, - libvgcode::EViewType::LayerTimeLinear, libvgcode::EViewType::FanSpeed, - libvgcode::EViewType::Temperature, libvgcode::EViewType::PressureAdvance}; - -// preview_state() of the Preview's toolpaths, plus which legend rows are visible and the colour range of -// every view type. Ranges span the whole print, but count travels, wipes and Custom extrusions only -// while the legend shows them. UI thread. -json preview_view(GLCanvas3D& canvas) -{ - // The viewer recomputes its ranges at its next frame after a legend change; nothing draws while - // the Preview is hidden, and nothing changes the legend then either. - canvas.set_as_dirty(); - canvas.render(); - GCodeViewer& viewer = canvas.get_gcode_viewer(); - const libvgcode::Viewer& toolpaths = viewer.get_viewer(); - json view = preview_state(viewer); - json features = json::object(); - for (const libvgcode::EGCodeExtrusionRole role : toolpaths.get_extrusion_roles()) - features[legend_feature_key(role)] = toolpaths.is_extrusion_role_visible(role); - json options = json::object(); - for (const libvgcode::EOptionType type : toolpaths.get_options()) - if (const char* key = legend_option_key(type)) - options[key] = toolpaths.is_option_visible(type); - view["legend"] = {{"features", std::move(features)}, {"options", std::move(options)}}; - json ranges = json::object(); - for (const libvgcode::EViewType type : range_view_types) { - // [FLT_MAX, -FLT_MAX] when the print has no such value. - const std::array& range = toolpaths.get_color_range(type).get_range(); - if (range[0] <= range[1]) - ranges[GCodeViewer::view_type_to_config_name(type)] = {rounded(range[0], 1e4), rounded(range[1], 1e4)}; - } - view["ranges"] = std::move(ranges); - return view; -} - // A legend key in any case, with _ or a space between words: "Filament changes" is filament_changes, // "sparse_infill" is Sparse infill. bool same_legend_key(const std::string& given, const std::string& name) @@ -519,319 +475,305 @@ const char* legend_option_key(libvgcode::EOptionType type) } } -json preview_features(const json& statistics) +namespace { + +// Whether the shown 3D view has drawn at its canvas's size, asking for a frame when it hasn't: until it +// has, the camera's viewport is the old size, which a fit or a screen_rect would use. True when no 3D +// view is shown. UI thread. +bool view_drawn_at_size() { - const json& summary = statistics.at("summary"); - const double total = summary.at("time").get(); - const auto row = [total](double seconds) { - return json{{"time_s", rounded(seconds, 100.)}, {"percent", total > 0. ? rounded(100. * seconds / total, 10.) : 0.}}; - }; - json out = json::object(); - for (const auto& feature : summary.at("features").items()) { - json r = row(feature.value().at("time").get()); - r["g"] = rounded(feature.value().at("weight").get(), 100.); - out[feature.key()] = std::move(r); - } - json travel = row(summary.at("travel_time").get()); - travel["mm"] = rounded(summary.at("travel_distance").get(), 10.); - out["Travel"] = std::move(travel); - return out; + GLCanvas3D* canvas = shown_canvas(); + if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) + return true; + // What render() gives the viewport: the canvas's size in GL pixels, at least 10. + const Size size = canvas->get_canvas_size(); + const std::array& viewport = ui_plater().get_camera().get_viewport(); + if (viewport[2] == std::max(10, size.get_width()) && viewport[3] == std::max(10, size.get_height())) + return true; + canvas->set_as_dirty(); + return false; } -json preview_layers(const json& statistics, bool with_features) +// The window window_set's target names: the main window, the topmost modal dialog, or the window a ref or +// locator is in. Refuses one no tool may size or move. `locator` gets what the journal records for a +// ref. UI thread. +wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, json& locator) { - json items = json::array(); - double below = 0.; - for (const json& layer : statistics.at("layers")) { - const double z = layer.at("z").get(); - json item{{"layer", items.size() + 1}, - {"z", z}, - {"height", rounded(z > below ? z - below : z, 1000.)}, - {"time_s", rounded(layer.at("time").get(), 100.)}, - {"g", rounded(layer.at("weight").get(), 1000.)}}; - if (with_features) { - json features = json::object(); - for (const auto& feature : layer.at("features").items()) - features[feature.key()] = rounded(feature.value().at("time").get(), 100.); - item["features"] = std::move(features); + wxWindow* window = nullptr; + if (target == "main") { + window = wxGetApp().mainframe; + if (window == nullptr) + throw ToolFailure("The main window is not up yet"); + } else if (target == "dialog") { + window = runtime.modals().top(); + if (window == nullptr) + throw ToolFailure(no_modal_dialog(runtime.modals())); + } else { + UiTarget t; + try { + t = runtime.inspector().resolve(target); + } catch (const ToolFailure& e) { + // A window's ref goes stale once the window is destroyed, and window_list gives the open ones'. + if (!target.is_string()) + throw; + throw ToolFailure(std::string(e.what()) + ", or window_list for the open windows", e.details); } - items.push_back(std::move(item)); - below = z; + locator = runtime.inspector().locator_for(t); + window = t.window.get() != nullptr ? wxGetTopLevelParent(t.window.get()) : nullptr; } - return items; + if (dynamic_cast(window) != nullptr) + throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (window_list)"); + auto* tlw = dynamic_cast(window); + if (tlw == nullptr) + throw ToolFailure("The target is in no window"); + if (tlw->GetName() == kHiddenFromAutomation) + throw ToolFailure("The window is the person's own, which no tool reaches"); + if (auto* dlg = dynamic_cast(tlw); dlg != nullptr && is_native_dialog(dlg)) + throw ToolFailure("A native dialog is placed by the system; answer it with dialog_answer"); + // A closed dialog may be hidden rather than destroyed, so its ref still resolves. + if (!tlw->IsShown()) + throw ToolFailure("The window is closed; window_list lists the open windows"); + return *tlw; } -json preview_objects(const json& statistics, const std::vector& object_names) +// `window` while it is still one of the app's top-level windows, else null: window_set keeps a plain +// pointer across its UI closures and checks it before following it. UI thread. +wxTopLevelWindow* live_window(wxTopLevelWindow* window) { - json out = json::array(); - for (const json& object : statistics.at("objects")) { - const std::string name = object.at("name").get(); - json item{{"name", name}, - {"instance", object.at("instance")}, - {"g", rounded(object.at("weight").get(), 100.)}, - {"support_g", rounded(object.at("support_weight").get(), 100.)}}; - const auto first = std::find(object_names.begin(), object_names.end(), name); - if (first != object_names.end() && std::find(std::next(first), object_names.end(), name) == object_names.end()) - item["object"] = std::distance(object_names.begin(), first); - out.push_back(std::move(item)); + for (wxWindow* w : wxTopLevelWindows) + if (w == window) + return window; + return nullptr; +} + +// window_set: checks the request and applies it in one UI closure, waits for the window to take it, +// then replies with what the window became. A size or position applies to the normal window, so a +// maximized or minimized one is restored first. Where the window system restores it later (GTK), the call +// waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to +// the restore sizes the window again, and wx would size it by the maximized window's decorations. A window +// brought back from the minimized state is finished restoring once it is back (finish_restore(), macOS). +ToolResult set_window(AutomationRuntime& runtime, ToolContext& ctx, const json& args) +{ + const json target = args.value("target", json("main")); + json locator; + // Never followed off the UI thread, and checked by live_window() on it: a wxWeakRef can't be made or + // dropped on this thread. + wxTopLevelWindow* window = nullptr; + bool main = false, modal = false, restoring = false, unminimizing = false; + WindowSettling settling; + const bool placing = args.contains("size") || args.contains("position"); + const std::string state = arg_string(args, "state"); + const auto minimized = [](const wxTopLevelWindow& w) { return std::string(window_state(w)) == "minimized"; }; + // The request, less the restore that comes before a size or position. UI thread. + const auto apply = [&](wxTopLevelWindow& w) { + if (args.contains("size")) + settling.limited = resize_window(w, wxSize(args["size"][0].get(), args["size"][1].get())); + // -1 is a place on a screen left of or above the primary one, not "keep this coordinate". + if (args.contains("position")) + w.Move(args["position"][0].get(), args["position"][1].get(), wxSIZE_ALLOW_MINUS_ONE); + if (state == "maximized") { + maximize_window(w); + } else if (state == "minimized") { + minimize_window(w); + } else if (state == "normal") { + settling.activation = settling.activation || (restore_needs_activation() && minimized(w)); + unminimizing = unminimizing || minimized(w); + restore_window(w); + } + if (arg_bool(args, "raise", false)) + raise_window(w); + }; + ctx.run_ui([&] { + wxTopLevelWindow& w = window_target(runtime, target, locator); + auto* dlg = dynamic_cast(&w); + main = &w == wxGetApp().mainframe; + modal = dlg != nullptr && dlg->IsModal(); + WindowAbilities abilities; + abilities.main = main; + abilities.modal = modal; + abilities.can_maximize = w.HasFlag(wxMAXIMIZE_BOX); + abilities.can_minimize = w.HasFlag(wxMINIMIZE_BOX); + abilities.positions_known = window_positions_known(); + if (const std::string refusal = window_request_refusal(args, abilities); !refusal.empty()) + throw ToolFailure(refusal); + window = &w; + if (placing && std::string(window_state(w)) != "normal") { + settling.activation = restore_needs_activation() && minimized(w); + unminimizing = minimized(w); + restoring = restore_window(w); + } + if (!restoring) + apply(w); + return json(); + }); + journal_with_locator(ctx, args, locator); + + // The window manager may apply a request later (X11) or animate it (macOS): a wait ends at two equal + // readings in a row in the state asked for. `holds` takes a reading and says whether the window held + // still in `wanted` (any state when empty). UI thread. + const char* closed = "The request was applied before the window closed"; + json last; + const auto holds = [&](const std::string& wanted) { + wxTopLevelWindow* w = live_window(window); + if (w == nullptr) + throw ToolFailure(closed); + const wxPoint pos = w->GetScreenPosition(); + const wxSize size = window_size(*w); + const std::string now = window_state(*w); + const json reading{pos.x, pos.y, size.x, size.y, now}; + return reading == std::exchange(last, reading) && (wanted.empty() || now == wanted); + }; + const auto cancelled = [] { return ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped"); }; + if (restoring) { + // The rest of the request goes to the window the restore left, normal or not. + poll_until(ctx, [&] { return holds("normal") ? json(true) : json(); }, state_change_timeout("normal"), std::chrono::milliseconds(50)); + if (ctx.cancelled()) + throw cancelled(); + ctx.run_ui([&] { + wxTopLevelWindow* w = live_window(window); + if (w == nullptr) + throw ToolFailure(closed); + apply(*w); + return json(); + }); + last = json(); } - return out; + + // For the main window the wait also lasts until its 3D view has drawn at the new size, which a + // minimized window never does. + std::string wanted = state; + if (wanted.empty() && placing) + wanted = "normal"; + const std::chrono::seconds timeout = state_change_timeout(wanted); + settling.seconds = int(timeout.count()); + const json done = poll_until( + ctx, + [&]() -> json { + if (wxTopLevelWindow* w = live_window(window); w != nullptr && unminimizing) + unminimizing = !finish_restore(*w); + settling.held = holds(wanted); + if (!settling.held) + return json(); + return !main || minimized(*live_window(window)) || view_drawn_at_size() ? json(true) : json(); + }, + timeout, std::chrono::milliseconds(50)); + if (done.is_null() && ctx.cancelled()) + throw cancelled(); + settling.drawn = !done.is_null(); + if (settling.held && !settling.drawn) + settling.undrawn = undrawn_window(ctx); + + json out = ctx.observe_ui([&] { + wxTopLevelWindow* w = live_window(window); + if (w == nullptr) + throw ToolFailure(closed); + // window_list's own entry, so the two report a window alike. + const json entry = runtime.inspector().window_entry(*w, modal); + json reply{{"title", entry["title"]}, {"kind", entry["kind"]}, {"ref", entry["ref"]}, {"size", {entry["width"], entry["height"]}}}; + if (entry.contains("x")) + reply["position"] = {entry["x"], entry["y"]}; + reply["state"] = entry["state"]; + reply["resizable"] = entry["resizable"]; + reply["scale"] = w->GetContentScaleFactor(); + // A minimized window may be on no display; the primary one stands for it then. + int index = wxDisplay::GetFromWindow(w); + for (unsigned i = 0; index == wxNOT_FOUND && i < wxDisplay::GetCount(); ++i) + if (wxDisplay(i).IsPrimary()) + index = int(i); + reply["display"] = display_area(unsigned(std::max(index, 0))); + if (arg_bool(args, "raise", false)) + reply["active"] = w->IsActive(); + return reply; + }); + add_window_notes(args, settling, out); + return ToolResult::ok(out); } -bool viewer_holds(const GCodeViewer& viewer, const GCodeProcessorResult* result) +} // namespace + +void add_window_notes(const json& args, const WindowSettling& settling, json& reply) { - return result != nullptr && viewer.has_data() && viewer.last_result_id() == result->id; + json adjusted = json::array(); + for (const std::string field : {"size", "position", "state"}) + if (args.contains(field) && reply.contains(field) && reply[field] != args[field]) + adjusted.push_back(field); + std::string note = settling.limited ? "size is held to the window's minimum or maximum size" : ""; + const auto add = [¬e](const std::string& why) { note += (note.empty() ? "" : "; ") + why; }; + if (!settling.held && settling.activation) + add("the compositor did not bring the window back: Wayland lets an app restore its minimized window only by " + "activating it, which the compositor allows only while the app may take the focus, so the person restores it " + "from the taskbar"); + else if (!settling.held) + add("the window manager did not apply the request within " + std::to_string(settling.seconds) + " s"); + else if (!settling.drawn) + add("the 3D view did not draw at the window's size within " + std::to_string(settling.seconds) + " s" + + (settling.undrawn.empty() ? "" : ": " + settling.undrawn)); + else if (note.empty() && !adjusted.empty()) + note = "the window manager adjusted the request"; + if (!adjusted.empty()) + reply["adjusted"] = std::move(adjusted); + if (!note.empty()) + reply["note"] = note; } -json preview_state(GCodeViewer& viewer) +std::string window_request_refusal(const json& args, const WindowAbilities& window) { - IMSlider* layers = viewer.get_layers_slider(); - if (!viewer.has_data() || layers == nullptr) - return nullptr; - const bool silent = viewer.get_viewer().get_time_mode() == libvgcode::ETimeMode::Stealth; - return json{{"view_type", GCodeViewer::view_type_to_config_name(viewer.get_view_type())}, - {"time_mode", silent ? "silent" : "normal"}, - {"layers", {layers->GetLowerValue() + 1, layers->GetHigherValue() + 1}}, - {"z", {rounded(layers->GetLowerValueD(), 1000.), rounded(layers->GetHigherValueD(), 1000.)}}, - {"layer_count", layers->GetMaxValue() + 1}}; + const bool size = args.contains("size"), position = args.contains("position"); + if (!size && !position && !args.contains("state") && !args.contains("raise")) + return "Give at least one of size, position, state or raise; window_list reads a window's geometry without changing it"; + // Two whole numbers that fit wx's int coordinates, both positive for a size. Whole floats pass, as + // they pass the schema's integer type. + const auto is_pair = [](const json& value, bool positive) { + const auto whole = [positive](const json& n) { + if (!n.is_number()) + return false; + const double d = n.get(); + return d == std::floor(d) && d >= (positive ? 1.0 : double(std::numeric_limits::min())) && + d <= double(std::numeric_limits::max()); + }; + return value.is_array() && value.size() == 2 && std::all_of(value.begin(), value.end(), whole); + }; + if (size && !is_pair(args.at("size"), true)) + return "Give size as [width, height], two positive integers"; + if (position && !is_pair(args.at("position"), false)) + return "Give position as [x, y], two integers"; + const json state = args.value("state", json()); + if ((state == "maximized" || state == "minimized") && (size || position)) + return "A " + state.get() + + " window's size and position are set by the system: give state alone, or size and position without state"; + if (state == "maximized" && !window.main && !window.can_maximize) + return "This window's title bar has no maximize button: give it a size instead"; + if (state == "minimized" && window.modal) + return "A modal dialog never minimizes, as the app would stay blocked with nothing showing: close the dialog instead"; + if (state == "minimized" && !window.main && !window.can_minimize) + return "This window's title bar has no minimize button: move it aside with position, or close it, instead"; + if (position && !window.positions_known) + return "position needs X11: Wayland gives an app no way to place its window or to read where it is. Leave position " + "out, or start OrcaSlicer with GDK_BACKEND=x11 to run it under XWayland, where every field works"; + return {}; +} + +json display_area(unsigned index) +{ + const wxRect area = wxDisplay(index).GetClientArea(); + return {{"index", index}, {"x", area.x}, {"y", area.y}, {"width", area.width}, {"height", area.height}}; } void register_view_tools(CommandCatalog& catalog) { - NativeCommand screenshot = inspect_tool( - "window_screenshot", L("Take a screenshot"), - "Capture what OrcaSlicer shows and return it as an image, downscaled to `max_dim` on the long edge (default 1280), " - "plus the full-size PNG written to `save_path` (or the session's output folder). `target: \"main\"` (the main " - "window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the " - "Design tab its view), " - "\"dialog\" (the topmost modal dialog), or a ref: a window's from `window_list` (one that is not modal, say), or a " - "widget's from `widget_list`, cropped to that widget (a page element's ref captures its whole web view). The result " - "says when parts may differ from the " - "screen (approximate). Point the view first with `view_set`.", - object_schema({{"target", {{"type", json::array({"string", "object"})}, - {"description", "main (default), canvas, dialog, or a widget's ref or locator from `widget_list`."}}}, - {"max_dim", {{"type", "integer"}, {"minimum", 256}, {"maximum", 2000}, {"description", "Long edge of the returned image."}}}, - {"save_path", prop("string", "Absolute .png path for the full-size image.")}, - {"overwrite", prop("boolean", "Replace an existing `save_path`.")}, - {"include_image", prop("boolean", "Return the image itself (default true); false returns only the path.")}}), - [](const json& args, ToolContext& ctx) { - AutomationRuntime& runtime = ctx.runtime(); - const json target_arg = args.value("target", json("main")); - const std::string target = target_arg.is_string() ? target_arg.get() : std::string(); - json locator; - fs::path path; - if (args.contains("save_path")) { - std::string err; - auto p = resolve_output_path(arg_string(args, "save_path"), arg_bool(args, "overwrite", false), err); - if (!p) - throw ToolFailure(err); - path = *p; - } else { - path = timestamped_path(output_dir(), "screenshot", ".png"); - } - const int max_dim = std::clamp(arg_int(args, "max_dim", 1280), 256, 2000); - json info; - wxImage full; - if (target != "main" && target != "canvas" && target != "dialog") - // Scrolled into view first, and painted before the capture below runs. - ctx.run_ui([&] { - UiTarget t = runtime.inspector().resolve(target_arg); - runtime.inspector().reveal(t); - return json(); - }); - // A canvas that comes back blank has not drawn yet; it does within moments. - bool blank = false; - for (int attempt = 0;; ++attempt) { - ctx.run_ui([&] { - std::string err; - std::optional cap; - if (target == "canvas") { - ui_plater(); // refuses while OrcaSlicer starts or closes - GLCanvas3D* canvas = shown_canvas(); - if (canvas == nullptr) - throw ToolFailure("No 3D view is shown; switch to one with view_set tab"); - cap = capture_canvas(*canvas, err); - } else if (target == "dialog") { - wxDialog* top = runtime.modals().top(); - if (top == nullptr) - throw ToolFailure(no_modal_dialog(runtime.modals())); - cap = capture_window(*top, err); - } else if (target != "main") { - // A widget: its top-level window, cropped to the widget unless it is that window. - const UiTarget t = runtime.inspector().resolve(target_arg); - locator = runtime.inspector().locator_for(t); - // A page element is captured as its web view. - wxWindow* w = t.window.get(); - if ((t.kind != UiTarget::Kind::Window && t.kind != UiTarget::Kind::WebElement) || w == nullptr) - throw ToolFailure("target must be main, canvas, dialog or the ref of a widget"); - if (t.kind == UiTarget::Kind::WebElement) { - // A replay captures the same web view, by its own locator: a page element's - // has none the window_screenshot's target takes. - UiTarget view; - view.kind = UiTarget::Kind::Window; - view.window = w; - view.locator = {{"class", "webview"}}; - if (const std::string within = within_of(w); !within.empty()) - view.locator["within"] = within; - locator = runtime.inspector().locator_for(view); - } - if (t.page >= 0) { - // A tab: its page, which only the selected tab shows. - auto* book = dynamic_cast(w); - if (book == nullptr || t.page >= int(book->GetPageCount())) - throw ToolFailure("The tab is gone; call widget_list again"); - if (book->GetSelection() != t.page) - throw ToolFailure("The tab's page is not shown; click the tab (widget_click) first"); - w = book->GetPage(size_t(t.page)); - } - if (GLCanvas3D* canvas = runtime.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { - cap = capture_canvas(*canvas, err); - } else { - wxWindow* top = wxGetTopLevelParent(w); - // A popup is a native window of its own, which its window's capture draws in. - if (dynamic_cast(top) != nullptr) - throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and widget_list " - "{target: \"popup\"} lists it"); - auto* tlw = dynamic_cast(top); - if (tlw == nullptr) - throw ToolFailure("The widget has no window"); - tlw->Update(); - cap = capture_window(*tlw, err); - if (cap && w != tlw) { - // The capture is in physical pixels, like client_offset_in(). - const wxPoint at = client_offset_in(*w, *tlw); - const double scale = tlw->GetContentScaleFactor(); - const wxSize size(int(std::lround(w->GetSize().x * scale)), int(std::lround(w->GetSize().y * scale))); - const wxRect r = wxRect(at, size).Intersect(wxRect(cap->image.GetSize())); - if (r.IsEmpty()) - throw ToolFailure("The widget is outside its window's visible area"); - cap->image = cap->image.GetSubImage(r); - } - } - } else { - wxTopLevelWindow* frame = wxGetApp().mainframe; - if (frame == nullptr) - throw ToolFailure("The main window is not up yet"); - cap = capture_window(*frame, err); - } - if (!cap) - throw ToolFailure(err); - full = cap->image; - info = {{"source", target.empty() ? json(target_arg) : json(target)}, {"width", full.GetWidth()}, {"height", full.GetHeight()}}; - if (cap->approximate) - info["approximate"] = true; - if (!cap->note.empty()) - info["note"] = cap->note; - blank = cap->blank_canvas; - return json(); - }); - if (!blank || attempt >= 10 || ctx.cancelled()) - break; - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - } - if (blank) { - const std::string undrawn = undrawn_window(ctx); - info["approximate"] = true; - info["note"] = info.value("note", std::string()) + (info.contains("note") ? "; " : "") + "the 3D view came back blank" + - (undrawn.empty() ? ", as if not drawn yet" : ": " + undrawn); - } - if (target_arg.is_string() && !locator.is_null()) { - // A replay needs the locator; refs mean nothing in another session. - json recorded = args; - recorded["target"] = locator; - ctx.set_journal_args(std::move(recorded)); - } - // Encoding and scaling run off the UI thread. - if (!full.SaveFile(from_path(path), wxBITMAP_TYPE_PNG)) - throw ToolFailure("Could not write " + path_to_utf8(path)); - info["path"] = path_to_utf8(path); - ToolResult out = ToolResult::ok(info); - if (arg_bool(args, "include_image", true)) { - const wxSize size = fit_within(full.GetSize(), max_dim); - const wxImage scaled = size == full.GetSize() ? full : full.Scale(size.x, size.y, wxIMAGE_QUALITY_HIGH); - out.data["image_width"] = size.x; - out.data["image_height"] = size.y; - out.content.push_back({{"type", "image"}, {"mimeType", "image/png"}, {"data", base64(encode_png(scaled))}}); - } - return out; - }); - screenshot.journal = true; // a replay takes the same screenshots - catalog.add(screenshot); + using NativeCommands::action; - catalog.add(inspect_tool( - "plate_slice_stats", L("Get slice statistics"), - "What the Preview shows for a sliced plate. summary: `plate_slice`'s, plus prepare and travel time and travel " - "distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and " - "travel. layers: per layer (1-based, as `view_set`'s layer) Z, height, seconds and grams, paged; `layer_features` adds " - "each feature type's seconds. objects: grams per object instance, with its `object_list` index when its name is " - "unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, " - "and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file " - "opened for viewing reads the same.", - object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index; default the current plate."}}}, - {"include", array_prop({{"type", "string"}, {"enum", json::array({"features", "layers", "layer_features", "objects", "view"})}}, - "Parts besides the summary; default `[\"features\", \"view\"]`.")}, - {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 1000}, {"description", "Layers per page (default 100)."}}}, - {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [](const json& args, ToolContext& ctx) { - const std::set parts = args.contains("include") ? args["include"].get>() : - std::set{"features", "view"}; - return ToolResult::ok(ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - if (plater.printer_technology() != ptFFF) - throw ToolFailure("The Preview needs an FFF printer"); - // The background process may be rewriting a result whatever its valid flag says. - if (plater.is_slicing_any()) - throw ToolFailure("Slicing is in progress; app_wait {\"for\": \"idle\"} first"); - PartPlateList& plates = plater.get_partplate_list(); - const int current = plates.get_curr_plate_index(); - const int index = arg_int(args, "plate", current); - if (index >= plates.get_plate_count()) - throw ToolFailure(no_such_plate(index, plates.get_plate_count())); - GLCanvas3D* canvas = plater.get_preview_canvas3D(); - if (canvas == nullptr) - throw ToolFailure("The preview is not available"); - PartPlate* plate = plates.get_plate(index); - const GCodeProcessorResult* result = plate->get_slice_result(); - const bool shown = index == current && viewer_holds(canvas->get_gcode_viewer(), result); - // A G-code file opened for viewing fills the current plate's result, which the Preview - // shows, without marking the plate sliced. - const bool gcode_file = plater.only_gcode_mode() && shown; - const std::string name = "Plate " + std::to_string(index); - const std::string slice_it = "plate_slice {\"plates\": " + std::to_string(index) + "}"; - if (result == nullptr || !(plate->is_slice_result_valid() || gcode_file)) - throw ToolFailure(name + " has no up-to-date slice; " + slice_it + " first"); - // Of a project opened from a sliced 3MF, a plate the Preview has not shown keeps only the file's totals. - if (result->moves.empty()) - throw ToolFailure(name + " has no toolpaths, only the totals of a sliced 3MF; " + slice_it + " again for layer data"); - - const json statistics = json::parse(gcode_statistics_json(*result)); - const json& totals = statistics.at("summary"); - json summary = plate_summary(statistics, *result); - summary["prepare_time_s"] = std::lround(totals.at("prepare_time").get()); - summary["travel_time_s"] = std::lround(totals.at("travel_time").get()); - summary["travel_mm"] = std::lround(totals.at("travel_distance").get()); - json out{{"plate", index}, {"summary", std::move(summary)}}; - if (parts.count("features") > 0) - out["features"] = preview_features(statistics); - if (parts.count("layers") > 0 || parts.count("layer_features") > 0) - out["layers"] = page(preview_layers(statistics, parts.count("layer_features") > 0), args, 100); - if (parts.count("objects") > 0) { - std::vector names; - for (const ModelObject* object : plater.model().objects) - names.push_back(object->name); - out["objects"] = preview_objects(statistics, names); - } - if (parts.count("view") > 0) { - out["view"] = shown ? preview_view(*canvas) : json(); - if (index != current) - out["note"] = "The Preview shows plate " + std::to_string(current) + "; show plate " + std::to_string(index) + - " there (plate_select {\"plate\": " + std::to_string(index) + "}) to read its legend"; - else if (!shown) - out["note"] = "The Preview has not loaded this plate's toolpaths; show it with view_set {\"tab\": \"preview\"}"; - } - return out; - })); - })); + // The Agent Activity pane's menu item, which has no argument form. + const std::string activity = "Show or hide the Agent Activity pane, where a person watches what agents, Action Replay, Run Script, " + "the command line's run and plugins do in the app, call by call. It is the person's: it lists your " + "calls, and you never need it."; + NativeCommand toggle_activity = menu_command("view_toggle_activity_panel", L("Agent Activity"), activity, object_schema({}), + json::array({action("toggle_agent_activity_panel", L("Agent Activity"), L("View"), "", + json::object(), activity)}), + [](const json&) { return MenuItems::toggle_agent_activity_panel(); }); + // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. + toggle_activity.listed = false; + catalog.add(std::move(toggle_activity)); // The legend combo's view types; the first-layer inspection type has no name and no combo entry. std::vector view_types; @@ -965,7 +907,7 @@ void register_view_tools(CommandCatalog& catalog) // Design view refuses (point_camera()), are refused here, before the tab or anything else // changes; a rebuild refuses the options, its worker holding the document the reference planes // are read from. - // With no Design panel to show or set, the refusal is cad_gate()'s (Mcp::no_design_tab()). + // With no Design panel to show or set, the refusal is design_gate()'s (Mcp::no_design_tab()). DesignPanel* design = nullptr; if (arg_string(args, "tab") == "design" && frame->m_design_page != nullptr) design = DesignPanel::ensure(); @@ -1364,16 +1306,52 @@ void register_view_tools(CommandCatalog& catalog) return MenuItems::open_window(window, preferences); })); - const std::string saved = "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless " - "they chose another) and show the person a notification naming it; the reply has its path. Agents use " - "the window_screenshot tool, which returns the image."; - NativeCommand save_screenshot = menu_command("window_save_screenshot", L("Take Screenshot"), saved, object_schema({}), - json::array({NativeCommands::action("take_screenshot", L("Take Screenshot"), - L("Commands"), "screenshot", json::object(), saved)}), - [](const json&) { return MenuItems::take_screenshot(); }); - // A menu item with no argument form: tool_list lists it and tool_call runs it, the tool list does not show it. - save_screenshot.listed = false; - catalog.add(std::move(save_screenshot)); + catalog.add(inspect_tool( + "window_list", L("List the windows"), + "List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an " + "object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the " + "topmost last. A window's ref goes to `window_screenshot` as target to capture that window, to `widget_list` as target to " + "list it alone, and to `keyboard_press` as target; its title is the within of locators for its widgets.\n" + "Reply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, " + "ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state " + "(normal, maximized or minimized) and resizable (it has a resize border); `window_set` changes them.\n" + "A native dialog (a message box, a file picker) has `native: true` and no ref: `dialog_answer` answers it. `hidden: " + "true` marks the person's own windows (the Run Script panel floating, its prompts and Action Replay's, the Python " + "scripts setting), which no tool reaches and screenshots leave out.", + object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 100."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { + AutomationRuntime& runtime = ctx.runtime(); + return ToolResult::ok(page(ctx.run_ui([&] { return runtime.inspector().windows(); }), args)); + })); + + { + NativeCommand def = recover_input_tool( + "window_set", L("Size, move or raise a window"), + "Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one " + "`window_list` lists, also while a modal dialog is open. Size the main window before `view_set` fits the camera and " + "before `recording_start`, as a recording keeps its first frame's size. size and position are in the units " + "`window_list` reports, whose x/y and width/height are read as position and size too. A size or position restores " + "a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog " + "never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn " + "at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per " + "window unit), display (its work area), active with raise, and adjusted with a note: what the OS or a size limit " + "changed.", + object_schema({{"target", {{"type", json::array({"string", "object"})}, + {"description", "main (default), dialog (the topmost modal " + "dialog), or a window's ref or locator from `window_list`; a widget's ref or " + "locator picks the window it is in."}}}, + {"size", array_prop({{"type", "integer"}}, "`[width, height]`, held to the window's minimum and maximum size.")}, + {"position", array_prop({{"type", "integer"}}, "`[x, y]` of the window's top-left corner on screen; not on Wayland.")}, + {"state", enum_prop({"normal", "maximized", "minimized"}, + "normal restores a maximized or minimized window; maximized and minimized take no size " + "or position.")}, + {"raise", prop("boolean", "Bring the window in front of the app's other windows; active in the reply says " + "whether it became the active one.")}}), + [](const json& args, ToolContext& ctx) { return set_window(ctx.runtime(), ctx, args); }); + def.allowed_during_operation = true; + catalog.add(def); + } } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index f4e198d8a2..48f133ac68 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -2998,7 +2998,7 @@ std::vector> UiInspector::match_tabs(const json& json UiInspector::locator_for(const UiTarget& t) { - // A page element's locator comes from its page, which the tool asks (see McpToolsUi.cpp). + // A page element's locator comes from its page, which the tool asks (see Tools/GuiTools.cpp). if (t.kind == UiTarget::Kind::WebElement) return t.locator; json loc = t.locator; diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index 5a225e9917..9ff687e06f 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -45,7 +45,7 @@ #include "Mcp/McpTools.hpp" #ifdef SLIC3R_CAD #include "CAD/DesignPanel.hpp" -#include "Mcp/McpToolsCad.hpp" +#include "Mcp/McpToolsDesign.hpp" #endif #include "Mcp/RecordingSettings.hpp" #include "Mcp/ScreenCapture.hpp" @@ -773,7 +773,7 @@ AppActionRunResult MenuItems::toggle_developer_mode() // ---- The app ---- // The Design tab's history is "design", else "project". Without args.history it is the shown tab's, as the Edit menu's -// Undo and Redo choose it. The reply says which history it was and, for the Design tab's, what Mcp::cad_undo_redo() +// Undo and Redo choose it. The reply says which history it was and, for the Design tab's, what Mcp::design_undo_redo() // replies. AppActionRunResult MenuItems::undo_redo(const json& args, bool redo) { @@ -787,7 +787,7 @@ AppActionRunResult MenuItems::undo_redo(const json& args, bool redo) } if (history == "design") { #ifdef SLIC3R_CAD - json reply{{"history", "design"}, {"result", Mcp::cad_undo_redo(redo)}}; + json reply{{"history", "design"}, {"result", Mcp::design_undo_redo(redo)}}; return {AppActionRunResult::Level::Succeeded, {}, true, reply.dump()}; #else throw ToolFailure("The CAD feature is off: this build of OrcaSlicer has no Design tab"); @@ -1100,8 +1100,8 @@ const char* NativeCommands::place_heading(const std::string& key) void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unused]] const CatalogOptions& options) { - // The families' commands are gathered first, so that each takes its place's group and its place in the order - // (list_rank()), whichever family declares it; a stable sort keeps a place's commands in their families' order. + // The places' commands are gathered first, so that each takes its place's group and its place in the order + // (list_rank()); a stable sort keeps a place's commands in the order its file adds them. // The Design tab's commands, only while the CAD feature is on, go before the GUI-driving ones; tool_list's // description names them then, and undo's and redo's examples show the Design tab's history. std::string design_index; @@ -1109,29 +1109,24 @@ void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unus if (options.cad) design_index = Mcp::design_command_index(); #endif - // The families register into a catalog of their own, which keeps only their commands for the sort: a source or a + // The places register into a catalog of their own, which keeps only their commands for the sort: a source or a // left-out record added to it would be lost with it. So the plugin operations' source is added to `catalog` apart // (register_plugin_operations()), as are the Design commands and their left-out records. - CommandCatalog families; - Mcp::register_app_tools(families, options.cad); - Mcp::register_api_tools(families, design_index); - Mcp::register_project_tools(families); - Mcp::register_config_tools(families); - Mcp::register_preference_tools(families); - Mcp::register_install_tools(families); - Mcp::register_scene_tools(families); - Mcp::register_gizmo_tools(families); - Mcp::register_printer_tools(families); - Mcp::register_layer_tools(families); - Mcp::register_view_tools(families); - Mcp::register_plugin_tools(families); - Mcp::register_replay_tools(families); - Mcp::register_python_tools(families); - Mcp::register_record_tools(families); - Mcp::register_action_tools(families); - Mcp::register_ui_tools(families); + CommandCatalog places; + Mcp::register_catalog_tools(places, design_index); + Mcp::register_app_tools(places, options.cad); + Mcp::register_project_tools(places); + Mcp::register_object_tools(places); + Mcp::register_plate_tools(places); + Mcp::register_preset_tools(places); + Mcp::register_filament_tools(places); + Mcp::register_printer_tools(places); + Mcp::register_plugin_tools(places); + Mcp::register_view_tools(places); + Mcp::register_recording_tools(places); + Mcp::register_gui_tools(places); - std::vector placed(families.commands().begin(), families.commands().end()); + std::vector placed(places.commands().begin(), places.commands().end()); for (NativeCommand& command : placed) { const char* heading = place_heading(command.key); if (heading == nullptr) @@ -1147,9 +1142,9 @@ void NativeCommands::register_all_commands(CommandCatalog& catalog, [[maybe_unus catalog.add(std::move(*it)); #ifdef SLIC3R_CAD if (options.cad) - Mcp::register_cad_commands(catalog); + Mcp::register_design_tools(catalog); else - Mcp::leave_out_cad_commands(catalog, options.editor); + Mcp::leave_out_design_tools(catalog, options.editor); #endif for (auto it = gui; it != placed.end(); ++it) catalog.add(std::move(*it)); diff --git a/src/slic3r/GUI/NativeCommands.hpp b/src/slic3r/GUI/NativeCommands.hpp index bd942e9d56..4c48285402 100644 --- a/src/slic3r/GUI/NativeCommands.hpp +++ b/src/slic3r/GUI/NativeCommands.hpp @@ -29,16 +29,16 @@ struct CatalogOptions bool editor = true; }; -// Adds the built-in commands to `catalog`, family by family (Mcp::register_app_tools() and the others): the typed +// Adds the built-in commands to `catalog`, place by place (Mcp::register_app_tools() and the others): the typed // tools and the commands made from menu items (MenuItems, NativeCommandMenuItems.hpp), whose items are their actions, eight of them // with an action of their own (has_own_action). Each is in the group of its place (place_heading()) and is listed, as it runs // from its arguments, but for the three menu items that take none (window_save_screenshot, script_toggle_panel, // settings_toggle_developer_mode). They come in the order tools/list gives them: tool_list, tool_describe, tool_call and app_state, // then place by place (Tools and actions, The app, The project, Objects, Parts, Plates and on), each place's commands -// in the order their families declare them, and Driving the GUI last. Before Driving the GUI, with options.cad, the Design tab's commands -// (Mcp::register_cad_commands()), not listed, of which those with a handler have an action the Speed Dial shows in the +// in the order their place's file adds them, and Driving the GUI last. Before Driving the GUI, with options.cad, the Design tab's commands +// (Mcp::register_design_tools()), not listed, of which those with a handler have an action the Speed Dial shows in the // Design tab; without it, in a build with CAD, it records that it leaves them out and why -// (Mcp::leave_out_cad_commands()). undo and redo act on the Design tab's history or the project's, a person's pick +// (Mcp::leave_out_design_tools()). undo and redo act on the Design tab's history or the project's, a person's pick // as the Edit menu's item does; with options.cad their examples show the Design tab's. Also adds the source of the // operations the loaded plugins offer (Mcp::register_plugin_operations()). void register_all_commands(CommandCatalog& catalog, const CatalogOptions& options); diff --git a/tests/libslic3r/test_caddocument.cpp b/tests/libslic3r/test_caddocument.cpp index d6bdbca520..0f23a30c11 100644 --- a/tests/libslic3r/test_caddocument.cpp +++ b/tests/libslic3r/test_caddocument.cpp @@ -5198,7 +5198,7 @@ TEST_CASE("unknown identifier fails recompute", "[CadDocument][variables]") } // The checkpoint -> mutate -> recompute -> undo-on-failure pattern is what both the GUI and -// Mcp/McpToolsCad.cpp use to keep a bad edit out of the document. It only works if the snapshot +// the Design commands (Mcp/Tools/Design*.cpp) use to keep a bad edit out of the document. It only works if the snapshot // covers `variables` as well as `features`: an undo() that restored features alone would let a bad // variable survive the rollback, and every later recompute would fail — the document left unusable. TEST_CASE("undo rolls back a bad variable, not just features", "[CadDocument][variables]") diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index 73f4626c00..3e183588da 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -510,6 +510,51 @@ TEST_CASE("the commands outside the Design tab are the design's, under its headi CHECK(heading_of("") == "(none)"); } +TEST_CASE("each place's file adds only its place's commands", "[CommandCatalog]") +{ + // Each file under Mcp/Tools/ holds one place's commands (ObjectTools.cpp two); the catalog groups a command by its + // key wherever it is added, so only this keeps a command out of another place's file. + struct PlaceFile + { + const char* file; + void (*add)(CommandCatalog&); + std::set headings; + }; + const std::vector files{ + {"CatalogTools.cpp", [](CommandCatalog& c) { Mcp::register_catalog_tools(c, ""); }, {"Tools and actions"}}, + {"AppTools.cpp", [](CommandCatalog& c) { Mcp::register_app_tools(c, false); }, {"The app"}}, + {"ProjectTools.cpp", Mcp::register_project_tools, {"The project"}}, + {"ObjectTools.cpp", Mcp::register_object_tools, {"Objects", "Parts"}}, + {"PlateTools.cpp", Mcp::register_plate_tools, {"Plates"}}, + {"PresetTools.cpp", Mcp::register_preset_tools, {"Presets and settings"}}, + {"FilamentTools.cpp", Mcp::register_filament_tools, {"Filaments"}}, + {"PrinterTools.cpp", Mcp::register_printer_tools, {"Printers and prints"}}, + {"PluginTools.cpp", Mcp::register_plugin_tools, {"Plugins"}}, + {"ViewTools.cpp", Mcp::register_view_tools, {"View and windows"}}, + {"RecordingTools.cpp", Mcp::register_recording_tools, {"Recordings, replays and scripts"}}, + {"GuiTools.cpp", Mcp::register_gui_tools, {"Driving the GUI"}}, + }; + std::set added; + for (const PlaceFile& place : files) { + INFO(place.file); + CommandCatalog catalog; + place.add(catalog); + CHECK_FALSE(catalog.commands().empty()); + for (const NativeCommand& c : catalog.commands()) { + INFO(c.key); + const char* heading = NativeCommands::place_heading(c.key); + REQUIRE(heading != nullptr); + CHECK(place.headings.count(heading) == 1); + CHECK(added.insert(c.key).second); + } + } + // Together the files add every place's commands. + std::set expected; + for (const auto& [heading, keys] : kPlaces) + expected.insert(keys.begin(), keys.end()); + CHECK(added == expected); +} + TEST_CASE("every command that runs from arguments is in the tool list, by place", "[CommandCatalog]") { const CommandCatalog& catalog = NativeCommands::instance(); diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index da4d279cbc..416c176e0f 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -39,7 +39,7 @@ #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/McpArguments.hpp" #include "slic3r/GUI/Mcp/McpTools.hpp" -#include "slic3r/GUI/Mcp/McpToolsCad.hpp" +#include "slic3r/GUI/Mcp/McpToolsDesign.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "retired_names.hpp" #include "test_utils.hpp" @@ -195,7 +195,7 @@ void add_bound_block(CadDocument& doc) GUI::CommandCatalog cad_catalog() { GUI::CommandCatalog catalog; - GUI::Mcp::register_cad_commands(catalog); + GUI::Mcp::register_design_tools(catalog); catalog.seal(); return catalog; } @@ -464,10 +464,10 @@ TEST_CASE("every block has a silent function and every silent function a block", for (int i = 0; i < GUI::kDesignToolCount; ++i) if (GUI::kDesignTools[i].doc != nullptr) blocks.insert(GUI::kDesignTools[i].id); - for (std::size_t i = 0; i < GUI::Mcp::kSilentFormCount; ++i) { - INFO(GUI::Mcp::kSilentForms[i].first); - CHECK(functions.insert(GUI::Mcp::kSilentForms[i].first).second); - CHECK(GUI::Mcp::kSilentForms[i].second != nullptr); + for (const auto& [id, run] : GUI::Mcp::silent_forms()) { + INFO(id); + CHECK(functions.insert(id).second); + CHECK(run != nullptr); } CHECK(blocks.size() == 83); CHECK(blocks == functions); @@ -659,7 +659,7 @@ TEST_CASE("a folded item opens only in its own mode", "[Mcp][CAD]") TEST_CASE("a tool block's schema refuses an argument it does not name", "[Mcp][CAD]") { const json block{{"params", json::array({{{"name", "radius"}, {"type", "number"}, {"default", 1}}})}}; - const json schema = GUI::Mcp::cad_input_schema(block); + const json schema = GUI::Mcp::design_input_schema(block); CHECK(schema.at("additionalProperties") == false); CHECK_THAT(GUI::Mcp::validate_arguments(schema, {{"radius", 2}, {"edge", 3}}), ContainsSubstring("unknown argument edge")); // What it names, the generation among them, it takes. @@ -1353,22 +1353,22 @@ TEST_CASE("a CAD call's generation is any integer of 0 or more, signed or unsign { // A script's or plugin's Python integers reach the command as signed JSON integers, which must read as the same // generation a reply gave. - CHECK_FALSE(GUI::Mcp::cad_generation(json::object()).has_value()); - CHECK_FALSE(GUI::Mcp::cad_generation(json()).has_value()); - CHECK(GUI::Mcp::cad_generation({{"generation", std::uint64_t(7)}}) == std::optional(7)); - CHECK(GUI::Mcp::cad_generation({{"generation", std::int64_t(7)}}) == std::optional(7)); - CHECK(GUI::Mcp::cad_generation({{"generation", std::int64_t(0)}}) == std::optional(0)); + CHECK_FALSE(GUI::Mcp::design_generation(json::object()).has_value()); + CHECK_FALSE(GUI::Mcp::design_generation(json()).has_value()); + CHECK(GUI::Mcp::design_generation({{"generation", std::uint64_t(7)}}) == std::optional(7)); + CHECK(GUI::Mcp::design_generation({{"generation", std::int64_t(7)}}) == std::optional(7)); + CHECK(GUI::Mcp::design_generation({{"generation", std::int64_t(0)}}) == std::optional(0)); // A whole number written as a float passes the schema's integer type, so it counts too. - CHECK(GUI::Mcp::cad_generation({{"generation", 7.0}}) == std::optional(7)); + CHECK(GUI::Mcp::design_generation({{"generation", 7.0}}) == std::optional(7)); // The largest unsigned integer is a generation. A float is one where the schema's integer type takes it, below 2^63 // (is_whole_number()), so the call and a caller that skips the schema read the same numbers. - CHECK(GUI::Mcp::cad_generation({{"generation", std::uint64_t(18446744073709551615ull)}}) == + CHECK(GUI::Mcp::design_generation({{"generation", std::uint64_t(18446744073709551615ull)}}) == std::optional(18446744073709551615ull)); - CHECK(GUI::Mcp::cad_generation({{"generation", 9.0e18}}) == std::optional(9000000000000000000ull)); + CHECK(GUI::Mcp::design_generation({{"generation", 9.0e18}}) == std::optional(9000000000000000000ull)); for (const json& bad : {json(std::int64_t(-1)), json(-1.0), json("7"), json(7.5), json(nullptr), json(9.3e18), json(9223372036854775808.0), json(18446744073709551616.0), json(1.0e300)}) { INFO(bad.dump()); - CHECK(failure_code([&] { GUI::Mcp::cad_generation({{"generation", bad}}); }) == "invalid_argument"); + CHECK(failure_code([&] { GUI::Mcp::design_generation({{"generation", bad}}); }) == "invalid_argument"); } } @@ -1881,7 +1881,7 @@ TEST_CASE("the tool_list description names every Design command under its headin TEST_CASE("a Design reply keeps a rejected rebuild's ok false and its error", "[Mcp][CAD]") { const json rejected{{"ok", false}, {"replaced", false}, {"error", "the sketch was not replaced: open profile"}}; - const GUI::NativeCommand finish = GUI::Mcp::cad_command("sketch_finish", "Finish sketch", + const GUI::NativeCommand finish = GUI::Mcp::design_command("sketch_finish", "Finish sketch", json{{"type", "object"}, {"properties", json::object()}}, [&rejected](const json&, bool) { return rejected; }); JournalContext agent; @@ -1893,7 +1893,7 @@ TEST_CASE("a Design reply keeps a rejected rebuild's ok false and its error", "[ TEST_CASE("a CAD call is journaled without its generation and with its silent", "[Mcp][CAD]") { json seen; - const GUI::NativeCommand fillet = GUI::Mcp::cad_command("fillet", "Fillet", json{{"type", "object"}, {"properties", json::object()}}, + const GUI::NativeCommand fillet = GUI::Mcp::design_command("fillet", "Fillet", json{{"type", "object"}, {"properties", json::object()}}, [&seen](const json& args, bool) { seen = args; return json{{"ok", true}, {"error", ""}, {"feature_index", 3}}; @@ -1917,7 +1917,7 @@ TEST_CASE("a CAD call is journaled without its generation and with its silent", // A call that ran and gave nothing but its generation is journaled silent when a call with no arguments // opens a tool: its replay, given none, would open the tool. - const GUI::NativeCommand shell = GUI::Mcp::cad_command( + const GUI::NativeCommand shell = GUI::Mcp::design_command( "shell", "Shell", GUI::Mcp::with_silent(json{{"type", "object"}, {"properties", json::object()}}), [](const json&, bool) { return json{{"ok", true}}; }, [](const json& args) { return GUI::Mcp::person_form(args); }); JournalContext generation_only; @@ -1939,7 +1939,7 @@ TEST_CASE("a CAD call is journaled without its generation and with its silent", CHECK(cut.journaled == json{{"operation", "cut"}, {"silent", true}}); // A failure is the call's error. - const GUI::NativeCommand refused = GUI::Mcp::cad_command("hole", "Hole", json{{"type", "object"}, {"properties", json::object()}}, + const GUI::NativeCommand refused = GUI::Mcp::design_command("hole", "Hole", json{{"type", "object"}, {"properties", json::object()}}, [](const json&, bool) -> json { throw GUI::ToolFailure("removed no material", {{"code", "rebuild_failed"}}); }); @@ -1951,7 +1951,7 @@ TEST_CASE("a CAD command tells its function a person's pick from a call", "[Mcp] // The four menu items that act on the Feature list's row are not refused for the selection on a call, and a person's // pick keeps the menu's rule: the function is told which it runs for. std::vector told; - const GUI::NativeCommand rename = GUI::Mcp::cad_command("rename_selected", "Rename", json{{"type", "object"}, {"properties", json::object()}}, + const GUI::NativeCommand rename = GUI::Mcp::design_command("rename_selected", "Rename", json{{"type", "object"}, {"properties", json::object()}}, [&told](const json&, bool person) { told.push_back(person); return json{{"ok", true}}; @@ -1983,7 +1983,7 @@ bool takes_arg(const GUI::NativeCommand& command, const std::string& key) if (key.size() <= suffix.size() || key.compare(key.size() - suffix.size(), suffix.size(), suffix) != 0) return false; const auto radians = properties.find(key.substr(0, key.size() - suffix.size())); if (radians == properties.end()) return false; - // cad_input_schema() writes a param's unit into its description. + // design_input_schema() writes a param's unit into its description. const std::string description = radians->value("description", std::string()); const std::string unit = " (rad)"; return description == "In rad." || diff --git a/tests/slic3rutils/test_operations.cpp b/tests/slic3rutils/test_operations.cpp index 1e5266d12c..e2f0ec52c9 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -2220,7 +2220,7 @@ TEST_CASE("the exception list names only commands the catalog has under the rule } // The Design tab's commands act on its document, which no operation stands for, as -// scripts/check_operation_calls.py leaves McpToolsCad.cpp out. +// scripts/check_operation_calls.py leaves their files, Mcp/Tools/Design*.cpp, out. TEST_CASE("the operations rule leaves the Design group and the read-only commands out", "[Operations]") { Slic3r::GUI::NativeCommand shell; diff --git a/tools/mcp/test-entries/commands.md b/tools/mcp/test-entries/commands.md index d9eba25068..8b54726980 100644 --- a/tools/mcp/test-entries/commands.md +++ b/tools/mcp/test-entries/commands.md @@ -41,7 +41,7 @@ An action is its command run with fixed arguments as a person's pick, and `actio - The calibration's project beyond its name and an object: the test's objects and the settings it changes are `test_presets`' calibration scenarios'. **To settle in review:** -- That a calibration action's journal step has the id alone, not `{"test": ""}`. The action runs its command's person form (`NativeCommands::with_person_form()`), which opens the test's dialog and journals nothing; only `calibration_generate_test`'s own run, with parameters or `silent`, calls `set_journal_args`, and `ActionContext` puts the action's fixed arguments in the step only in place of such a rewrite. Both are this branch's code (`McpToolsProject.cpp`, `McpPersonContext.hpp`, not on `main`). The step with the id alone replays the same, since the action supplies `test`. +- That a calibration action's journal step has the id alone, not `{"test": ""}`. The action runs its command's person form (`NativeCommands::with_person_form()`), which opens the test's dialog and journals nothing; only `calibration_generate_test`'s own run, with parameters or `silent`, calls `set_journal_args`, and `ActionContext` puts the action's fixed arguments in the step only in place of such a rewrite. Both are this branch's code (`Tools/PlateTools.cpp`, `McpPersonContext.hpp`, not on `main`). The step with the id alone replays the same, since the action supplies `test`. **Strength:** Partial — the handy model, the rear view and Go to tab have their effect read back exactly, the calibration loosely, the window only by its title and the screenshot by its file; every action is listed with its command, and the journal step is pinned exactly for every row that runs. @@ -69,7 +69,7 @@ An action is its command run with fixed arguments as a person's pick, and `actio - `and takes no undo snapshot` reads the info-level log through `ops_undo.py`. It would pass if snapshots stopped being logged; the Duplicate Plate count-1 check in the same run would catch that. **To settle in review:** -- The notices the pairs share are regular notices, not error notices that never fade: `menu_info()` (`McpToolsScene.cpp`, from commits not on `main`) answers `too_few_objects` and `one_object_only` as information, as the menu items told them, since the person can select something else and pick again. So the first notice may fade before the second pick, and the close step then finds nothing; "the earlier notice is closed" still reads the text gone before the second pick, and that pick's own check reads it shown again. +- The notices the pairs share are regular notices, not error notices that never fade: `menu_info()` (`Tools/ObjectTools.cpp`, from commits not on `main`) answers `too_few_objects` and `one_object_only` as information, as the menu items told them, since the person can select something else and pick again. So the first notice may fade before the second pick, and the close step then finds nothing; "the earlier notice is closed" still reads the text gone before the second pick, and that pick's own check reads it shown again. - Reaching the close button through a refusal's count is roundabout. Naming the button in the app (`record_named_item` on the close button in `render_close_button()`) would let the test click it by name; that is a change to the app. **Strength:** Strong — refusal codes and the state after each refusal are compared exactly, and each pick's notice is its own; only a few picks rest on notice text alone. diff --git a/tools/mcp/test-entries/files.md b/tools/mcp/test-entries/files.md index 174f515914..f6d6c40fff 100644 --- a/tools/mcp/test-entries/files.md +++ b/tools/mcp/test-entries/files.md @@ -339,7 +339,7 @@ refusal with other words fails at once. - An object index the project lacks (exporting meshes, step 7) is refused by the target check, `IndexCheck::object()` (`src/slic3r/GUI/Mcp/McpTargets.cpp`), with "object index 5 is out of range" and no code, before `Ops::export_objects_refusal()` runs, so the export's own refusal for it, `no_such_object`, never answers. The - fix: `project_export`'s handler (`src/slic3r/GUI/Mcp/McpToolsProject.cpp`) runs `Ops::export_objects_refusal()` on + fix: `project_export`'s handler (`src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp`) runs `Ops::export_objects_refusal()` on the indices `objects` gives before `resolve_targets()`. The step expects the fixed behaviour: `no_such_object`, "Object 5 does not exist (the project has objects 0..1)". - `project_import` of model files leaves an untitled project named `Untitled`, while File > Import names it after the diff --git a/tools/mcp/test-entries/gui_tools.md b/tools/mcp/test-entries/gui_tools.md index 714c7ce9d0..1018150046 100644 --- a/tools/mcp/test-entries/gui_tools.md +++ b/tools/mcp/test-entries/gui_tools.md @@ -318,7 +318,7 @@ stored state (see **To settle**). The start is checked: the project's `curr_bed_ Close element by their ids, and the top list's column headings as text; its auto-update switch is commented out of the page, and its bundle lists, which hold what the data folder holds, are not read. - The web view a script runs in (web dialogs, steps 1 to 9 and 28): `webview_run_javascript` without a target takes - the topmost modal's web view, else the only one shown (`default_webview()` in `McpToolsUi.cpp`), and refuses a web + the topmost modal's web view, else the only one shown (`default_webview()` in `Tools/GuiTools.cpp`), and refuses a web view in a dialog under the topmost, or behind a modal, before it runs (`guard_page()`); no dialog is named there. The Flushing volumes dialog (steps 27 to 29) runs that same code as step 4; it stays as the one web dialog here whose web view the app makes with `wxWebView::New` (`WipingDialog`), where the bundle dialogs' come from @@ -354,7 +354,7 @@ stored state (see **To settle**). The start is checked: the project's `curr_bed_ printer page holds beyond the card step 25 ticks. - The printers other tests installed: the printer list is read for the one printer the wizard's card names. - Closing a dialog from its page by a script (`webview_run_javascript` clicking `#close_btn`): it takes the branch - step 10's click takes. Both tools follow their page call with `observe_page()` (`McpToolsUi.cpp`), which replies + step 10's click takes. Both tools follow their page call with `observe_page()` (`Tools/GuiTools.cpp`), which replies `closed` once the dialog leaves the modal stack, so step 10 covers it. - How soon the page's Close is told (web dialogs, step 10): the web view's destruction ends the click's wait for its page (`PageCalls` in `WebPages.cpp`), and without that the click is refused after its 10 s, so the reply's `closed` @@ -481,7 +481,7 @@ The default limit of an hour is step 1 of the first scenario (`max_seconds` 3600 and a skipped check is not counted among the checks. - Typed keys leave a setting's field as it was (first scenario, step 6): `keyboard_press` sends key events to the field's `TextInput`, which a native text control does not take as typing; its description says typing reaches - ImGui fields and key handlers and sends a widget's text field to `widget_set_value` (`McpToolsUi.cpp`, this + ImGui fields and key handlers and sends a widget's text field to `widget_set_value` (`Tools/GuiTools.cpp`, this branch's d64e10f4dd). The step stays as the recording's typed caption, and step 8 shows that the first layer kept its 0.2 mm while the layer height set by `widget_set_value` took effect. - A recording's first frame is the size `window_screenshot` captures of the same target (`MAIN`, `CANVAS`): both diff --git a/tools/mcp/test-entries/objects.md b/tools/mcp/test-entries/objects.md index dd35558be0..2f8de00c25 100644 --- a/tools/mcp/test-entries/objects.md +++ b/tools/mcp/test-entries/objects.md @@ -667,7 +667,7 @@ unscaled and not mirrored, and a plate's settings as in a plate's own settings. it. Without that bound the step shows only that the spacing was taken. - The arrange options an arrange stores (arranging, steps 4 and 7; cloning, steps 3 and 6). An arrange given `spacing`, `rotate` or `multi_material` stores the panel's options (`start_arrange()` in - `src/slic3r/GUI/Mcp/McpToolsScene.cpp` calls `GLCanvas3D::store_arrange_settings()`), and every arrange after takes + `src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp` calls `GLCanvas3D::store_arrange_settings()`), and every arrange after takes them, Clone's among them (`Ops::clone_objects()` arranges with `Plater::arrange()`), so step 4's options are the ones cloning arranges with until arranging's later steps change the spacing. - The plate an arrange of one plate or a Fill bed leaves current (arranging, steps 14 and 17): `Ops::start_arrange()` @@ -699,13 +699,13 @@ unscaled and not mirrored, and a plate's settings as in a plate's own settings. meshes' centres in their files, (10, 10, 5) here, for an instance that is neither turned nor scaled. The cylinder's centre is (0, 0, 5) only to its facets, hence 0.05. - A reload that finds only missing files takes no undo step (files, step 6): `Ops::reload_parts()` reloads nothing, - so it takes no snapshot. `object_reload_from_disk`'s description (`register_object_tools()` in - `src/slic3r/GUI/Mcp/McpToolsScene.cpp`) and the comment on `reload_parts()` in + so it takes no snapshot. `object_reload_from_disk`'s description (`register_actionless_object_commands()` in + `src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp`) and the comment on `reload_parts()` in `src/slic3r/GUI/Operations/ObjectOps.hpp` say so: one undo step, none when every part's file is missing. - An order the objects already have takes no undo step (ordering, steps 13 and 14): `Ops::reorder_objects()` takes its snapshot only when it moves an object, as `ObjectList::order_objects()`, the app's own code, takes one only when the order changes. `object_order`'s description (`register_object_menu_commands()` in - `src/slic3r/GUI/Mcp/McpToolsScene.cpp`) and the comments on `order_objects()` and `reorder_objects()` in + `src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp`) and the comments on `order_objects()` and `reorder_objects()` in `src/slic3r/GUI/Operations/ObjectOps.hpp` say so: one undo step, none when the order stays as it was. - The words of `part_add`'s refusals (parts, steps 8 and 9) carry no code, so they are matched by their text. A shape's size names the fields of Add Primitive's size dialog (`primitive_size_names()`), so a cylinder's is diff --git a/tools/mcp/test-entries/slice_preview.md b/tools/mcp/test-entries/slice_preview.md index 6ac2872c66..c36899790b 100644 --- a/tools/mcp/test-entries/slice_preview.md +++ b/tools/mcp/test-entries/slice_preview.md @@ -391,7 +391,7 @@ checked not to be a person's own folder (`APPDATA` or `~` plus `OrcaSlicer`), wh **To settle in review:** - A layer asked of a Preview with none (nothing to slice, steps 1, 2 and 11; the layers, step 21) still shows the Preview tab before it is refused, and an arrange refused for its plate (plate index, step 16) still shows Prepare. - Both are this branch's code (`view_set` in `McpToolsView.cpp` and `start_arrange()` in `McpToolsScene.cpp`, commit + Both are this branch's code (`view_set` in `Tools/ViewTools.cpp` and `start_arrange()` in `Tools/ObjectTools.cpp`, commit d64e10f4dd, not on `main`) and both are its design, not a bug: a field of the Preview shows the Preview, as a person's Go to layer pick does, and an arrangement runs on Prepare, as the toolbar's Arrange does. The rows expect that tab. @@ -410,10 +410,10 @@ checked not to be a person's own folder (`APPDATA` or `~` plus `OrcaSlicer`), wh `plate_slice_stats` and `plate_set_custom_gcode`, whose text is the same. A refusal without a code is not a bug: those are matched by their words. - A `plates` string other than "all" taken as the current plate (plate index, step 4). A bug in this branch's code, - fixed when the test is written: `plate_slice`'s handler (`McpToolsScene.cpp`, commit 0616068e26) and - `project_export`'s (`McpToolsProject.cpp`, commits dc522e59e4 and 5e5571a99f), none on `main`, read `{plates: + fixed when the test is written: `plate_slice`'s handler (`Tools/PlateTools.cpp`, commit 0616068e26) and + `project_export`'s (`Tools/ProjectTools.cpp`, commits dc522e59e4 and 5e5571a99f), none on `main`, read `{plates: "abc"}` as the current plate. The fix, in both handlers: refuse a string other than "all" and "current" with - `object_arrange`'s words, `plates is "all", "current" or a plate index` (`start_arrange()`, `McpToolsScene.cpp`), + `object_arrange`'s words, `plates is "all", "current" or a plate index` (`start_arrange()`, `Tools/ObjectTools.cpp`), before anything changes. The row expects that refusal from all three commands. - The two-colour slice (statistics, step 4) changes filament once a layer: the tool order puts each layer's last filament first on the next, so 100 changes and one tool line a layer. The replay this takes the place of checked diff --git a/tools/mcp/test-entries/windows_web.md b/tools/mcp/test-entries/windows_web.md index c3a481d876..591fda983a 100644 --- a/tools/mcp/test-entries/windows_web.md +++ b/tools/mcp/test-entries/windows_web.md @@ -31,7 +31,7 @@ mini and the ER20 are the subject, not a default: their extruders, nozzle varian checks read. The X1 Carbon is chosen for what the folder may keep, not for a behaviour of its own (see **Starts from**). -The refusals of `settings_set` on a printer each stand for one check of `McpToolsConfig.cpp`, all made before +The refusals of `settings_set` on a printer each stand for one check of `Tools/PresetTools.cpp`, all made before anything changes: | Case | Code path |